leaflet-src.js 380 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802
  1. /* @preserve
  2. * Leaflet 1.3.1, a JS library for interactive maps. http://leafletjs.com
  3. * (c) 2010-2017 Vladimir Agafonkin, (c) 2010-2011 CloudMade
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  7. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  8. (factory((global.L = {})));
  9. }(this, (function (exports) { 'use strict';
  10. var version = "1.3.1";
  11. /*
  12. * @namespace Util
  13. *
  14. * Various utility functions, used by Leaflet internally.
  15. */
  16. var freeze = Object.freeze;
  17. Object.freeze = function (obj) { return obj; };
  18. // @function extend(dest: Object, src?: Object): Object
  19. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  20. function extend(dest) {
  21. var i, j, len, src;
  22. for (j = 1, len = arguments.length; j < len; j++) {
  23. src = arguments[j];
  24. for (i in src) {
  25. dest[i] = src[i];
  26. }
  27. }
  28. return dest;
  29. }
  30. // @function create(proto: Object, properties?: Object): Object
  31. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  32. var create = Object.create || (function () {
  33. function F() {}
  34. return function (proto) {
  35. F.prototype = proto;
  36. return new F();
  37. };
  38. })();
  39. // @function bind(fn: Function, …): Function
  40. // Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
  41. // Has a `L.bind()` shortcut.
  42. function bind(fn, obj) {
  43. var slice = Array.prototype.slice;
  44. if (fn.bind) {
  45. return fn.bind.apply(fn, slice.call(arguments, 1));
  46. }
  47. var args = slice.call(arguments, 2);
  48. return function () {
  49. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  50. };
  51. }
  52. // @property lastId: Number
  53. // Last unique ID used by [`stamp()`](#util-stamp)
  54. var lastId = 0;
  55. // @function stamp(obj: Object): Number
  56. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  57. function stamp(obj) {
  58. /*eslint-disable */
  59. obj._leaflet_id = obj._leaflet_id || ++lastId;
  60. return obj._leaflet_id;
  61. /* eslint-enable */
  62. }
  63. // @function throttle(fn: Function, time: Number, context: Object): Function
  64. // Returns a function which executes function `fn` with the given scope `context`
  65. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  66. // `fn` will be called no more than one time per given amount of `time`. The arguments
  67. // received by the bound function will be any arguments passed when binding the
  68. // function, followed by any arguments passed when invoking the bound function.
  69. // Has an `L.throttle` shortcut.
  70. function throttle(fn, time, context) {
  71. var lock, args, wrapperFn, later;
  72. later = function () {
  73. // reset lock and call if queued
  74. lock = false;
  75. if (args) {
  76. wrapperFn.apply(context, args);
  77. args = false;
  78. }
  79. };
  80. wrapperFn = function () {
  81. if (lock) {
  82. // called too soon, queue to call later
  83. args = arguments;
  84. } else {
  85. // call and lock until later
  86. fn.apply(context, arguments);
  87. setTimeout(later, time);
  88. lock = true;
  89. }
  90. };
  91. return wrapperFn;
  92. }
  93. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  94. // Returns the number `num` modulo `range` in such a way so it lies within
  95. // `range[0]` and `range[1]`. The returned value will be always smaller than
  96. // `range[1]` unless `includeMax` is set to `true`.
  97. function wrapNum(x, range, includeMax) {
  98. var max = range[1],
  99. min = range[0],
  100. d = max - min;
  101. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  102. }
  103. // @function falseFn(): Function
  104. // Returns a function which always returns `false`.
  105. function falseFn() { return false; }
  106. // @function formatNum(num: Number, digits?: Number): Number
  107. // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
  108. function formatNum(num, digits) {
  109. var pow = Math.pow(10, (digits === undefined ? 6 : digits));
  110. return Math.round(num * pow) / pow;
  111. }
  112. // @function trim(str: String): String
  113. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  114. function trim(str) {
  115. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  116. }
  117. // @function splitWords(str: String): String[]
  118. // Trims and splits the string on whitespace and returns the array of parts.
  119. function splitWords(str) {
  120. return trim(str).split(/\s+/);
  121. }
  122. // @function setOptions(obj: Object, options: Object): Object
  123. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  124. function setOptions(obj, options) {
  125. if (!obj.hasOwnProperty('options')) {
  126. obj.options = obj.options ? create(obj.options) : {};
  127. }
  128. for (var i in options) {
  129. obj.options[i] = options[i];
  130. }
  131. return obj.options;
  132. }
  133. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  134. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  135. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  136. // be appended at the end. If `uppercase` is `true`, the parameter names will
  137. // be uppercased (e.g. `'?A=foo&B=bar'`)
  138. function getParamString(obj, existingUrl, uppercase) {
  139. var params = [];
  140. for (var i in obj) {
  141. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  142. }
  143. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  144. }
  145. var templateRe = /\{ *([\w_-]+) *\}/g;
  146. // @function template(str: String, data: Object): String
  147. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  148. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  149. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  150. // data values — they will be evaluated passing `data` as an argument.
  151. function template(str, data) {
  152. return str.replace(templateRe, function (str, key) {
  153. var value = data[key];
  154. if (value === undefined) {
  155. throw new Error('No value provided for variable ' + str);
  156. } else if (typeof value === 'function') {
  157. value = value(data);
  158. }
  159. return value;
  160. });
  161. }
  162. // @function isArray(obj): Boolean
  163. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  164. var isArray = Array.isArray || function (obj) {
  165. return (Object.prototype.toString.call(obj) === '[object Array]');
  166. };
  167. // @function indexOf(array: Array, el: Object): Number
  168. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  169. function indexOf(array, el) {
  170. for (var i = 0; i < array.length; i++) {
  171. if (array[i] === el) { return i; }
  172. }
  173. return -1;
  174. }
  175. // @property emptyImageUrl: String
  176. // Data URI string containing a base64-encoded empty GIF image.
  177. // Used as a hack to free memory from unused images on WebKit-powered
  178. // mobile devices (by setting image `src` to this string).
  179. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  180. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  181. function getPrefixed(name) {
  182. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  183. }
  184. var lastTime = 0;
  185. // fallback for IE 7-8
  186. function timeoutDefer(fn) {
  187. var time = +new Date(),
  188. timeToCall = Math.max(0, 16 - (time - lastTime));
  189. lastTime = time + timeToCall;
  190. return window.setTimeout(fn, timeToCall);
  191. }
  192. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  193. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  194. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  195. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  196. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  197. // `context` if given. When `immediate` is set, `fn` is called immediately if
  198. // the browser doesn't have native support for
  199. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  200. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  201. function requestAnimFrame(fn, context, immediate) {
  202. if (immediate && requestFn === timeoutDefer) {
  203. fn.call(context);
  204. } else {
  205. return requestFn.call(window, bind(fn, context));
  206. }
  207. }
  208. // @function cancelAnimFrame(id: Number): undefined
  209. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  210. function cancelAnimFrame(id) {
  211. if (id) {
  212. cancelFn.call(window, id);
  213. }
  214. }
  215. var Util = (Object.freeze || Object)({
  216. freeze: freeze,
  217. extend: extend,
  218. create: create,
  219. bind: bind,
  220. lastId: lastId,
  221. stamp: stamp,
  222. throttle: throttle,
  223. wrapNum: wrapNum,
  224. falseFn: falseFn,
  225. formatNum: formatNum,
  226. trim: trim,
  227. splitWords: splitWords,
  228. setOptions: setOptions,
  229. getParamString: getParamString,
  230. template: template,
  231. isArray: isArray,
  232. indexOf: indexOf,
  233. emptyImageUrl: emptyImageUrl,
  234. requestFn: requestFn,
  235. cancelFn: cancelFn,
  236. requestAnimFrame: requestAnimFrame,
  237. cancelAnimFrame: cancelAnimFrame
  238. });
  239. // @class Class
  240. // @aka L.Class
  241. // @section
  242. // @uninheritable
  243. // Thanks to John Resig and Dean Edwards for inspiration!
  244. function Class() {}
  245. Class.extend = function (props) {
  246. // @function extend(props: Object): Function
  247. // [Extends the current class](#class-inheritance) given the properties to be included.
  248. // Returns a Javascript function that is a class constructor (to be called with `new`).
  249. var NewClass = function () {
  250. // call the constructor
  251. if (this.initialize) {
  252. this.initialize.apply(this, arguments);
  253. }
  254. // call all constructor hooks
  255. this.callInitHooks();
  256. };
  257. var parentProto = NewClass.__super__ = this.prototype;
  258. var proto = create(parentProto);
  259. proto.constructor = NewClass;
  260. NewClass.prototype = proto;
  261. // inherit parent's statics
  262. for (var i in this) {
  263. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  264. NewClass[i] = this[i];
  265. }
  266. }
  267. // mix static properties into the class
  268. if (props.statics) {
  269. extend(NewClass, props.statics);
  270. delete props.statics;
  271. }
  272. // mix includes into the prototype
  273. if (props.includes) {
  274. checkDeprecatedMixinEvents(props.includes);
  275. extend.apply(null, [proto].concat(props.includes));
  276. delete props.includes;
  277. }
  278. // merge options
  279. if (proto.options) {
  280. props.options = extend(create(proto.options), props.options);
  281. }
  282. // mix given properties into the prototype
  283. extend(proto, props);
  284. proto._initHooks = [];
  285. // add method for calling all hooks
  286. proto.callInitHooks = function () {
  287. if (this._initHooksCalled) { return; }
  288. if (parentProto.callInitHooks) {
  289. parentProto.callInitHooks.call(this);
  290. }
  291. this._initHooksCalled = true;
  292. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  293. proto._initHooks[i].call(this);
  294. }
  295. };
  296. return NewClass;
  297. };
  298. // @function include(properties: Object): this
  299. // [Includes a mixin](#class-includes) into the current class.
  300. Class.include = function (props) {
  301. extend(this.prototype, props);
  302. return this;
  303. };
  304. // @function mergeOptions(options: Object): this
  305. // [Merges `options`](#class-options) into the defaults of the class.
  306. Class.mergeOptions = function (options) {
  307. extend(this.prototype.options, options);
  308. return this;
  309. };
  310. // @function addInitHook(fn: Function): this
  311. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  312. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  313. var args = Array.prototype.slice.call(arguments, 1);
  314. var init = typeof fn === 'function' ? fn : function () {
  315. this[fn].apply(this, args);
  316. };
  317. this.prototype._initHooks = this.prototype._initHooks || [];
  318. this.prototype._initHooks.push(init);
  319. return this;
  320. };
  321. function checkDeprecatedMixinEvents(includes) {
  322. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  323. includes = isArray(includes) ? includes : [includes];
  324. for (var i = 0; i < includes.length; i++) {
  325. if (includes[i] === L.Mixin.Events) {
  326. console.warn('Deprecated include of L.Mixin.Events: ' +
  327. 'this property will be removed in future releases, ' +
  328. 'please inherit from L.Evented instead.', new Error().stack);
  329. }
  330. }
  331. }
  332. /*
  333. * @class Evented
  334. * @aka L.Evented
  335. * @inherits Class
  336. *
  337. * A set of methods shared between event-powered classes (like `Map` and `Marker`). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event).
  338. *
  339. * @example
  340. *
  341. * ```js
  342. * map.on('click', function(e) {
  343. * alert(e.latlng);
  344. * } );
  345. * ```
  346. *
  347. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  348. *
  349. * ```js
  350. * function onClick(e) { ... }
  351. *
  352. * map.on('click', onClick);
  353. * map.off('click', onClick);
  354. * ```
  355. */
  356. var Events = {
  357. /* @method on(type: String, fn: Function, context?: Object): this
  358. * Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`).
  359. *
  360. * @alternative
  361. * @method on(eventMap: Object): this
  362. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  363. */
  364. on: function (types, fn, context) {
  365. // types can be a map of types/handlers
  366. if (typeof types === 'object') {
  367. for (var type in types) {
  368. // we don't process space-separated events here for performance;
  369. // it's a hot path since Layer uses the on(obj) syntax
  370. this._on(type, types[type], fn);
  371. }
  372. } else {
  373. // types can be a string of space-separated words
  374. types = splitWords(types);
  375. for (var i = 0, len = types.length; i < len; i++) {
  376. this._on(types[i], fn, context);
  377. }
  378. }
  379. return this;
  380. },
  381. /* @method off(type: String, fn?: Function, context?: Object): this
  382. * Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener.
  383. *
  384. * @alternative
  385. * @method off(eventMap: Object): this
  386. * Removes a set of type/listener pairs.
  387. *
  388. * @alternative
  389. * @method off: this
  390. * Removes all listeners to all events on the object.
  391. */
  392. off: function (types, fn, context) {
  393. if (!types) {
  394. // clear all listeners if called without arguments
  395. delete this._events;
  396. } else if (typeof types === 'object') {
  397. for (var type in types) {
  398. this._off(type, types[type], fn);
  399. }
  400. } else {
  401. types = splitWords(types);
  402. for (var i = 0, len = types.length; i < len; i++) {
  403. this._off(types[i], fn, context);
  404. }
  405. }
  406. return this;
  407. },
  408. // attach listener (without syntactic sugar now)
  409. _on: function (type, fn, context) {
  410. this._events = this._events || {};
  411. /* get/init listeners for type */
  412. var typeListeners = this._events[type];
  413. if (!typeListeners) {
  414. typeListeners = [];
  415. this._events[type] = typeListeners;
  416. }
  417. if (context === this) {
  418. // Less memory footprint.
  419. context = undefined;
  420. }
  421. var newListener = {fn: fn, ctx: context},
  422. listeners = typeListeners;
  423. // check if fn already there
  424. for (var i = 0, len = listeners.length; i < len; i++) {
  425. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  426. return;
  427. }
  428. }
  429. listeners.push(newListener);
  430. },
  431. _off: function (type, fn, context) {
  432. var listeners,
  433. i,
  434. len;
  435. if (!this._events) { return; }
  436. listeners = this._events[type];
  437. if (!listeners) {
  438. return;
  439. }
  440. if (!fn) {
  441. // Set all removed listeners to noop so they are not called if remove happens in fire
  442. for (i = 0, len = listeners.length; i < len; i++) {
  443. listeners[i].fn = falseFn;
  444. }
  445. // clear all listeners for a type if function isn't specified
  446. delete this._events[type];
  447. return;
  448. }
  449. if (context === this) {
  450. context = undefined;
  451. }
  452. if (listeners) {
  453. // find fn and remove it
  454. for (i = 0, len = listeners.length; i < len; i++) {
  455. var l = listeners[i];
  456. if (l.ctx !== context) { continue; }
  457. if (l.fn === fn) {
  458. // set the removed listener to noop so that's not called if remove happens in fire
  459. l.fn = falseFn;
  460. if (this._firingCount) {
  461. /* copy array in case events are being fired */
  462. this._events[type] = listeners = listeners.slice();
  463. }
  464. listeners.splice(i, 1);
  465. return;
  466. }
  467. }
  468. }
  469. },
  470. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  471. // Fires an event of the specified type. You can optionally provide an data
  472. // object — the first argument of the listener function will contain its
  473. // properties. The event can optionally be propagated to event parents.
  474. fire: function (type, data, propagate) {
  475. if (!this.listens(type, propagate)) { return this; }
  476. var event = extend({}, data, {
  477. type: type,
  478. target: this,
  479. sourceTarget: data && data.sourceTarget || this
  480. });
  481. if (this._events) {
  482. var listeners = this._events[type];
  483. if (listeners) {
  484. this._firingCount = (this._firingCount + 1) || 1;
  485. for (var i = 0, len = listeners.length; i < len; i++) {
  486. var l = listeners[i];
  487. l.fn.call(l.ctx || this, event);
  488. }
  489. this._firingCount--;
  490. }
  491. }
  492. if (propagate) {
  493. // propagate the event to parents (set with addEventParent)
  494. this._propagateEvent(event);
  495. }
  496. return this;
  497. },
  498. // @method listens(type: String): Boolean
  499. // Returns `true` if a particular event type has any listeners attached to it.
  500. listens: function (type, propagate) {
  501. var listeners = this._events && this._events[type];
  502. if (listeners && listeners.length) { return true; }
  503. if (propagate) {
  504. // also check parents for listeners if event propagates
  505. for (var id in this._eventParents) {
  506. if (this._eventParents[id].listens(type, propagate)) { return true; }
  507. }
  508. }
  509. return false;
  510. },
  511. // @method once(…): this
  512. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  513. once: function (types, fn, context) {
  514. if (typeof types === 'object') {
  515. for (var type in types) {
  516. this.once(type, types[type], fn);
  517. }
  518. return this;
  519. }
  520. var handler = bind(function () {
  521. this
  522. .off(types, fn, context)
  523. .off(types, handler, context);
  524. }, this);
  525. // add a listener that's executed once and removed after that
  526. return this
  527. .on(types, fn, context)
  528. .on(types, handler, context);
  529. },
  530. // @method addEventParent(obj: Evented): this
  531. // Adds an event parent - an `Evented` that will receive propagated events
  532. addEventParent: function (obj) {
  533. this._eventParents = this._eventParents || {};
  534. this._eventParents[stamp(obj)] = obj;
  535. return this;
  536. },
  537. // @method removeEventParent(obj: Evented): this
  538. // Removes an event parent, so it will stop receiving propagated events
  539. removeEventParent: function (obj) {
  540. if (this._eventParents) {
  541. delete this._eventParents[stamp(obj)];
  542. }
  543. return this;
  544. },
  545. _propagateEvent: function (e) {
  546. for (var id in this._eventParents) {
  547. this._eventParents[id].fire(e.type, extend({
  548. layer: e.target,
  549. propagatedFrom: e.target
  550. }, e), true);
  551. }
  552. }
  553. };
  554. // aliases; we should ditch those eventually
  555. // @method addEventListener(…): this
  556. // Alias to [`on(…)`](#evented-on)
  557. Events.addEventListener = Events.on;
  558. // @method removeEventListener(…): this
  559. // Alias to [`off(…)`](#evented-off)
  560. // @method clearAllEventListeners(…): this
  561. // Alias to [`off()`](#evented-off)
  562. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  563. // @method addOneTimeEventListener(…): this
  564. // Alias to [`once(…)`](#evented-once)
  565. Events.addOneTimeEventListener = Events.once;
  566. // @method fireEvent(…): this
  567. // Alias to [`fire(…)`](#evented-fire)
  568. Events.fireEvent = Events.fire;
  569. // @method hasEventListeners(…): Boolean
  570. // Alias to [`listens(…)`](#evented-listens)
  571. Events.hasEventListeners = Events.listens;
  572. var Evented = Class.extend(Events);
  573. /*
  574. * @class Point
  575. * @aka L.Point
  576. *
  577. * Represents a point with `x` and `y` coordinates in pixels.
  578. *
  579. * @example
  580. *
  581. * ```js
  582. * var point = L.point(200, 300);
  583. * ```
  584. *
  585. * All Leaflet methods and options that accept `Point` objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:
  586. *
  587. * ```js
  588. * map.panBy([200, 300]);
  589. * map.panBy(L.point(200, 300));
  590. * ```
  591. *
  592. * Note that `Point` does not inherit from Leafet's `Class` object,
  593. * which means new classes can't inherit from it, and new methods
  594. * can't be added to it with the `include` function.
  595. */
  596. function Point(x, y, round) {
  597. // @property x: Number; The `x` coordinate of the point
  598. this.x = (round ? Math.round(x) : x);
  599. // @property y: Number; The `y` coordinate of the point
  600. this.y = (round ? Math.round(y) : y);
  601. }
  602. var trunc = Math.trunc || function (v) {
  603. return v > 0 ? Math.floor(v) : Math.ceil(v);
  604. };
  605. Point.prototype = {
  606. // @method clone(): Point
  607. // Returns a copy of the current point.
  608. clone: function () {
  609. return new Point(this.x, this.y);
  610. },
  611. // @method add(otherPoint: Point): Point
  612. // Returns the result of addition of the current and the given points.
  613. add: function (point) {
  614. // non-destructive, returns a new point
  615. return this.clone()._add(toPoint(point));
  616. },
  617. _add: function (point) {
  618. // destructive, used directly for performance in situations where it's safe to modify existing point
  619. this.x += point.x;
  620. this.y += point.y;
  621. return this;
  622. },
  623. // @method subtract(otherPoint: Point): Point
  624. // Returns the result of subtraction of the given point from the current.
  625. subtract: function (point) {
  626. return this.clone()._subtract(toPoint(point));
  627. },
  628. _subtract: function (point) {
  629. this.x -= point.x;
  630. this.y -= point.y;
  631. return this;
  632. },
  633. // @method divideBy(num: Number): Point
  634. // Returns the result of division of the current point by the given number.
  635. divideBy: function (num) {
  636. return this.clone()._divideBy(num);
  637. },
  638. _divideBy: function (num) {
  639. this.x /= num;
  640. this.y /= num;
  641. return this;
  642. },
  643. // @method multiplyBy(num: Number): Point
  644. // Returns the result of multiplication of the current point by the given number.
  645. multiplyBy: function (num) {
  646. return this.clone()._multiplyBy(num);
  647. },
  648. _multiplyBy: function (num) {
  649. this.x *= num;
  650. this.y *= num;
  651. return this;
  652. },
  653. // @method scaleBy(scale: Point): Point
  654. // Multiply each coordinate of the current point by each coordinate of
  655. // `scale`. In linear algebra terms, multiply the point by the
  656. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  657. // defined by `scale`.
  658. scaleBy: function (point) {
  659. return new Point(this.x * point.x, this.y * point.y);
  660. },
  661. // @method unscaleBy(scale: Point): Point
  662. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  663. // each coordinate of `scale`.
  664. unscaleBy: function (point) {
  665. return new Point(this.x / point.x, this.y / point.y);
  666. },
  667. // @method round(): Point
  668. // Returns a copy of the current point with rounded coordinates.
  669. round: function () {
  670. return this.clone()._round();
  671. },
  672. _round: function () {
  673. this.x = Math.round(this.x);
  674. this.y = Math.round(this.y);
  675. return this;
  676. },
  677. // @method floor(): Point
  678. // Returns a copy of the current point with floored coordinates (rounded down).
  679. floor: function () {
  680. return this.clone()._floor();
  681. },
  682. _floor: function () {
  683. this.x = Math.floor(this.x);
  684. this.y = Math.floor(this.y);
  685. return this;
  686. },
  687. // @method ceil(): Point
  688. // Returns a copy of the current point with ceiled coordinates (rounded up).
  689. ceil: function () {
  690. return this.clone()._ceil();
  691. },
  692. _ceil: function () {
  693. this.x = Math.ceil(this.x);
  694. this.y = Math.ceil(this.y);
  695. return this;
  696. },
  697. // @method trunc(): Point
  698. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  699. trunc: function () {
  700. return this.clone()._trunc();
  701. },
  702. _trunc: function () {
  703. this.x = trunc(this.x);
  704. this.y = trunc(this.y);
  705. return this;
  706. },
  707. // @method distanceTo(otherPoint: Point): Number
  708. // Returns the cartesian distance between the current and the given points.
  709. distanceTo: function (point) {
  710. point = toPoint(point);
  711. var x = point.x - this.x,
  712. y = point.y - this.y;
  713. return Math.sqrt(x * x + y * y);
  714. },
  715. // @method equals(otherPoint: Point): Boolean
  716. // Returns `true` if the given point has the same coordinates.
  717. equals: function (point) {
  718. point = toPoint(point);
  719. return point.x === this.x &&
  720. point.y === this.y;
  721. },
  722. // @method contains(otherPoint: Point): Boolean
  723. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  724. contains: function (point) {
  725. point = toPoint(point);
  726. return Math.abs(point.x) <= Math.abs(this.x) &&
  727. Math.abs(point.y) <= Math.abs(this.y);
  728. },
  729. // @method toString(): String
  730. // Returns a string representation of the point for debugging purposes.
  731. toString: function () {
  732. return 'Point(' +
  733. formatNum(this.x) + ', ' +
  734. formatNum(this.y) + ')';
  735. }
  736. };
  737. // @factory L.point(x: Number, y: Number, round?: Boolean)
  738. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  739. // @alternative
  740. // @factory L.point(coords: Number[])
  741. // Expects an array of the form `[x, y]` instead.
  742. // @alternative
  743. // @factory L.point(coords: Object)
  744. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  745. function toPoint(x, y, round) {
  746. if (x instanceof Point) {
  747. return x;
  748. }
  749. if (isArray(x)) {
  750. return new Point(x[0], x[1]);
  751. }
  752. if (x === undefined || x === null) {
  753. return x;
  754. }
  755. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  756. return new Point(x.x, x.y);
  757. }
  758. return new Point(x, y, round);
  759. }
  760. /*
  761. * @class Bounds
  762. * @aka L.Bounds
  763. *
  764. * Represents a rectangular area in pixel coordinates.
  765. *
  766. * @example
  767. *
  768. * ```js
  769. * var p1 = L.point(10, 10),
  770. * p2 = L.point(40, 60),
  771. * bounds = L.bounds(p1, p2);
  772. * ```
  773. *
  774. * All Leaflet methods that accept `Bounds` objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  775. *
  776. * ```js
  777. * otherBounds.intersects([[10, 10], [40, 60]]);
  778. * ```
  779. *
  780. * Note that `Bounds` does not inherit from Leafet's `Class` object,
  781. * which means new classes can't inherit from it, and new methods
  782. * can't be added to it with the `include` function.
  783. */
  784. function Bounds(a, b) {
  785. if (!a) { return; }
  786. var points = b ? [a, b] : a;
  787. for (var i = 0, len = points.length; i < len; i++) {
  788. this.extend(points[i]);
  789. }
  790. }
  791. Bounds.prototype = {
  792. // @method extend(point: Point): this
  793. // Extends the bounds to contain the given point.
  794. extend: function (point) { // (Point)
  795. point = toPoint(point);
  796. // @property min: Point
  797. // The top left corner of the rectangle.
  798. // @property max: Point
  799. // The bottom right corner of the rectangle.
  800. if (!this.min && !this.max) {
  801. this.min = point.clone();
  802. this.max = point.clone();
  803. } else {
  804. this.min.x = Math.min(point.x, this.min.x);
  805. this.max.x = Math.max(point.x, this.max.x);
  806. this.min.y = Math.min(point.y, this.min.y);
  807. this.max.y = Math.max(point.y, this.max.y);
  808. }
  809. return this;
  810. },
  811. // @method getCenter(round?: Boolean): Point
  812. // Returns the center point of the bounds.
  813. getCenter: function (round) {
  814. return new Point(
  815. (this.min.x + this.max.x) / 2,
  816. (this.min.y + this.max.y) / 2, round);
  817. },
  818. // @method getBottomLeft(): Point
  819. // Returns the bottom-left point of the bounds.
  820. getBottomLeft: function () {
  821. return new Point(this.min.x, this.max.y);
  822. },
  823. // @method getTopRight(): Point
  824. // Returns the top-right point of the bounds.
  825. getTopRight: function () { // -> Point
  826. return new Point(this.max.x, this.min.y);
  827. },
  828. // @method getTopLeft(): Point
  829. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  830. getTopLeft: function () {
  831. return this.min; // left, top
  832. },
  833. // @method getBottomRight(): Point
  834. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  835. getBottomRight: function () {
  836. return this.max; // right, bottom
  837. },
  838. // @method getSize(): Point
  839. // Returns the size of the given bounds
  840. getSize: function () {
  841. return this.max.subtract(this.min);
  842. },
  843. // @method contains(otherBounds: Bounds): Boolean
  844. // Returns `true` if the rectangle contains the given one.
  845. // @alternative
  846. // @method contains(point: Point): Boolean
  847. // Returns `true` if the rectangle contains the given point.
  848. contains: function (obj) {
  849. var min, max;
  850. if (typeof obj[0] === 'number' || obj instanceof Point) {
  851. obj = toPoint(obj);
  852. } else {
  853. obj = toBounds(obj);
  854. }
  855. if (obj instanceof Bounds) {
  856. min = obj.min;
  857. max = obj.max;
  858. } else {
  859. min = max = obj;
  860. }
  861. return (min.x >= this.min.x) &&
  862. (max.x <= this.max.x) &&
  863. (min.y >= this.min.y) &&
  864. (max.y <= this.max.y);
  865. },
  866. // @method intersects(otherBounds: Bounds): Boolean
  867. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  868. // intersect if they have at least one point in common.
  869. intersects: function (bounds) { // (Bounds) -> Boolean
  870. bounds = toBounds(bounds);
  871. var min = this.min,
  872. max = this.max,
  873. min2 = bounds.min,
  874. max2 = bounds.max,
  875. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  876. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  877. return xIntersects && yIntersects;
  878. },
  879. // @method overlaps(otherBounds: Bounds): Boolean
  880. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  881. // overlap if their intersection is an area.
  882. overlaps: function (bounds) { // (Bounds) -> Boolean
  883. bounds = toBounds(bounds);
  884. var min = this.min,
  885. max = this.max,
  886. min2 = bounds.min,
  887. max2 = bounds.max,
  888. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  889. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  890. return xOverlaps && yOverlaps;
  891. },
  892. isValid: function () {
  893. return !!(this.min && this.max);
  894. }
  895. };
  896. // @factory L.bounds(corner1: Point, corner2: Point)
  897. // Creates a Bounds object from two corners coordinate pairs.
  898. // @alternative
  899. // @factory L.bounds(points: Point[])
  900. // Creates a Bounds object from the given array of points.
  901. function toBounds(a, b) {
  902. if (!a || a instanceof Bounds) {
  903. return a;
  904. }
  905. return new Bounds(a, b);
  906. }
  907. /*
  908. * @class LatLngBounds
  909. * @aka L.LatLngBounds
  910. *
  911. * Represents a rectangular geographical area on a map.
  912. *
  913. * @example
  914. *
  915. * ```js
  916. * var corner1 = L.latLng(40.712, -74.227),
  917. * corner2 = L.latLng(40.774, -74.125),
  918. * bounds = L.latLngBounds(corner1, corner2);
  919. * ```
  920. *
  921. * All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:
  922. *
  923. * ```js
  924. * map.fitBounds([
  925. * [40.712, -74.227],
  926. * [40.774, -74.125]
  927. * ]);
  928. * ```
  929. *
  930. * Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners _outside_ the [-180, 180] degrees longitude range.
  931. *
  932. * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,
  933. * which means new classes can't inherit from it, and new methods
  934. * can't be added to it with the `include` function.
  935. */
  936. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  937. if (!corner1) { return; }
  938. var latlngs = corner2 ? [corner1, corner2] : corner1;
  939. for (var i = 0, len = latlngs.length; i < len; i++) {
  940. this.extend(latlngs[i]);
  941. }
  942. }
  943. LatLngBounds.prototype = {
  944. // @method extend(latlng: LatLng): this
  945. // Extend the bounds to contain the given point
  946. // @alternative
  947. // @method extend(otherBounds: LatLngBounds): this
  948. // Extend the bounds to contain the given bounds
  949. extend: function (obj) {
  950. var sw = this._southWest,
  951. ne = this._northEast,
  952. sw2, ne2;
  953. if (obj instanceof LatLng) {
  954. sw2 = obj;
  955. ne2 = obj;
  956. } else if (obj instanceof LatLngBounds) {
  957. sw2 = obj._southWest;
  958. ne2 = obj._northEast;
  959. if (!sw2 || !ne2) { return this; }
  960. } else {
  961. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  962. }
  963. if (!sw && !ne) {
  964. this._southWest = new LatLng(sw2.lat, sw2.lng);
  965. this._northEast = new LatLng(ne2.lat, ne2.lng);
  966. } else {
  967. sw.lat = Math.min(sw2.lat, sw.lat);
  968. sw.lng = Math.min(sw2.lng, sw.lng);
  969. ne.lat = Math.max(ne2.lat, ne.lat);
  970. ne.lng = Math.max(ne2.lng, ne.lng);
  971. }
  972. return this;
  973. },
  974. // @method pad(bufferRatio: Number): LatLngBounds
  975. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  976. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  977. // Negative values will retract the bounds.
  978. pad: function (bufferRatio) {
  979. var sw = this._southWest,
  980. ne = this._northEast,
  981. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  982. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  983. return new LatLngBounds(
  984. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  985. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  986. },
  987. // @method getCenter(): LatLng
  988. // Returns the center point of the bounds.
  989. getCenter: function () {
  990. return new LatLng(
  991. (this._southWest.lat + this._northEast.lat) / 2,
  992. (this._southWest.lng + this._northEast.lng) / 2);
  993. },
  994. // @method getSouthWest(): LatLng
  995. // Returns the south-west point of the bounds.
  996. getSouthWest: function () {
  997. return this._southWest;
  998. },
  999. // @method getNorthEast(): LatLng
  1000. // Returns the north-east point of the bounds.
  1001. getNorthEast: function () {
  1002. return this._northEast;
  1003. },
  1004. // @method getNorthWest(): LatLng
  1005. // Returns the north-west point of the bounds.
  1006. getNorthWest: function () {
  1007. return new LatLng(this.getNorth(), this.getWest());
  1008. },
  1009. // @method getSouthEast(): LatLng
  1010. // Returns the south-east point of the bounds.
  1011. getSouthEast: function () {
  1012. return new LatLng(this.getSouth(), this.getEast());
  1013. },
  1014. // @method getWest(): Number
  1015. // Returns the west longitude of the bounds
  1016. getWest: function () {
  1017. return this._southWest.lng;
  1018. },
  1019. // @method getSouth(): Number
  1020. // Returns the south latitude of the bounds
  1021. getSouth: function () {
  1022. return this._southWest.lat;
  1023. },
  1024. // @method getEast(): Number
  1025. // Returns the east longitude of the bounds
  1026. getEast: function () {
  1027. return this._northEast.lng;
  1028. },
  1029. // @method getNorth(): Number
  1030. // Returns the north latitude of the bounds
  1031. getNorth: function () {
  1032. return this._northEast.lat;
  1033. },
  1034. // @method contains(otherBounds: LatLngBounds): Boolean
  1035. // Returns `true` if the rectangle contains the given one.
  1036. // @alternative
  1037. // @method contains (latlng: LatLng): Boolean
  1038. // Returns `true` if the rectangle contains the given point.
  1039. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1040. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1041. obj = toLatLng(obj);
  1042. } else {
  1043. obj = toLatLngBounds(obj);
  1044. }
  1045. var sw = this._southWest,
  1046. ne = this._northEast,
  1047. sw2, ne2;
  1048. if (obj instanceof LatLngBounds) {
  1049. sw2 = obj.getSouthWest();
  1050. ne2 = obj.getNorthEast();
  1051. } else {
  1052. sw2 = ne2 = obj;
  1053. }
  1054. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1055. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1056. },
  1057. // @method intersects(otherBounds: LatLngBounds): Boolean
  1058. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1059. intersects: function (bounds) {
  1060. bounds = toLatLngBounds(bounds);
  1061. var sw = this._southWest,
  1062. ne = this._northEast,
  1063. sw2 = bounds.getSouthWest(),
  1064. ne2 = bounds.getNorthEast(),
  1065. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1066. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1067. return latIntersects && lngIntersects;
  1068. },
  1069. // @method overlaps(otherBounds: Bounds): Boolean
  1070. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1071. overlaps: function (bounds) {
  1072. bounds = toLatLngBounds(bounds);
  1073. var sw = this._southWest,
  1074. ne = this._northEast,
  1075. sw2 = bounds.getSouthWest(),
  1076. ne2 = bounds.getNorthEast(),
  1077. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1078. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1079. return latOverlaps && lngOverlaps;
  1080. },
  1081. // @method toBBoxString(): String
  1082. // Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.
  1083. toBBoxString: function () {
  1084. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1085. },
  1086. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1087. // Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number.
  1088. equals: function (bounds, maxMargin) {
  1089. if (!bounds) { return false; }
  1090. bounds = toLatLngBounds(bounds);
  1091. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1092. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1093. },
  1094. // @method isValid(): Boolean
  1095. // Returns `true` if the bounds are properly initialized.
  1096. isValid: function () {
  1097. return !!(this._southWest && this._northEast);
  1098. }
  1099. };
  1100. // TODO International date line?
  1101. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1102. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1103. // @alternative
  1104. // @factory L.latLngBounds(latlngs: LatLng[])
  1105. // Creates a `LatLngBounds` object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds).
  1106. function toLatLngBounds(a, b) {
  1107. if (a instanceof LatLngBounds) {
  1108. return a;
  1109. }
  1110. return new LatLngBounds(a, b);
  1111. }
  1112. /* @class LatLng
  1113. * @aka L.LatLng
  1114. *
  1115. * Represents a geographical point with a certain latitude and longitude.
  1116. *
  1117. * @example
  1118. *
  1119. * ```
  1120. * var latlng = L.latLng(50.5, 30.5);
  1121. * ```
  1122. *
  1123. * All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:
  1124. *
  1125. * ```
  1126. * map.panTo([50, 30]);
  1127. * map.panTo({lon: 30, lat: 50});
  1128. * map.panTo({lat: 50, lng: 30});
  1129. * map.panTo(L.latLng(50, 30));
  1130. * ```
  1131. *
  1132. * Note that `LatLng` does not inherit from Leafet's `Class` object,
  1133. * which means new classes can't inherit from it, and new methods
  1134. * can't be added to it with the `include` function.
  1135. */
  1136. function LatLng(lat, lng, alt) {
  1137. if (isNaN(lat) || isNaN(lng)) {
  1138. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1139. }
  1140. // @property lat: Number
  1141. // Latitude in degrees
  1142. this.lat = +lat;
  1143. // @property lng: Number
  1144. // Longitude in degrees
  1145. this.lng = +lng;
  1146. // @property alt: Number
  1147. // Altitude in meters (optional)
  1148. if (alt !== undefined) {
  1149. this.alt = +alt;
  1150. }
  1151. }
  1152. LatLng.prototype = {
  1153. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1154. // Returns `true` if the given `LatLng` point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number.
  1155. equals: function (obj, maxMargin) {
  1156. if (!obj) { return false; }
  1157. obj = toLatLng(obj);
  1158. var margin = Math.max(
  1159. Math.abs(this.lat - obj.lat),
  1160. Math.abs(this.lng - obj.lng));
  1161. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1162. },
  1163. // @method toString(): String
  1164. // Returns a string representation of the point (for debugging purposes).
  1165. toString: function (precision) {
  1166. return 'LatLng(' +
  1167. formatNum(this.lat, precision) + ', ' +
  1168. formatNum(this.lng, precision) + ')';
  1169. },
  1170. // @method distanceTo(otherLatLng: LatLng): Number
  1171. // Returns the distance (in meters) to the given `LatLng` calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines).
  1172. distanceTo: function (other) {
  1173. return Earth.distance(this, toLatLng(other));
  1174. },
  1175. // @method wrap(): LatLng
  1176. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1177. wrap: function () {
  1178. return Earth.wrapLatLng(this);
  1179. },
  1180. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1181. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1182. toBounds: function (sizeInMeters) {
  1183. var latAccuracy = 180 * sizeInMeters / 40075017,
  1184. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1185. return toLatLngBounds(
  1186. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1187. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1188. },
  1189. clone: function () {
  1190. return new LatLng(this.lat, this.lng, this.alt);
  1191. }
  1192. };
  1193. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1194. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1195. // @alternative
  1196. // @factory L.latLng(coords: Array): LatLng
  1197. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1198. // @alternative
  1199. // @factory L.latLng(coords: Object): LatLng
  1200. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1201. function toLatLng(a, b, c) {
  1202. if (a instanceof LatLng) {
  1203. return a;
  1204. }
  1205. if (isArray(a) && typeof a[0] !== 'object') {
  1206. if (a.length === 3) {
  1207. return new LatLng(a[0], a[1], a[2]);
  1208. }
  1209. if (a.length === 2) {
  1210. return new LatLng(a[0], a[1]);
  1211. }
  1212. return null;
  1213. }
  1214. if (a === undefined || a === null) {
  1215. return a;
  1216. }
  1217. if (typeof a === 'object' && 'lat' in a) {
  1218. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1219. }
  1220. if (b === undefined) {
  1221. return null;
  1222. }
  1223. return new LatLng(a, b, c);
  1224. }
  1225. /*
  1226. * @namespace CRS
  1227. * @crs L.CRS.Base
  1228. * Object that defines coordinate reference systems for projecting
  1229. * geographical points into pixel (screen) coordinates and back (and to
  1230. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1231. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1232. *
  1233. * Leaflet defines the most usual CRSs by default. If you want to use a
  1234. * CRS not defined by default, take a look at the
  1235. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1236. *
  1237. * Note that the CRS instances do not inherit from Leafet's `Class` object,
  1238. * and can't be instantiated. Also, new classes can't inherit from them,
  1239. * and methods can't be added to them with the `include` function.
  1240. */
  1241. var CRS = {
  1242. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1243. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1244. latLngToPoint: function (latlng, zoom) {
  1245. var projectedPoint = this.projection.project(latlng),
  1246. scale = this.scale(zoom);
  1247. return this.transformation._transform(projectedPoint, scale);
  1248. },
  1249. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1250. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1251. // zoom into geographical coordinates.
  1252. pointToLatLng: function (point, zoom) {
  1253. var scale = this.scale(zoom),
  1254. untransformedPoint = this.transformation.untransform(point, scale);
  1255. return this.projection.unproject(untransformedPoint);
  1256. },
  1257. // @method project(latlng: LatLng): Point
  1258. // Projects geographical coordinates into coordinates in units accepted for
  1259. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1260. project: function (latlng) {
  1261. return this.projection.project(latlng);
  1262. },
  1263. // @method unproject(point: Point): LatLng
  1264. // Given a projected coordinate returns the corresponding LatLng.
  1265. // The inverse of `project`.
  1266. unproject: function (point) {
  1267. return this.projection.unproject(point);
  1268. },
  1269. // @method scale(zoom: Number): Number
  1270. // Returns the scale used when transforming projected coordinates into
  1271. // pixel coordinates for a particular zoom. For example, it returns
  1272. // `256 * 2^zoom` for Mercator-based CRS.
  1273. scale: function (zoom) {
  1274. return 256 * Math.pow(2, zoom);
  1275. },
  1276. // @method zoom(scale: Number): Number
  1277. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1278. // factor of `scale`.
  1279. zoom: function (scale) {
  1280. return Math.log(scale / 256) / Math.LN2;
  1281. },
  1282. // @method getProjectedBounds(zoom: Number): Bounds
  1283. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1284. getProjectedBounds: function (zoom) {
  1285. if (this.infinite) { return null; }
  1286. var b = this.projection.bounds,
  1287. s = this.scale(zoom),
  1288. min = this.transformation.transform(b.min, s),
  1289. max = this.transformation.transform(b.max, s);
  1290. return new Bounds(min, max);
  1291. },
  1292. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1293. // Returns the distance between two geographical coordinates.
  1294. // @property code: String
  1295. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1296. //
  1297. // @property wrapLng: Number[]
  1298. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1299. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1300. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1301. //
  1302. // @property wrapLat: Number[]
  1303. // Like `wrapLng`, but for the latitude (vertical) axis.
  1304. // wrapLng: [min, max],
  1305. // wrapLat: [min, max],
  1306. // @property infinite: Boolean
  1307. // If true, the coordinate space will be unbounded (infinite in both axes)
  1308. infinite: false,
  1309. // @method wrapLatLng(latlng: LatLng): LatLng
  1310. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1311. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1312. wrapLatLng: function (latlng) {
  1313. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1314. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1315. alt = latlng.alt;
  1316. return new LatLng(lat, lng, alt);
  1317. },
  1318. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1319. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1320. // that its center is within the CRS's bounds.
  1321. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1322. wrapLatLngBounds: function (bounds) {
  1323. var center = bounds.getCenter(),
  1324. newCenter = this.wrapLatLng(center),
  1325. latShift = center.lat - newCenter.lat,
  1326. lngShift = center.lng - newCenter.lng;
  1327. if (latShift === 0 && lngShift === 0) {
  1328. return bounds;
  1329. }
  1330. var sw = bounds.getSouthWest(),
  1331. ne = bounds.getNorthEast(),
  1332. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1333. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1334. return new LatLngBounds(newSw, newNe);
  1335. }
  1336. };
  1337. /*
  1338. * @namespace CRS
  1339. * @crs L.CRS.Earth
  1340. *
  1341. * Serves as the base for CRS that are global such that they cover the earth.
  1342. * Can only be used as the base for other CRS and cannot be used directly,
  1343. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1344. * meters.
  1345. */
  1346. var Earth = extend({}, CRS, {
  1347. wrapLng: [-180, 180],
  1348. // Mean Earth Radius, as recommended for use by
  1349. // the International Union of Geodesy and Geophysics,
  1350. // see http://rosettacode.org/wiki/Haversine_formula
  1351. R: 6371000,
  1352. // distance between two geographical points using spherical law of cosines approximation
  1353. distance: function (latlng1, latlng2) {
  1354. var rad = Math.PI / 180,
  1355. lat1 = latlng1.lat * rad,
  1356. lat2 = latlng2.lat * rad,
  1357. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1358. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1359. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1360. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1361. return this.R * c;
  1362. }
  1363. });
  1364. /*
  1365. * @namespace Projection
  1366. * @projection L.Projection.SphericalMercator
  1367. *
  1368. * Spherical Mercator projection — the most common projection for online maps,
  1369. * used by almost all free and commercial tile providers. Assumes that Earth is
  1370. * a sphere. Used by the `EPSG:3857` CRS.
  1371. */
  1372. var SphericalMercator = {
  1373. R: 6378137,
  1374. MAX_LATITUDE: 85.0511287798,
  1375. project: function (latlng) {
  1376. var d = Math.PI / 180,
  1377. max = this.MAX_LATITUDE,
  1378. lat = Math.max(Math.min(max, latlng.lat), -max),
  1379. sin = Math.sin(lat * d);
  1380. return new Point(
  1381. this.R * latlng.lng * d,
  1382. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1383. },
  1384. unproject: function (point) {
  1385. var d = 180 / Math.PI;
  1386. return new LatLng(
  1387. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1388. point.x * d / this.R);
  1389. },
  1390. bounds: (function () {
  1391. var d = 6378137 * Math.PI;
  1392. return new Bounds([-d, -d], [d, d]);
  1393. })()
  1394. };
  1395. /*
  1396. * @class Transformation
  1397. * @aka L.Transformation
  1398. *
  1399. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1400. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1401. * the reverse. Used by Leaflet in its projections code.
  1402. *
  1403. * @example
  1404. *
  1405. * ```js
  1406. * var transformation = L.transformation(2, 5, -1, 10),
  1407. * p = L.point(1, 2),
  1408. * p2 = transformation.transform(p), // L.point(7, 8)
  1409. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1410. * ```
  1411. */
  1412. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1413. // Creates a `Transformation` object with the given coefficients.
  1414. function Transformation(a, b, c, d) {
  1415. if (isArray(a)) {
  1416. // use array properties
  1417. this._a = a[0];
  1418. this._b = a[1];
  1419. this._c = a[2];
  1420. this._d = a[3];
  1421. return;
  1422. }
  1423. this._a = a;
  1424. this._b = b;
  1425. this._c = c;
  1426. this._d = d;
  1427. }
  1428. Transformation.prototype = {
  1429. // @method transform(point: Point, scale?: Number): Point
  1430. // Returns a transformed point, optionally multiplied by the given scale.
  1431. // Only accepts actual `L.Point` instances, not arrays.
  1432. transform: function (point, scale) { // (Point, Number) -> Point
  1433. return this._transform(point.clone(), scale);
  1434. },
  1435. // destructive transform (faster)
  1436. _transform: function (point, scale) {
  1437. scale = scale || 1;
  1438. point.x = scale * (this._a * point.x + this._b);
  1439. point.y = scale * (this._c * point.y + this._d);
  1440. return point;
  1441. },
  1442. // @method untransform(point: Point, scale?: Number): Point
  1443. // Returns the reverse transformation of the given point, optionally divided
  1444. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1445. untransform: function (point, scale) {
  1446. scale = scale || 1;
  1447. return new Point(
  1448. (point.x / scale - this._b) / this._a,
  1449. (point.y / scale - this._d) / this._c);
  1450. }
  1451. };
  1452. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1453. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1454. // Instantiates a Transformation object with the given coefficients.
  1455. // @alternative
  1456. // @factory L.transformation(coefficients: Array): Transformation
  1457. // Expects an coefficients array of the form
  1458. // `[a: Number, b: Number, c: Number, d: Number]`.
  1459. function toTransformation(a, b, c, d) {
  1460. return new Transformation(a, b, c, d);
  1461. }
  1462. /*
  1463. * @namespace CRS
  1464. * @crs L.CRS.EPSG3857
  1465. *
  1466. * The most common CRS for online maps, used by almost all free and commercial
  1467. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1468. * Map's `crs` option.
  1469. */
  1470. var EPSG3857 = extend({}, Earth, {
  1471. code: 'EPSG:3857',
  1472. projection: SphericalMercator,
  1473. transformation: (function () {
  1474. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1475. return toTransformation(scale, 0.5, -scale, 0.5);
  1476. }())
  1477. });
  1478. var EPSG900913 = extend({}, EPSG3857, {
  1479. code: 'EPSG:900913'
  1480. });
  1481. // @namespace SVG; @section
  1482. // There are several static functions which can be called without instantiating L.SVG:
  1483. // @function create(name: String): SVGElement
  1484. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1485. // corresponding to the class name passed. For example, using 'line' will return
  1486. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1487. function svgCreate(name) {
  1488. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1489. }
  1490. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1491. // Generates a SVG path string for multiple rings, with each ring turning
  1492. // into "M..L..L.." instructions
  1493. function pointsToPath(rings, closed) {
  1494. var str = '',
  1495. i, j, len, len2, points, p;
  1496. for (i = 0, len = rings.length; i < len; i++) {
  1497. points = rings[i];
  1498. for (j = 0, len2 = points.length; j < len2; j++) {
  1499. p = points[j];
  1500. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1501. }
  1502. // closes the ring for polygons; "x" is VML syntax
  1503. str += closed ? (svg ? 'z' : 'x') : '';
  1504. }
  1505. // SVG complains about empty path strings
  1506. return str || 'M0 0';
  1507. }
  1508. /*
  1509. * @namespace Browser
  1510. * @aka L.Browser
  1511. *
  1512. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1513. *
  1514. * @example
  1515. *
  1516. * ```js
  1517. * if (L.Browser.ielt9) {
  1518. * alert('Upgrade your browser, dude!');
  1519. * }
  1520. * ```
  1521. */
  1522. var style$1 = document.documentElement.style;
  1523. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1524. var ie = 'ActiveXObject' in window;
  1525. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1526. var ielt9 = ie && !document.addEventListener;
  1527. // @property edge: Boolean; `true` for the Edge web browser.
  1528. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1529. // @property webkit: Boolean;
  1530. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1531. var webkit = userAgentContains('webkit');
  1532. // @property android: Boolean
  1533. // `true` for any browser running on an Android platform.
  1534. var android = userAgentContains('android');
  1535. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1536. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1537. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1538. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1539. // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
  1540. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1541. // @property opera: Boolean; `true` for the Opera browser
  1542. var opera = !!window.opera;
  1543. // @property chrome: Boolean; `true` for the Chrome browser.
  1544. var chrome = userAgentContains('chrome');
  1545. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1546. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1547. // @property safari: Boolean; `true` for the Safari browser.
  1548. var safari = !chrome && userAgentContains('safari');
  1549. var phantom = userAgentContains('phantom');
  1550. // @property opera12: Boolean
  1551. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1552. var opera12 = 'OTransition' in style$1;
  1553. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1554. var win = navigator.platform.indexOf('Win') === 0;
  1555. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1556. var ie3d = ie && ('transition' in style$1);
  1557. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1558. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1559. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1560. var gecko3d = 'MozPerspective' in style$1;
  1561. // @property any3d: Boolean
  1562. // `true` for all browsers supporting CSS transforms.
  1563. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1564. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1565. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1566. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1567. var mobileWebkit = mobile && webkit;
  1568. // @property mobileWebkit3d: Boolean
  1569. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1570. var mobileWebkit3d = mobile && webkit3d;
  1571. // @property msPointer: Boolean
  1572. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1573. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1574. // @property pointer: Boolean
  1575. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1576. var pointer = !!(window.PointerEvent || msPointer);
  1577. // @property touch: Boolean
  1578. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1579. // This does not necessarily mean that the browser is running in a computer with
  1580. // a touchscreen, it only means that the browser is capable of understanding
  1581. // touch events.
  1582. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1583. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1584. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1585. var mobileOpera = mobile && opera;
  1586. // @property mobileGecko: Boolean
  1587. // `true` for gecko-based browsers running in a mobile device.
  1588. var mobileGecko = mobile && gecko;
  1589. // @property retina: Boolean
  1590. // `true` for browsers on a high-resolution "retina" screen.
  1591. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1592. // @property canvas: Boolean
  1593. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1594. var canvas = (function () {
  1595. return !!document.createElement('canvas').getContext;
  1596. }());
  1597. // @property svg: Boolean
  1598. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1599. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1600. // @property vml: Boolean
  1601. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1602. var vml = !svg && (function () {
  1603. try {
  1604. var div = document.createElement('div');
  1605. div.innerHTML = '<v:shape adj="1"/>';
  1606. var shape = div.firstChild;
  1607. shape.style.behavior = 'url(#default#VML)';
  1608. return shape && (typeof shape.adj === 'object');
  1609. } catch (e) {
  1610. return false;
  1611. }
  1612. }());
  1613. function userAgentContains(str) {
  1614. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1615. }
  1616. var Browser = (Object.freeze || Object)({
  1617. ie: ie,
  1618. ielt9: ielt9,
  1619. edge: edge,
  1620. webkit: webkit,
  1621. android: android,
  1622. android23: android23,
  1623. androidStock: androidStock,
  1624. opera: opera,
  1625. chrome: chrome,
  1626. gecko: gecko,
  1627. safari: safari,
  1628. phantom: phantom,
  1629. opera12: opera12,
  1630. win: win,
  1631. ie3d: ie3d,
  1632. webkit3d: webkit3d,
  1633. gecko3d: gecko3d,
  1634. any3d: any3d,
  1635. mobile: mobile,
  1636. mobileWebkit: mobileWebkit,
  1637. mobileWebkit3d: mobileWebkit3d,
  1638. msPointer: msPointer,
  1639. pointer: pointer,
  1640. touch: touch,
  1641. mobileOpera: mobileOpera,
  1642. mobileGecko: mobileGecko,
  1643. retina: retina,
  1644. canvas: canvas,
  1645. svg: svg,
  1646. vml: vml
  1647. });
  1648. /*
  1649. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1650. */
  1651. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1652. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1653. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1654. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1655. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1656. var _pointers = {};
  1657. var _pointerDocListener = false;
  1658. // DomEvent.DoubleTap needs to know about this
  1659. var _pointersCount = 0;
  1660. // Provides a touch events wrapper for (ms)pointer events.
  1661. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1662. function addPointerListener(obj, type, handler, id) {
  1663. if (type === 'touchstart') {
  1664. _addPointerStart(obj, handler, id);
  1665. } else if (type === 'touchmove') {
  1666. _addPointerMove(obj, handler, id);
  1667. } else if (type === 'touchend') {
  1668. _addPointerEnd(obj, handler, id);
  1669. }
  1670. return this;
  1671. }
  1672. function removePointerListener(obj, type, id) {
  1673. var handler = obj['_leaflet_' + type + id];
  1674. if (type === 'touchstart') {
  1675. obj.removeEventListener(POINTER_DOWN, handler, false);
  1676. } else if (type === 'touchmove') {
  1677. obj.removeEventListener(POINTER_MOVE, handler, false);
  1678. } else if (type === 'touchend') {
  1679. obj.removeEventListener(POINTER_UP, handler, false);
  1680. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1681. }
  1682. return this;
  1683. }
  1684. function _addPointerStart(obj, handler, id) {
  1685. var onDown = bind(function (e) {
  1686. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1687. // In IE11, some touch events needs to fire for form controls, or
  1688. // the controls will stop working. We keep a whitelist of tag names that
  1689. // need these events. For other target tags, we prevent default on the event.
  1690. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1691. preventDefault(e);
  1692. } else {
  1693. return;
  1694. }
  1695. }
  1696. _handlePointer(e, handler);
  1697. });
  1698. obj['_leaflet_touchstart' + id] = onDown;
  1699. obj.addEventListener(POINTER_DOWN, onDown, false);
  1700. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1701. if (!_pointerDocListener) {
  1702. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1703. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1704. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1705. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1706. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1707. _pointerDocListener = true;
  1708. }
  1709. }
  1710. function _globalPointerDown(e) {
  1711. _pointers[e.pointerId] = e;
  1712. _pointersCount++;
  1713. }
  1714. function _globalPointerMove(e) {
  1715. if (_pointers[e.pointerId]) {
  1716. _pointers[e.pointerId] = e;
  1717. }
  1718. }
  1719. function _globalPointerUp(e) {
  1720. delete _pointers[e.pointerId];
  1721. _pointersCount--;
  1722. }
  1723. function _handlePointer(e, handler) {
  1724. e.touches = [];
  1725. for (var i in _pointers) {
  1726. e.touches.push(_pointers[i]);
  1727. }
  1728. e.changedTouches = [e];
  1729. handler(e);
  1730. }
  1731. function _addPointerMove(obj, handler, id) {
  1732. var onMove = function (e) {
  1733. // don't fire touch moves when mouse isn't down
  1734. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1735. _handlePointer(e, handler);
  1736. };
  1737. obj['_leaflet_touchmove' + id] = onMove;
  1738. obj.addEventListener(POINTER_MOVE, onMove, false);
  1739. }
  1740. function _addPointerEnd(obj, handler, id) {
  1741. var onUp = function (e) {
  1742. _handlePointer(e, handler);
  1743. };
  1744. obj['_leaflet_touchend' + id] = onUp;
  1745. obj.addEventListener(POINTER_UP, onUp, false);
  1746. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1747. }
  1748. /*
  1749. * Extends the event handling code with double tap support for mobile browsers.
  1750. */
  1751. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1752. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1753. var _pre = '_leaflet_';
  1754. // inspired by Zepto touch code by Thomas Fuchs
  1755. function addDoubleTapListener(obj, handler, id) {
  1756. var last, touch$$1,
  1757. doubleTap = false,
  1758. delay = 250;
  1759. function onTouchStart(e) {
  1760. var count;
  1761. if (pointer) {
  1762. if ((!edge) || e.pointerType === 'mouse') { return; }
  1763. count = _pointersCount;
  1764. } else {
  1765. count = e.touches.length;
  1766. }
  1767. if (count > 1) { return; }
  1768. var now = Date.now(),
  1769. delta = now - (last || now);
  1770. touch$$1 = e.touches ? e.touches[0] : e;
  1771. doubleTap = (delta > 0 && delta <= delay);
  1772. last = now;
  1773. }
  1774. function onTouchEnd(e) {
  1775. if (doubleTap && !touch$$1.cancelBubble) {
  1776. if (pointer) {
  1777. if ((!edge) || e.pointerType === 'mouse') { return; }
  1778. // work around .type being readonly with MSPointer* events
  1779. var newTouch = {},
  1780. prop, i;
  1781. for (i in touch$$1) {
  1782. prop = touch$$1[i];
  1783. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1784. }
  1785. touch$$1 = newTouch;
  1786. }
  1787. touch$$1.type = 'dblclick';
  1788. handler(touch$$1);
  1789. last = null;
  1790. }
  1791. }
  1792. obj[_pre + _touchstart + id] = onTouchStart;
  1793. obj[_pre + _touchend + id] = onTouchEnd;
  1794. obj[_pre + 'dblclick' + id] = handler;
  1795. obj.addEventListener(_touchstart, onTouchStart, false);
  1796. obj.addEventListener(_touchend, onTouchEnd, false);
  1797. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1798. // the browser doesn't fire touchend/pointerup events but does fire
  1799. // native dblclicks. See #4127.
  1800. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1801. obj.addEventListener('dblclick', handler, false);
  1802. return this;
  1803. }
  1804. function removeDoubleTapListener(obj, id) {
  1805. var touchstart = obj[_pre + _touchstart + id],
  1806. touchend = obj[_pre + _touchend + id],
  1807. dblclick = obj[_pre + 'dblclick' + id];
  1808. obj.removeEventListener(_touchstart, touchstart, false);
  1809. obj.removeEventListener(_touchend, touchend, false);
  1810. if (!edge) {
  1811. obj.removeEventListener('dblclick', dblclick, false);
  1812. }
  1813. return this;
  1814. }
  1815. /*
  1816. * @namespace DomEvent
  1817. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  1818. */
  1819. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  1820. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1821. // Adds a listener function (`fn`) to a particular DOM event type of the
  1822. // element `el`. You can optionally specify the context of the listener
  1823. // (object the `this` keyword will point to). You can also pass several
  1824. // space-separated types (e.g. `'click dblclick'`).
  1825. // @alternative
  1826. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  1827. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1828. function on(obj, types, fn, context) {
  1829. if (typeof types === 'object') {
  1830. for (var type in types) {
  1831. addOne(obj, type, types[type], fn);
  1832. }
  1833. } else {
  1834. types = splitWords(types);
  1835. for (var i = 0, len = types.length; i < len; i++) {
  1836. addOne(obj, types[i], fn, context);
  1837. }
  1838. }
  1839. return this;
  1840. }
  1841. var eventsKey = '_leaflet_events';
  1842. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1843. // Removes a previously added listener function.
  1844. // Note that if you passed a custom context to on, you must pass the same
  1845. // context to `off` in order to remove the listener.
  1846. // @alternative
  1847. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  1848. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1849. function off(obj, types, fn, context) {
  1850. if (typeof types === 'object') {
  1851. for (var type in types) {
  1852. removeOne(obj, type, types[type], fn);
  1853. }
  1854. } else if (types) {
  1855. types = splitWords(types);
  1856. for (var i = 0, len = types.length; i < len; i++) {
  1857. removeOne(obj, types[i], fn, context);
  1858. }
  1859. } else {
  1860. for (var j in obj[eventsKey]) {
  1861. removeOne(obj, j, obj[eventsKey][j]);
  1862. }
  1863. delete obj[eventsKey];
  1864. }
  1865. return this;
  1866. }
  1867. function addOne(obj, type, fn, context) {
  1868. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  1869. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  1870. var handler = function (e) {
  1871. return fn.call(context || obj, e || window.event);
  1872. };
  1873. var originalHandler = handler;
  1874. if (pointer && type.indexOf('touch') === 0) {
  1875. // Needs DomEvent.Pointer.js
  1876. addPointerListener(obj, type, handler, id);
  1877. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  1878. !(pointer && chrome)) {
  1879. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  1880. // See #5180
  1881. addDoubleTapListener(obj, handler, id);
  1882. } else if ('addEventListener' in obj) {
  1883. if (type === 'mousewheel') {
  1884. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1885. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  1886. handler = function (e) {
  1887. e = e || window.event;
  1888. if (isExternalTarget(obj, e)) {
  1889. originalHandler(e);
  1890. }
  1891. };
  1892. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  1893. } else {
  1894. if (type === 'click' && android) {
  1895. handler = function (e) {
  1896. filterClick(e, originalHandler);
  1897. };
  1898. }
  1899. obj.addEventListener(type, handler, false);
  1900. }
  1901. } else if ('attachEvent' in obj) {
  1902. obj.attachEvent('on' + type, handler);
  1903. }
  1904. obj[eventsKey] = obj[eventsKey] || {};
  1905. obj[eventsKey][id] = handler;
  1906. }
  1907. function removeOne(obj, type, fn, context) {
  1908. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  1909. handler = obj[eventsKey] && obj[eventsKey][id];
  1910. if (!handler) { return this; }
  1911. if (pointer && type.indexOf('touch') === 0) {
  1912. removePointerListener(obj, type, id);
  1913. } else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
  1914. !(pointer && chrome)) {
  1915. removeDoubleTapListener(obj, id);
  1916. } else if ('removeEventListener' in obj) {
  1917. if (type === 'mousewheel') {
  1918. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1919. } else {
  1920. obj.removeEventListener(
  1921. type === 'mouseenter' ? 'mouseover' :
  1922. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  1923. }
  1924. } else if ('detachEvent' in obj) {
  1925. obj.detachEvent('on' + type, handler);
  1926. }
  1927. obj[eventsKey][id] = null;
  1928. }
  1929. // @function stopPropagation(ev: DOMEvent): this
  1930. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  1931. // ```js
  1932. // L.DomEvent.on(div, 'click', function (ev) {
  1933. // L.DomEvent.stopPropagation(ev);
  1934. // });
  1935. // ```
  1936. function stopPropagation(e) {
  1937. if (e.stopPropagation) {
  1938. e.stopPropagation();
  1939. } else if (e.originalEvent) { // In case of Leaflet event.
  1940. e.originalEvent._stopped = true;
  1941. } else {
  1942. e.cancelBubble = true;
  1943. }
  1944. skipped(e);
  1945. return this;
  1946. }
  1947. // @function disableScrollPropagation(el: HTMLElement): this
  1948. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  1949. function disableScrollPropagation(el) {
  1950. addOne(el, 'mousewheel', stopPropagation);
  1951. return this;
  1952. }
  1953. // @function disableClickPropagation(el: HTMLElement): this
  1954. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  1955. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  1956. function disableClickPropagation(el) {
  1957. on(el, 'mousedown touchstart dblclick', stopPropagation);
  1958. addOne(el, 'click', fakeStop);
  1959. return this;
  1960. }
  1961. // @function preventDefault(ev: DOMEvent): this
  1962. // Prevents the default action of the DOM Event `ev` from happening (such as
  1963. // following a link in the href of the a element, or doing a POST request
  1964. // with page reload when a `<form>` is submitted).
  1965. // Use it inside listener functions.
  1966. function preventDefault(e) {
  1967. if (e.preventDefault) {
  1968. e.preventDefault();
  1969. } else {
  1970. e.returnValue = false;
  1971. }
  1972. return this;
  1973. }
  1974. // @function stop(ev: DOMEvent): this
  1975. // Does `stopPropagation` and `preventDefault` at the same time.
  1976. function stop(e) {
  1977. preventDefault(e);
  1978. stopPropagation(e);
  1979. return this;
  1980. }
  1981. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  1982. // Gets normalized mouse position from a DOM event relative to the
  1983. // `container` or to the whole page if not specified.
  1984. function getMousePosition(e, container) {
  1985. if (!container) {
  1986. return new Point(e.clientX, e.clientY);
  1987. }
  1988. var rect = container.getBoundingClientRect();
  1989. var scaleX = rect.width / container.offsetWidth || 1;
  1990. var scaleY = rect.height / container.offsetHeight || 1;
  1991. return new Point(
  1992. e.clientX / scaleX - rect.left - container.clientLeft,
  1993. e.clientY / scaleY - rect.top - container.clientTop);
  1994. }
  1995. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  1996. // and Firefox scrolls device pixels, not CSS pixels
  1997. var wheelPxFactor =
  1998. (win && chrome) ? 2 * window.devicePixelRatio :
  1999. gecko ? window.devicePixelRatio : 1;
  2000. // @function getWheelDelta(ev: DOMEvent): Number
  2001. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2002. // pixels scrolled (negative if scrolling down).
  2003. // Events from pointing devices without precise scrolling are mapped to
  2004. // a best guess of 60 pixels.
  2005. function getWheelDelta(e) {
  2006. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2007. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2008. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2009. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2010. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2011. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2012. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2013. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2014. 0;
  2015. }
  2016. var skipEvents = {};
  2017. function fakeStop(e) {
  2018. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2019. skipEvents[e.type] = true;
  2020. }
  2021. function skipped(e) {
  2022. var events = skipEvents[e.type];
  2023. // reset when checking, as it's only used in map container and propagates outside of the map
  2024. skipEvents[e.type] = false;
  2025. return events;
  2026. }
  2027. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2028. function isExternalTarget(el, e) {
  2029. var related = e.relatedTarget;
  2030. if (!related) { return true; }
  2031. try {
  2032. while (related && (related !== el)) {
  2033. related = related.parentNode;
  2034. }
  2035. } catch (err) {
  2036. return false;
  2037. }
  2038. return (related !== el);
  2039. }
  2040. var lastClick;
  2041. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2042. function filterClick(e, handler) {
  2043. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2044. elapsed = lastClick && (timeStamp - lastClick);
  2045. // are they closer together than 500ms yet more than 100ms?
  2046. // Android typically triggers them ~300ms apart while multiple listeners
  2047. // on the same event should be triggered far faster;
  2048. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2049. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2050. stop(e);
  2051. return;
  2052. }
  2053. lastClick = timeStamp;
  2054. handler(e);
  2055. }
  2056. var DomEvent = (Object.freeze || Object)({
  2057. on: on,
  2058. off: off,
  2059. stopPropagation: stopPropagation,
  2060. disableScrollPropagation: disableScrollPropagation,
  2061. disableClickPropagation: disableClickPropagation,
  2062. preventDefault: preventDefault,
  2063. stop: stop,
  2064. getMousePosition: getMousePosition,
  2065. getWheelDelta: getWheelDelta,
  2066. fakeStop: fakeStop,
  2067. skipped: skipped,
  2068. isExternalTarget: isExternalTarget,
  2069. addListener: on,
  2070. removeListener: off
  2071. });
  2072. /*
  2073. * @namespace DomUtil
  2074. *
  2075. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  2076. * tree, used by Leaflet internally.
  2077. *
  2078. * Most functions expecting or returning a `HTMLElement` also work for
  2079. * SVG elements. The only difference is that classes refer to CSS classes
  2080. * in HTML and SVG classes in SVG.
  2081. */
  2082. // @property TRANSFORM: String
  2083. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  2084. var TRANSFORM = testProp(
  2085. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  2086. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  2087. // the same for the transitionend event, in particular the Android 4.1 stock browser
  2088. // @property TRANSITION: String
  2089. // Vendor-prefixed transition style name.
  2090. var TRANSITION = testProp(
  2091. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  2092. // @property TRANSITION_END: String
  2093. // Vendor-prefixed transitionend event name.
  2094. var TRANSITION_END =
  2095. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  2096. // @function get(id: String|HTMLElement): HTMLElement
  2097. // Returns an element given its DOM id, or returns the element itself
  2098. // if it was passed directly.
  2099. function get(id) {
  2100. return typeof id === 'string' ? document.getElementById(id) : id;
  2101. }
  2102. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  2103. // Returns the value for a certain style attribute on an element,
  2104. // including computed values or values set through CSS.
  2105. function getStyle(el, style) {
  2106. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  2107. if ((!value || value === 'auto') && document.defaultView) {
  2108. var css = document.defaultView.getComputedStyle(el, null);
  2109. value = css ? css[style] : null;
  2110. }
  2111. return value === 'auto' ? null : value;
  2112. }
  2113. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  2114. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  2115. function create$1(tagName, className, container) {
  2116. var el = document.createElement(tagName);
  2117. el.className = className || '';
  2118. if (container) {
  2119. container.appendChild(el);
  2120. }
  2121. return el;
  2122. }
  2123. // @function remove(el: HTMLElement)
  2124. // Removes `el` from its parent element
  2125. function remove(el) {
  2126. var parent = el.parentNode;
  2127. if (parent) {
  2128. parent.removeChild(el);
  2129. }
  2130. }
  2131. // @function empty(el: HTMLElement)
  2132. // Removes all of `el`'s children elements from `el`
  2133. function empty(el) {
  2134. while (el.firstChild) {
  2135. el.removeChild(el.firstChild);
  2136. }
  2137. }
  2138. // @function toFront(el: HTMLElement)
  2139. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2140. function toFront(el) {
  2141. var parent = el.parentNode;
  2142. if (parent.lastChild !== el) {
  2143. parent.appendChild(el);
  2144. }
  2145. }
  2146. // @function toBack(el: HTMLElement)
  2147. // Makes `el` the first child of its parent, so it renders behind the other children.
  2148. function toBack(el) {
  2149. var parent = el.parentNode;
  2150. if (parent.firstChild !== el) {
  2151. parent.insertBefore(el, parent.firstChild);
  2152. }
  2153. }
  2154. // @function hasClass(el: HTMLElement, name: String): Boolean
  2155. // Returns `true` if the element's class attribute contains `name`.
  2156. function hasClass(el, name) {
  2157. if (el.classList !== undefined) {
  2158. return el.classList.contains(name);
  2159. }
  2160. var className = getClass(el);
  2161. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2162. }
  2163. // @function addClass(el: HTMLElement, name: String)
  2164. // Adds `name` to the element's class attribute.
  2165. function addClass(el, name) {
  2166. if (el.classList !== undefined) {
  2167. var classes = splitWords(name);
  2168. for (var i = 0, len = classes.length; i < len; i++) {
  2169. el.classList.add(classes[i]);
  2170. }
  2171. } else if (!hasClass(el, name)) {
  2172. var className = getClass(el);
  2173. setClass(el, (className ? className + ' ' : '') + name);
  2174. }
  2175. }
  2176. // @function removeClass(el: HTMLElement, name: String)
  2177. // Removes `name` from the element's class attribute.
  2178. function removeClass(el, name) {
  2179. if (el.classList !== undefined) {
  2180. el.classList.remove(name);
  2181. } else {
  2182. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2183. }
  2184. }
  2185. // @function setClass(el: HTMLElement, name: String)
  2186. // Sets the element's class.
  2187. function setClass(el, name) {
  2188. if (el.className.baseVal === undefined) {
  2189. el.className = name;
  2190. } else {
  2191. // in case of SVG element
  2192. el.className.baseVal = name;
  2193. }
  2194. }
  2195. // @function getClass(el: HTMLElement): String
  2196. // Returns the element's class.
  2197. function getClass(el) {
  2198. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2199. }
  2200. // @function setOpacity(el: HTMLElement, opacity: Number)
  2201. // Set the opacity of an element (including old IE support).
  2202. // `opacity` must be a number from `0` to `1`.
  2203. function setOpacity(el, value) {
  2204. if ('opacity' in el.style) {
  2205. el.style.opacity = value;
  2206. } else if ('filter' in el.style) {
  2207. _setOpacityIE(el, value);
  2208. }
  2209. }
  2210. function _setOpacityIE(el, value) {
  2211. var filter = false,
  2212. filterName = 'DXImageTransform.Microsoft.Alpha';
  2213. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2214. try {
  2215. filter = el.filters.item(filterName);
  2216. } catch (e) {
  2217. // don't set opacity to 1 if we haven't already set an opacity,
  2218. // it isn't needed and breaks transparent pngs.
  2219. if (value === 1) { return; }
  2220. }
  2221. value = Math.round(value * 100);
  2222. if (filter) {
  2223. filter.Enabled = (value !== 100);
  2224. filter.Opacity = value;
  2225. } else {
  2226. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2227. }
  2228. }
  2229. // @function testProp(props: String[]): String|false
  2230. // Goes through the array of style names and returns the first name
  2231. // that is a valid style name for an element. If no such name is found,
  2232. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2233. function testProp(props) {
  2234. var style = document.documentElement.style;
  2235. for (var i = 0; i < props.length; i++) {
  2236. if (props[i] in style) {
  2237. return props[i];
  2238. }
  2239. }
  2240. return false;
  2241. }
  2242. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2243. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2244. // and optionally scaled by `scale`. Does not have an effect if the
  2245. // browser doesn't support 3D CSS transforms.
  2246. function setTransform(el, offset, scale) {
  2247. var pos = offset || new Point(0, 0);
  2248. el.style[TRANSFORM] =
  2249. (ie3d ?
  2250. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2251. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2252. (scale ? ' scale(' + scale + ')' : '');
  2253. }
  2254. // @function setPosition(el: HTMLElement, position: Point)
  2255. // Sets the position of `el` to coordinates specified by `position`,
  2256. // using CSS translate or top/left positioning depending on the browser
  2257. // (used by Leaflet internally to position its layers).
  2258. function setPosition(el, point) {
  2259. /*eslint-disable */
  2260. el._leaflet_pos = point;
  2261. /* eslint-enable */
  2262. if (any3d) {
  2263. setTransform(el, point);
  2264. } else {
  2265. el.style.left = point.x + 'px';
  2266. el.style.top = point.y + 'px';
  2267. }
  2268. }
  2269. // @function getPosition(el: HTMLElement): Point
  2270. // Returns the coordinates of an element previously positioned with setPosition.
  2271. function getPosition(el) {
  2272. // this method is only used for elements previously positioned using setPosition,
  2273. // so it's safe to cache the position for performance
  2274. return el._leaflet_pos || new Point(0, 0);
  2275. }
  2276. // @function disableTextSelection()
  2277. // Prevents the user from generating `selectstart` DOM events, usually generated
  2278. // when the user drags the mouse through a page with text. Used internally
  2279. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2280. // the map. Affects drag interactions on the whole document.
  2281. // @function enableTextSelection()
  2282. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2283. var disableTextSelection;
  2284. var enableTextSelection;
  2285. var _userSelect;
  2286. if ('onselectstart' in document) {
  2287. disableTextSelection = function () {
  2288. on(window, 'selectstart', preventDefault);
  2289. };
  2290. enableTextSelection = function () {
  2291. off(window, 'selectstart', preventDefault);
  2292. };
  2293. } else {
  2294. var userSelectProperty = testProp(
  2295. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2296. disableTextSelection = function () {
  2297. if (userSelectProperty) {
  2298. var style = document.documentElement.style;
  2299. _userSelect = style[userSelectProperty];
  2300. style[userSelectProperty] = 'none';
  2301. }
  2302. };
  2303. enableTextSelection = function () {
  2304. if (userSelectProperty) {
  2305. document.documentElement.style[userSelectProperty] = _userSelect;
  2306. _userSelect = undefined;
  2307. }
  2308. };
  2309. }
  2310. // @function disableImageDrag()
  2311. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2312. // for `dragstart` DOM events, usually generated when the user drags an image.
  2313. function disableImageDrag() {
  2314. on(window, 'dragstart', preventDefault);
  2315. }
  2316. // @function enableImageDrag()
  2317. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2318. function enableImageDrag() {
  2319. off(window, 'dragstart', preventDefault);
  2320. }
  2321. var _outlineElement;
  2322. var _outlineStyle;
  2323. // @function preventOutline(el: HTMLElement)
  2324. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2325. // of the element `el` invisible. Used internally by Leaflet to prevent
  2326. // focusable elements from displaying an outline when the user performs a
  2327. // drag interaction on them.
  2328. function preventOutline(element) {
  2329. while (element.tabIndex === -1) {
  2330. element = element.parentNode;
  2331. }
  2332. if (!element.style) { return; }
  2333. restoreOutline();
  2334. _outlineElement = element;
  2335. _outlineStyle = element.style.outline;
  2336. element.style.outline = 'none';
  2337. on(window, 'keydown', restoreOutline);
  2338. }
  2339. // @function restoreOutline()
  2340. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2341. function restoreOutline() {
  2342. if (!_outlineElement) { return; }
  2343. _outlineElement.style.outline = _outlineStyle;
  2344. _outlineElement = undefined;
  2345. _outlineStyle = undefined;
  2346. off(window, 'keydown', restoreOutline);
  2347. }
  2348. var DomUtil = (Object.freeze || Object)({
  2349. TRANSFORM: TRANSFORM,
  2350. TRANSITION: TRANSITION,
  2351. TRANSITION_END: TRANSITION_END,
  2352. get: get,
  2353. getStyle: getStyle,
  2354. create: create$1,
  2355. remove: remove,
  2356. empty: empty,
  2357. toFront: toFront,
  2358. toBack: toBack,
  2359. hasClass: hasClass,
  2360. addClass: addClass,
  2361. removeClass: removeClass,
  2362. setClass: setClass,
  2363. getClass: getClass,
  2364. setOpacity: setOpacity,
  2365. testProp: testProp,
  2366. setTransform: setTransform,
  2367. setPosition: setPosition,
  2368. getPosition: getPosition,
  2369. disableTextSelection: disableTextSelection,
  2370. enableTextSelection: enableTextSelection,
  2371. disableImageDrag: disableImageDrag,
  2372. enableImageDrag: enableImageDrag,
  2373. preventOutline: preventOutline,
  2374. restoreOutline: restoreOutline
  2375. });
  2376. /*
  2377. * @class PosAnimation
  2378. * @aka L.PosAnimation
  2379. * @inherits Evented
  2380. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2381. *
  2382. * @example
  2383. * ```js
  2384. * var fx = new L.PosAnimation();
  2385. * fx.run(el, [300, 500], 0.5);
  2386. * ```
  2387. *
  2388. * @constructor L.PosAnimation()
  2389. * Creates a `PosAnimation` object.
  2390. *
  2391. */
  2392. var PosAnimation = Evented.extend({
  2393. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2394. // Run an animation of a given element to a new position, optionally setting
  2395. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2396. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2397. // `0.5` by default).
  2398. run: function (el, newPos, duration, easeLinearity) {
  2399. this.stop();
  2400. this._el = el;
  2401. this._inProgress = true;
  2402. this._duration = duration || 0.25;
  2403. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2404. this._startPos = getPosition(el);
  2405. this._offset = newPos.subtract(this._startPos);
  2406. this._startTime = +new Date();
  2407. // @event start: Event
  2408. // Fired when the animation starts
  2409. this.fire('start');
  2410. this._animate();
  2411. },
  2412. // @method stop()
  2413. // Stops the animation (if currently running).
  2414. stop: function () {
  2415. if (!this._inProgress) { return; }
  2416. this._step(true);
  2417. this._complete();
  2418. },
  2419. _animate: function () {
  2420. // animation loop
  2421. this._animId = requestAnimFrame(this._animate, this);
  2422. this._step();
  2423. },
  2424. _step: function (round) {
  2425. var elapsed = (+new Date()) - this._startTime,
  2426. duration = this._duration * 1000;
  2427. if (elapsed < duration) {
  2428. this._runFrame(this._easeOut(elapsed / duration), round);
  2429. } else {
  2430. this._runFrame(1);
  2431. this._complete();
  2432. }
  2433. },
  2434. _runFrame: function (progress, round) {
  2435. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2436. if (round) {
  2437. pos._round();
  2438. }
  2439. setPosition(this._el, pos);
  2440. // @event step: Event
  2441. // Fired continuously during the animation.
  2442. this.fire('step');
  2443. },
  2444. _complete: function () {
  2445. cancelAnimFrame(this._animId);
  2446. this._inProgress = false;
  2447. // @event end: Event
  2448. // Fired when the animation ends.
  2449. this.fire('end');
  2450. },
  2451. _easeOut: function (t) {
  2452. return 1 - Math.pow(1 - t, this._easeOutPower);
  2453. }
  2454. });
  2455. /*
  2456. * @class Map
  2457. * @aka L.Map
  2458. * @inherits Evented
  2459. *
  2460. * The central class of the API — it is used to create a map on a page and manipulate it.
  2461. *
  2462. * @example
  2463. *
  2464. * ```js
  2465. * // initialize the map on the "map" div with a given center and zoom
  2466. * var map = L.map('map', {
  2467. * center: [51.505, -0.09],
  2468. * zoom: 13
  2469. * });
  2470. * ```
  2471. *
  2472. */
  2473. var Map = Evented.extend({
  2474. options: {
  2475. // @section Map State Options
  2476. // @option crs: CRS = L.CRS.EPSG3857
  2477. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2478. // sure what it means.
  2479. crs: EPSG3857,
  2480. // @option center: LatLng = undefined
  2481. // Initial geographic center of the map
  2482. center: undefined,
  2483. // @option zoom: Number = undefined
  2484. // Initial map zoom level
  2485. zoom: undefined,
  2486. // @option minZoom: Number = *
  2487. // Minimum zoom level of the map.
  2488. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2489. // the lowest of their `minZoom` options will be used instead.
  2490. minZoom: undefined,
  2491. // @option maxZoom: Number = *
  2492. // Maximum zoom level of the map.
  2493. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2494. // the highest of their `maxZoom` options will be used instead.
  2495. maxZoom: undefined,
  2496. // @option layers: Layer[] = []
  2497. // Array of layers that will be added to the map initially
  2498. layers: [],
  2499. // @option maxBounds: LatLngBounds = null
  2500. // When this option is set, the map restricts the view to the given
  2501. // geographical bounds, bouncing the user back if the user tries to pan
  2502. // outside the view. To set the restriction dynamically, use
  2503. // [`setMaxBounds`](#map-setmaxbounds) method.
  2504. maxBounds: undefined,
  2505. // @option renderer: Renderer = *
  2506. // The default method for drawing vector layers on the map. `L.SVG`
  2507. // or `L.Canvas` by default depending on browser support.
  2508. renderer: undefined,
  2509. // @section Animation Options
  2510. // @option zoomAnimation: Boolean = true
  2511. // Whether the map zoom animation is enabled. By default it's enabled
  2512. // in all browsers that support CSS3 Transitions except Android.
  2513. zoomAnimation: true,
  2514. // @option zoomAnimationThreshold: Number = 4
  2515. // Won't animate zoom if the zoom difference exceeds this value.
  2516. zoomAnimationThreshold: 4,
  2517. // @option fadeAnimation: Boolean = true
  2518. // Whether the tile fade animation is enabled. By default it's enabled
  2519. // in all browsers that support CSS3 Transitions except Android.
  2520. fadeAnimation: true,
  2521. // @option markerZoomAnimation: Boolean = true
  2522. // Whether markers animate their zoom with the zoom animation, if disabled
  2523. // they will disappear for the length of the animation. By default it's
  2524. // enabled in all browsers that support CSS3 Transitions except Android.
  2525. markerZoomAnimation: true,
  2526. // @option transform3DLimit: Number = 2^23
  2527. // Defines the maximum size of a CSS translation transform. The default
  2528. // value should not be changed unless a web browser positions layers in
  2529. // the wrong place after doing a large `panBy`.
  2530. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2531. // @section Interaction Options
  2532. // @option zoomSnap: Number = 1
  2533. // Forces the map's zoom level to always be a multiple of this, particularly
  2534. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2535. // By default, the zoom level snaps to the nearest integer; lower values
  2536. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2537. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2538. zoomSnap: 1,
  2539. // @option zoomDelta: Number = 1
  2540. // Controls how much the map's zoom level will change after a
  2541. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2542. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2543. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2544. zoomDelta: 1,
  2545. // @option trackResize: Boolean = true
  2546. // Whether the map automatically handles browser window resize to update itself.
  2547. trackResize: true
  2548. },
  2549. initialize: function (id, options) { // (HTMLElement or String, Object)
  2550. options = setOptions(this, options);
  2551. this._initContainer(id);
  2552. this._initLayout();
  2553. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2554. this._onResize = bind(this._onResize, this);
  2555. this._initEvents();
  2556. if (options.maxBounds) {
  2557. this.setMaxBounds(options.maxBounds);
  2558. }
  2559. if (options.zoom !== undefined) {
  2560. this._zoom = this._limitZoom(options.zoom);
  2561. }
  2562. if (options.center && options.zoom !== undefined) {
  2563. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2564. }
  2565. this._handlers = [];
  2566. this._layers = {};
  2567. this._zoomBoundLayers = {};
  2568. this._sizeChanged = true;
  2569. this.callInitHooks();
  2570. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2571. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2572. this.options.zoomAnimation;
  2573. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2574. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2575. if (this._zoomAnimated) {
  2576. this._createAnimProxy();
  2577. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2578. }
  2579. this._addLayers(this.options.layers);
  2580. },
  2581. // @section Methods for modifying map state
  2582. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2583. // Sets the view of the map (geographical center and zoom) with the given
  2584. // animation options.
  2585. setView: function (center, zoom, options) {
  2586. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2587. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2588. options = options || {};
  2589. this._stop();
  2590. if (this._loaded && !options.reset && options !== true) {
  2591. if (options.animate !== undefined) {
  2592. options.zoom = extend({animate: options.animate}, options.zoom);
  2593. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2594. }
  2595. // try animating pan or zoom
  2596. var moved = (this._zoom !== zoom) ?
  2597. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2598. this._tryAnimatedPan(center, options.pan);
  2599. if (moved) {
  2600. // prevent resize handler call, the view will refresh after animation anyway
  2601. clearTimeout(this._sizeTimer);
  2602. return this;
  2603. }
  2604. }
  2605. // animation didn't start, just reset the map view
  2606. this._resetView(center, zoom);
  2607. return this;
  2608. },
  2609. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2610. // Sets the zoom of the map.
  2611. setZoom: function (zoom, options) {
  2612. if (!this._loaded) {
  2613. this._zoom = zoom;
  2614. return this;
  2615. }
  2616. return this.setView(this.getCenter(), zoom, {zoom: options});
  2617. },
  2618. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2619. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2620. zoomIn: function (delta, options) {
  2621. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2622. return this.setZoom(this._zoom + delta, options);
  2623. },
  2624. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2625. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2626. zoomOut: function (delta, options) {
  2627. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2628. return this.setZoom(this._zoom - delta, options);
  2629. },
  2630. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2631. // Zooms the map while keeping a specified geographical point on the map
  2632. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2633. // @alternative
  2634. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2635. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2636. setZoomAround: function (latlng, zoom, options) {
  2637. var scale = this.getZoomScale(zoom),
  2638. viewHalf = this.getSize().divideBy(2),
  2639. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2640. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2641. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2642. return this.setView(newCenter, zoom, {zoom: options});
  2643. },
  2644. _getBoundsCenterZoom: function (bounds, options) {
  2645. options = options || {};
  2646. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2647. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2648. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2649. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2650. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2651. if (zoom === Infinity) {
  2652. return {
  2653. center: bounds.getCenter(),
  2654. zoom: zoom
  2655. };
  2656. }
  2657. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2658. swPoint = this.project(bounds.getSouthWest(), zoom),
  2659. nePoint = this.project(bounds.getNorthEast(), zoom),
  2660. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2661. return {
  2662. center: center,
  2663. zoom: zoom
  2664. };
  2665. },
  2666. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2667. // Sets a map view that contains the given geographical bounds with the
  2668. // maximum zoom level possible.
  2669. fitBounds: function (bounds, options) {
  2670. bounds = toLatLngBounds(bounds);
  2671. if (!bounds.isValid()) {
  2672. throw new Error('Bounds are not valid.');
  2673. }
  2674. var target = this._getBoundsCenterZoom(bounds, options);
  2675. return this.setView(target.center, target.zoom, options);
  2676. },
  2677. // @method fitWorld(options?: fitBounds options): this
  2678. // Sets a map view that mostly contains the whole world with the maximum
  2679. // zoom level possible.
  2680. fitWorld: function (options) {
  2681. return this.fitBounds([[-90, -180], [90, 180]], options);
  2682. },
  2683. // @method panTo(latlng: LatLng, options?: Pan options): this
  2684. // Pans the map to a given center.
  2685. panTo: function (center, options) { // (LatLng)
  2686. return this.setView(center, this._zoom, {pan: options});
  2687. },
  2688. // @method panBy(offset: Point, options?: Pan options): this
  2689. // Pans the map by a given number of pixels (animated).
  2690. panBy: function (offset, options) {
  2691. offset = toPoint(offset).round();
  2692. options = options || {};
  2693. if (!offset.x && !offset.y) {
  2694. return this.fire('moveend');
  2695. }
  2696. // If we pan too far, Chrome gets issues with tiles
  2697. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2698. if (options.animate !== true && !this.getSize().contains(offset)) {
  2699. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2700. return this;
  2701. }
  2702. if (!this._panAnim) {
  2703. this._panAnim = new PosAnimation();
  2704. this._panAnim.on({
  2705. 'step': this._onPanTransitionStep,
  2706. 'end': this._onPanTransitionEnd
  2707. }, this);
  2708. }
  2709. // don't fire movestart if animating inertia
  2710. if (!options.noMoveStart) {
  2711. this.fire('movestart');
  2712. }
  2713. // animate pan unless animate: false specified
  2714. if (options.animate !== false) {
  2715. addClass(this._mapPane, 'leaflet-pan-anim');
  2716. var newPos = this._getMapPanePos().subtract(offset).round();
  2717. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2718. } else {
  2719. this._rawPanBy(offset);
  2720. this.fire('move').fire('moveend');
  2721. }
  2722. return this;
  2723. },
  2724. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2725. // Sets the view of the map (geographical center and zoom) performing a smooth
  2726. // pan-zoom animation.
  2727. flyTo: function (targetCenter, targetZoom, options) {
  2728. options = options || {};
  2729. if (options.animate === false || !any3d) {
  2730. return this.setView(targetCenter, targetZoom, options);
  2731. }
  2732. this._stop();
  2733. var from = this.project(this.getCenter()),
  2734. to = this.project(targetCenter),
  2735. size = this.getSize(),
  2736. startZoom = this._zoom;
  2737. targetCenter = toLatLng(targetCenter);
  2738. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2739. var w0 = Math.max(size.x, size.y),
  2740. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2741. u1 = (to.distanceTo(from)) || 1,
  2742. rho = 1.42,
  2743. rho2 = rho * rho;
  2744. function r(i) {
  2745. var s1 = i ? -1 : 1,
  2746. s2 = i ? w1 : w0,
  2747. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2748. b1 = 2 * s2 * rho2 * u1,
  2749. b = t1 / b1,
  2750. sq = Math.sqrt(b * b + 1) - b;
  2751. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2752. // thus triggering an infinite loop in flyTo
  2753. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2754. return log;
  2755. }
  2756. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2757. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2758. function tanh(n) { return sinh(n) / cosh(n); }
  2759. var r0 = r(0);
  2760. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2761. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2762. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2763. var start = Date.now(),
  2764. S = (r(1) - r0) / rho,
  2765. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2766. function frame() {
  2767. var t = (Date.now() - start) / duration,
  2768. s = easeOut(t) * S;
  2769. if (t <= 1) {
  2770. this._flyToFrame = requestAnimFrame(frame, this);
  2771. this._move(
  2772. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2773. this.getScaleZoom(w0 / w(s), startZoom),
  2774. {flyTo: true});
  2775. } else {
  2776. this
  2777. ._move(targetCenter, targetZoom)
  2778. ._moveEnd(true);
  2779. }
  2780. }
  2781. this._moveStart(true, options.noMoveStart);
  2782. frame.call(this);
  2783. return this;
  2784. },
  2785. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2786. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2787. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2788. flyToBounds: function (bounds, options) {
  2789. var target = this._getBoundsCenterZoom(bounds, options);
  2790. return this.flyTo(target.center, target.zoom, options);
  2791. },
  2792. // @method setMaxBounds(bounds: Bounds): this
  2793. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2794. setMaxBounds: function (bounds) {
  2795. bounds = toLatLngBounds(bounds);
  2796. if (!bounds.isValid()) {
  2797. this.options.maxBounds = null;
  2798. return this.off('moveend', this._panInsideMaxBounds);
  2799. } else if (this.options.maxBounds) {
  2800. this.off('moveend', this._panInsideMaxBounds);
  2801. }
  2802. this.options.maxBounds = bounds;
  2803. if (this._loaded) {
  2804. this._panInsideMaxBounds();
  2805. }
  2806. return this.on('moveend', this._panInsideMaxBounds);
  2807. },
  2808. // @method setMinZoom(zoom: Number): this
  2809. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2810. setMinZoom: function (zoom) {
  2811. var oldZoom = this.options.minZoom;
  2812. this.options.minZoom = zoom;
  2813. if (this._loaded && oldZoom !== zoom) {
  2814. this.fire('zoomlevelschange');
  2815. if (this.getZoom() < this.options.minZoom) {
  2816. return this.setZoom(zoom);
  2817. }
  2818. }
  2819. return this;
  2820. },
  2821. // @method setMaxZoom(zoom: Number): this
  2822. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2823. setMaxZoom: function (zoom) {
  2824. var oldZoom = this.options.maxZoom;
  2825. this.options.maxZoom = zoom;
  2826. if (this._loaded && oldZoom !== zoom) {
  2827. this.fire('zoomlevelschange');
  2828. if (this.getZoom() > this.options.maxZoom) {
  2829. return this.setZoom(zoom);
  2830. }
  2831. }
  2832. return this;
  2833. },
  2834. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2835. // 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.
  2836. panInsideBounds: function (bounds, options) {
  2837. this._enforcingBounds = true;
  2838. var center = this.getCenter(),
  2839. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2840. if (!center.equals(newCenter)) {
  2841. this.panTo(newCenter, options);
  2842. }
  2843. this._enforcingBounds = false;
  2844. return this;
  2845. },
  2846. // @method invalidateSize(options: Zoom/pan options): this
  2847. // Checks if the map container size changed and updates the map if so —
  2848. // call it after you've changed the map size dynamically, also animating
  2849. // pan by default. If `options.pan` is `false`, panning will not occur.
  2850. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2851. // that it doesn't happen often even if the method is called many
  2852. // times in a row.
  2853. // @alternative
  2854. // @method invalidateSize(animate: Boolean): this
  2855. // Checks if the map container size changed and updates the map if so —
  2856. // call it after you've changed the map size dynamically, also animating
  2857. // pan by default.
  2858. invalidateSize: function (options) {
  2859. if (!this._loaded) { return this; }
  2860. options = extend({
  2861. animate: false,
  2862. pan: true
  2863. }, options === true ? {animate: true} : options);
  2864. var oldSize = this.getSize();
  2865. this._sizeChanged = true;
  2866. this._lastCenter = null;
  2867. var newSize = this.getSize(),
  2868. oldCenter = oldSize.divideBy(2).round(),
  2869. newCenter = newSize.divideBy(2).round(),
  2870. offset = oldCenter.subtract(newCenter);
  2871. if (!offset.x && !offset.y) { return this; }
  2872. if (options.animate && options.pan) {
  2873. this.panBy(offset);
  2874. } else {
  2875. if (options.pan) {
  2876. this._rawPanBy(offset);
  2877. }
  2878. this.fire('move');
  2879. if (options.debounceMoveend) {
  2880. clearTimeout(this._sizeTimer);
  2881. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2882. } else {
  2883. this.fire('moveend');
  2884. }
  2885. }
  2886. // @section Map state change events
  2887. // @event resize: ResizeEvent
  2888. // Fired when the map is resized.
  2889. return this.fire('resize', {
  2890. oldSize: oldSize,
  2891. newSize: newSize
  2892. });
  2893. },
  2894. // @section Methods for modifying map state
  2895. // @method stop(): this
  2896. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2897. stop: function () {
  2898. this.setZoom(this._limitZoom(this._zoom));
  2899. if (!this.options.zoomSnap) {
  2900. this.fire('viewreset');
  2901. }
  2902. return this._stop();
  2903. },
  2904. // @section Geolocation methods
  2905. // @method locate(options?: Locate options): this
  2906. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2907. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2908. // and optionally sets the map view to the user's location with respect to
  2909. // detection accuracy (or to the world view if geolocation failed).
  2910. // Note that, if your page doesn't use HTTPS, this method will fail in
  2911. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2912. // See `Locate options` for more details.
  2913. locate: function (options) {
  2914. options = this._locateOptions = extend({
  2915. timeout: 10000,
  2916. watch: false
  2917. // setView: false
  2918. // maxZoom: <Number>
  2919. // maximumAge: 0
  2920. // enableHighAccuracy: false
  2921. }, options);
  2922. if (!('geolocation' in navigator)) {
  2923. this._handleGeolocationError({
  2924. code: 0,
  2925. message: 'Geolocation not supported.'
  2926. });
  2927. return this;
  2928. }
  2929. var onResponse = bind(this._handleGeolocationResponse, this),
  2930. onError = bind(this._handleGeolocationError, this);
  2931. if (options.watch) {
  2932. this._locationWatchId =
  2933. navigator.geolocation.watchPosition(onResponse, onError, options);
  2934. } else {
  2935. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2936. }
  2937. return this;
  2938. },
  2939. // @method stopLocate(): this
  2940. // Stops watching location previously initiated by `map.locate({watch: true})`
  2941. // and aborts resetting the map view if map.locate was called with
  2942. // `{setView: true}`.
  2943. stopLocate: function () {
  2944. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2945. navigator.geolocation.clearWatch(this._locationWatchId);
  2946. }
  2947. if (this._locateOptions) {
  2948. this._locateOptions.setView = false;
  2949. }
  2950. return this;
  2951. },
  2952. _handleGeolocationError: function (error) {
  2953. var c = error.code,
  2954. message = error.message ||
  2955. (c === 1 ? 'permission denied' :
  2956. (c === 2 ? 'position unavailable' : 'timeout'));
  2957. if (this._locateOptions.setView && !this._loaded) {
  2958. this.fitWorld();
  2959. }
  2960. // @section Location events
  2961. // @event locationerror: ErrorEvent
  2962. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2963. this.fire('locationerror', {
  2964. code: c,
  2965. message: 'Geolocation error: ' + message + '.'
  2966. });
  2967. },
  2968. _handleGeolocationResponse: function (pos) {
  2969. var lat = pos.coords.latitude,
  2970. lng = pos.coords.longitude,
  2971. latlng = new LatLng(lat, lng),
  2972. bounds = latlng.toBounds(pos.coords.accuracy),
  2973. options = this._locateOptions;
  2974. if (options.setView) {
  2975. var zoom = this.getBoundsZoom(bounds);
  2976. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2977. }
  2978. var data = {
  2979. latlng: latlng,
  2980. bounds: bounds,
  2981. timestamp: pos.timestamp
  2982. };
  2983. for (var i in pos.coords) {
  2984. if (typeof pos.coords[i] === 'number') {
  2985. data[i] = pos.coords[i];
  2986. }
  2987. }
  2988. // @event locationfound: LocationEvent
  2989. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2990. // went successfully.
  2991. this.fire('locationfound', data);
  2992. },
  2993. // TODO Appropriate docs section?
  2994. // @section Other Methods
  2995. // @method addHandler(name: String, HandlerClass: Function): this
  2996. // Adds a new `Handler` to the map, given its name and constructor function.
  2997. addHandler: function (name, HandlerClass) {
  2998. if (!HandlerClass) { return this; }
  2999. var handler = this[name] = new HandlerClass(this);
  3000. this._handlers.push(handler);
  3001. if (this.options[name]) {
  3002. handler.enable();
  3003. }
  3004. return this;
  3005. },
  3006. // @method remove(): this
  3007. // Destroys the map and clears all related event listeners.
  3008. remove: function () {
  3009. this._initEvents(true);
  3010. if (this._containerId !== this._container._leaflet_id) {
  3011. throw new Error('Map container is being reused by another instance');
  3012. }
  3013. try {
  3014. // throws error in IE6-8
  3015. delete this._container._leaflet_id;
  3016. delete this._containerId;
  3017. } catch (e) {
  3018. /*eslint-disable */
  3019. this._container._leaflet_id = undefined;
  3020. /* eslint-enable */
  3021. this._containerId = undefined;
  3022. }
  3023. if (this._locationWatchId !== undefined) {
  3024. this.stopLocate();
  3025. }
  3026. this._stop();
  3027. remove(this._mapPane);
  3028. if (this._clearControlPos) {
  3029. this._clearControlPos();
  3030. }
  3031. this._clearHandlers();
  3032. if (this._loaded) {
  3033. // @section Map state change events
  3034. // @event unload: Event
  3035. // Fired when the map is destroyed with [remove](#map-remove) method.
  3036. this.fire('unload');
  3037. }
  3038. var i;
  3039. for (i in this._layers) {
  3040. this._layers[i].remove();
  3041. }
  3042. for (i in this._panes) {
  3043. remove(this._panes[i]);
  3044. }
  3045. this._layers = [];
  3046. this._panes = [];
  3047. delete this._mapPane;
  3048. delete this._renderer;
  3049. return this;
  3050. },
  3051. // @section Other Methods
  3052. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3053. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3054. // then returns it. The pane is created as a child of `container`, or
  3055. // as a child of the main map pane if not set.
  3056. createPane: function (name, container) {
  3057. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3058. pane = create$1('div', className, container || this._mapPane);
  3059. if (name) {
  3060. this._panes[name] = pane;
  3061. }
  3062. return pane;
  3063. },
  3064. // @section Methods for Getting Map State
  3065. // @method getCenter(): LatLng
  3066. // Returns the geographical center of the map view
  3067. getCenter: function () {
  3068. this._checkIfLoaded();
  3069. if (this._lastCenter && !this._moved()) {
  3070. return this._lastCenter;
  3071. }
  3072. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3073. },
  3074. // @method getZoom(): Number
  3075. // Returns the current zoom level of the map view
  3076. getZoom: function () {
  3077. return this._zoom;
  3078. },
  3079. // @method getBounds(): LatLngBounds
  3080. // Returns the geographical bounds visible in the current map view
  3081. getBounds: function () {
  3082. var bounds = this.getPixelBounds(),
  3083. sw = this.unproject(bounds.getBottomLeft()),
  3084. ne = this.unproject(bounds.getTopRight());
  3085. return new LatLngBounds(sw, ne);
  3086. },
  3087. // @method getMinZoom(): Number
  3088. // 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.
  3089. getMinZoom: function () {
  3090. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3091. },
  3092. // @method getMaxZoom(): Number
  3093. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3094. getMaxZoom: function () {
  3095. return this.options.maxZoom === undefined ?
  3096. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3097. this.options.maxZoom;
  3098. },
  3099. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  3100. // Returns the maximum zoom level on which the given bounds fit to the map
  3101. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3102. // instead returns the minimum zoom level on which the map view fits into
  3103. // the given bounds in its entirety.
  3104. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3105. bounds = toLatLngBounds(bounds);
  3106. padding = toPoint(padding || [0, 0]);
  3107. var zoom = this.getZoom() || 0,
  3108. min = this.getMinZoom(),
  3109. max = this.getMaxZoom(),
  3110. nw = bounds.getNorthWest(),
  3111. se = bounds.getSouthEast(),
  3112. size = this.getSize().subtract(padding),
  3113. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3114. snap = any3d ? this.options.zoomSnap : 1,
  3115. scalex = size.x / boundsSize.x,
  3116. scaley = size.y / boundsSize.y,
  3117. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3118. zoom = this.getScaleZoom(scale, zoom);
  3119. if (snap) {
  3120. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3121. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3122. }
  3123. return Math.max(min, Math.min(max, zoom));
  3124. },
  3125. // @method getSize(): Point
  3126. // Returns the current size of the map container (in pixels).
  3127. getSize: function () {
  3128. if (!this._size || this._sizeChanged) {
  3129. this._size = new Point(
  3130. this._container.clientWidth || 0,
  3131. this._container.clientHeight || 0);
  3132. this._sizeChanged = false;
  3133. }
  3134. return this._size.clone();
  3135. },
  3136. // @method getPixelBounds(): Bounds
  3137. // Returns the bounds of the current map view in projected pixel
  3138. // coordinates (sometimes useful in layer and overlay implementations).
  3139. getPixelBounds: function (center, zoom) {
  3140. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3141. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3142. },
  3143. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3144. // the map pane? "left point of the map layer" can be confusing, specially
  3145. // since there can be negative offsets.
  3146. // @method getPixelOrigin(): Point
  3147. // Returns the projected pixel coordinates of the top left point of
  3148. // the map layer (useful in custom layer and overlay implementations).
  3149. getPixelOrigin: function () {
  3150. this._checkIfLoaded();
  3151. return this._pixelOrigin;
  3152. },
  3153. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3154. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3155. // If `zoom` is omitted, the map's current zoom level is used.
  3156. getPixelWorldBounds: function (zoom) {
  3157. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3158. },
  3159. // @section Other Methods
  3160. // @method getPane(pane: String|HTMLElement): HTMLElement
  3161. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3162. getPane: function (pane) {
  3163. return typeof pane === 'string' ? this._panes[pane] : pane;
  3164. },
  3165. // @method getPanes(): Object
  3166. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3167. // the panes as values.
  3168. getPanes: function () {
  3169. return this._panes;
  3170. },
  3171. // @method getContainer: HTMLElement
  3172. // Returns the HTML element that contains the map.
  3173. getContainer: function () {
  3174. return this._container;
  3175. },
  3176. // @section Conversion Methods
  3177. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3178. // Returns the scale factor to be applied to a map transition from zoom level
  3179. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3180. getZoomScale: function (toZoom, fromZoom) {
  3181. // TODO replace with universal implementation after refactoring projections
  3182. var crs = this.options.crs;
  3183. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3184. return crs.scale(toZoom) / crs.scale(fromZoom);
  3185. },
  3186. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3187. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3188. // level and everything is scaled by a factor of `scale`. Inverse of
  3189. // [`getZoomScale`](#map-getZoomScale).
  3190. getScaleZoom: function (scale, fromZoom) {
  3191. var crs = this.options.crs;
  3192. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3193. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3194. return isNaN(zoom) ? Infinity : zoom;
  3195. },
  3196. // @method project(latlng: LatLng, zoom: Number): Point
  3197. // Projects a geographical coordinate `LatLng` according to the projection
  3198. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3199. // `Transformation`. The result is pixel coordinate relative to
  3200. // the CRS origin.
  3201. project: function (latlng, zoom) {
  3202. zoom = zoom === undefined ? this._zoom : zoom;
  3203. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3204. },
  3205. // @method unproject(point: Point, zoom: Number): LatLng
  3206. // Inverse of [`project`](#map-project).
  3207. unproject: function (point, zoom) {
  3208. zoom = zoom === undefined ? this._zoom : zoom;
  3209. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3210. },
  3211. // @method layerPointToLatLng(point: Point): LatLng
  3212. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3213. // returns the corresponding geographical coordinate (for the current zoom level).
  3214. layerPointToLatLng: function (point) {
  3215. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3216. return this.unproject(projectedPoint);
  3217. },
  3218. // @method latLngToLayerPoint(latlng: LatLng): Point
  3219. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3220. // relative to the [origin pixel](#map-getpixelorigin).
  3221. latLngToLayerPoint: function (latlng) {
  3222. var projectedPoint = this.project(toLatLng(latlng))._round();
  3223. return projectedPoint._subtract(this.getPixelOrigin());
  3224. },
  3225. // @method wrapLatLng(latlng: LatLng): LatLng
  3226. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3227. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3228. // CRS's bounds.
  3229. // By default this means longitude is wrapped around the dateline so its
  3230. // value is between -180 and +180 degrees.
  3231. wrapLatLng: function (latlng) {
  3232. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3233. },
  3234. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3235. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3236. // its center is within the CRS's bounds.
  3237. // By default this means the center longitude is wrapped around the dateline so its
  3238. // value is between -180 and +180 degrees, and the majority of the bounds
  3239. // overlaps the CRS's bounds.
  3240. wrapLatLngBounds: function (latlng) {
  3241. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3242. },
  3243. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3244. // Returns the distance between two geographical coordinates according to
  3245. // the map's CRS. By default this measures distance in meters.
  3246. distance: function (latlng1, latlng2) {
  3247. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3248. },
  3249. // @method containerPointToLayerPoint(point: Point): Point
  3250. // Given a pixel coordinate relative to the map container, returns the corresponding
  3251. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3252. containerPointToLayerPoint: function (point) { // (Point)
  3253. return toPoint(point).subtract(this._getMapPanePos());
  3254. },
  3255. // @method layerPointToContainerPoint(point: Point): Point
  3256. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3257. // returns the corresponding pixel coordinate relative to the map container.
  3258. layerPointToContainerPoint: function (point) { // (Point)
  3259. return toPoint(point).add(this._getMapPanePos());
  3260. },
  3261. // @method containerPointToLatLng(point: Point): LatLng
  3262. // Given a pixel coordinate relative to the map container, returns
  3263. // the corresponding geographical coordinate (for the current zoom level).
  3264. containerPointToLatLng: function (point) {
  3265. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3266. return this.layerPointToLatLng(layerPoint);
  3267. },
  3268. // @method latLngToContainerPoint(latlng: LatLng): Point
  3269. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3270. // relative to the map container.
  3271. latLngToContainerPoint: function (latlng) {
  3272. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3273. },
  3274. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3275. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3276. // map container where the event took place.
  3277. mouseEventToContainerPoint: function (e) {
  3278. return getMousePosition(e, this._container);
  3279. },
  3280. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3281. // Given a MouseEvent object, returns the pixel coordinate relative to
  3282. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3283. mouseEventToLayerPoint: function (e) {
  3284. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3285. },
  3286. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3287. // Given a MouseEvent object, returns geographical coordinate where the
  3288. // event took place.
  3289. mouseEventToLatLng: function (e) { // (MouseEvent)
  3290. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3291. },
  3292. // map initialization methods
  3293. _initContainer: function (id) {
  3294. var container = this._container = get(id);
  3295. if (!container) {
  3296. throw new Error('Map container not found.');
  3297. } else if (container._leaflet_id) {
  3298. throw new Error('Map container is already initialized.');
  3299. }
  3300. on(container, 'scroll', this._onScroll, this);
  3301. this._containerId = stamp(container);
  3302. },
  3303. _initLayout: function () {
  3304. var container = this._container;
  3305. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3306. addClass(container, 'leaflet-container' +
  3307. (touch ? ' leaflet-touch' : '') +
  3308. (retina ? ' leaflet-retina' : '') +
  3309. (ielt9 ? ' leaflet-oldie' : '') +
  3310. (safari ? ' leaflet-safari' : '') +
  3311. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3312. var position = getStyle(container, 'position');
  3313. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3314. container.style.position = 'relative';
  3315. }
  3316. this._initPanes();
  3317. if (this._initControlPos) {
  3318. this._initControlPos();
  3319. }
  3320. },
  3321. _initPanes: function () {
  3322. var panes = this._panes = {};
  3323. this._paneRenderers = {};
  3324. // @section
  3325. //
  3326. // Panes are DOM elements used to control the ordering of layers on the map. You
  3327. // can access panes with [`map.getPane`](#map-getpane) or
  3328. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3329. // [`map.createPane`](#map-createpane) method.
  3330. //
  3331. // Every map has the following default panes that differ only in zIndex.
  3332. //
  3333. // @pane mapPane: HTMLElement = 'auto'
  3334. // Pane that contains all other map panes
  3335. this._mapPane = this.createPane('mapPane', this._container);
  3336. setPosition(this._mapPane, new Point(0, 0));
  3337. // @pane tilePane: HTMLElement = 200
  3338. // Pane for `GridLayer`s and `TileLayer`s
  3339. this.createPane('tilePane');
  3340. // @pane overlayPane: HTMLElement = 400
  3341. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3342. this.createPane('shadowPane');
  3343. // @pane shadowPane: HTMLElement = 500
  3344. // Pane for overlay shadows (e.g. `Marker` shadows)
  3345. this.createPane('overlayPane');
  3346. // @pane markerPane: HTMLElement = 600
  3347. // Pane for `Icon`s of `Marker`s
  3348. this.createPane('markerPane');
  3349. // @pane tooltipPane: HTMLElement = 650
  3350. // Pane for `Tooltip`s.
  3351. this.createPane('tooltipPane');
  3352. // @pane popupPane: HTMLElement = 700
  3353. // Pane for `Popup`s.
  3354. this.createPane('popupPane');
  3355. if (!this.options.markerZoomAnimation) {
  3356. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3357. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3358. }
  3359. },
  3360. // private methods that modify map state
  3361. // @section Map state change events
  3362. _resetView: function (center, zoom) {
  3363. setPosition(this._mapPane, new Point(0, 0));
  3364. var loading = !this._loaded;
  3365. this._loaded = true;
  3366. zoom = this._limitZoom(zoom);
  3367. this.fire('viewprereset');
  3368. var zoomChanged = this._zoom !== zoom;
  3369. this
  3370. ._moveStart(zoomChanged, false)
  3371. ._move(center, zoom)
  3372. ._moveEnd(zoomChanged);
  3373. // @event viewreset: Event
  3374. // Fired when the map needs to redraw its content (this usually happens
  3375. // on map zoom or load). Very useful for creating custom overlays.
  3376. this.fire('viewreset');
  3377. // @event load: Event
  3378. // Fired when the map is initialized (when its center and zoom are set
  3379. // for the first time).
  3380. if (loading) {
  3381. this.fire('load');
  3382. }
  3383. },
  3384. _moveStart: function (zoomChanged, noMoveStart) {
  3385. // @event zoomstart: Event
  3386. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3387. // @event movestart: Event
  3388. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3389. if (zoomChanged) {
  3390. this.fire('zoomstart');
  3391. }
  3392. if (!noMoveStart) {
  3393. this.fire('movestart');
  3394. }
  3395. return this;
  3396. },
  3397. _move: function (center, zoom, data) {
  3398. if (zoom === undefined) {
  3399. zoom = this._zoom;
  3400. }
  3401. var zoomChanged = this._zoom !== zoom;
  3402. this._zoom = zoom;
  3403. this._lastCenter = center;
  3404. this._pixelOrigin = this._getNewPixelOrigin(center);
  3405. // @event zoom: Event
  3406. // Fired repeatedly during any change in zoom level, including zoom
  3407. // and fly animations.
  3408. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3409. this.fire('zoom', data);
  3410. }
  3411. // @event move: Event
  3412. // Fired repeatedly during any movement of the map, including pan and
  3413. // fly animations.
  3414. return this.fire('move', data);
  3415. },
  3416. _moveEnd: function (zoomChanged) {
  3417. // @event zoomend: Event
  3418. // Fired when the map has changed, after any animations.
  3419. if (zoomChanged) {
  3420. this.fire('zoomend');
  3421. }
  3422. // @event moveend: Event
  3423. // Fired when the center of the map stops changing (e.g. user stopped
  3424. // dragging the map).
  3425. return this.fire('moveend');
  3426. },
  3427. _stop: function () {
  3428. cancelAnimFrame(this._flyToFrame);
  3429. if (this._panAnim) {
  3430. this._panAnim.stop();
  3431. }
  3432. return this;
  3433. },
  3434. _rawPanBy: function (offset) {
  3435. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3436. },
  3437. _getZoomSpan: function () {
  3438. return this.getMaxZoom() - this.getMinZoom();
  3439. },
  3440. _panInsideMaxBounds: function () {
  3441. if (!this._enforcingBounds) {
  3442. this.panInsideBounds(this.options.maxBounds);
  3443. }
  3444. },
  3445. _checkIfLoaded: function () {
  3446. if (!this._loaded) {
  3447. throw new Error('Set map center and zoom first.');
  3448. }
  3449. },
  3450. // DOM event handling
  3451. // @section Interaction events
  3452. _initEvents: function (remove$$1) {
  3453. this._targets = {};
  3454. this._targets[stamp(this._container)] = this;
  3455. var onOff = remove$$1 ? off : on;
  3456. // @event click: MouseEvent
  3457. // Fired when the user clicks (or taps) the map.
  3458. // @event dblclick: MouseEvent
  3459. // Fired when the user double-clicks (or double-taps) the map.
  3460. // @event mousedown: MouseEvent
  3461. // Fired when the user pushes the mouse button on the map.
  3462. // @event mouseup: MouseEvent
  3463. // Fired when the user releases the mouse button on the map.
  3464. // @event mouseover: MouseEvent
  3465. // Fired when the mouse enters the map.
  3466. // @event mouseout: MouseEvent
  3467. // Fired when the mouse leaves the map.
  3468. // @event mousemove: MouseEvent
  3469. // Fired while the mouse moves over the map.
  3470. // @event contextmenu: MouseEvent
  3471. // Fired when the user pushes the right mouse button on the map, prevents
  3472. // default browser context menu from showing if there are listeners on
  3473. // this event. Also fired on mobile when the user holds a single touch
  3474. // for a second (also called long press).
  3475. // @event keypress: KeyboardEvent
  3476. // Fired when the user presses a key from the keyboard while the map is focused.
  3477. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3478. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  3479. if (this.options.trackResize) {
  3480. onOff(window, 'resize', this._onResize, this);
  3481. }
  3482. if (any3d && this.options.transform3DLimit) {
  3483. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3484. }
  3485. },
  3486. _onResize: function () {
  3487. cancelAnimFrame(this._resizeRequest);
  3488. this._resizeRequest = requestAnimFrame(
  3489. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3490. },
  3491. _onScroll: function () {
  3492. this._container.scrollTop = 0;
  3493. this._container.scrollLeft = 0;
  3494. },
  3495. _onMoveEnd: function () {
  3496. var pos = this._getMapPanePos();
  3497. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3498. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3499. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3500. this._resetView(this.getCenter(), this.getZoom());
  3501. }
  3502. },
  3503. _findEventTargets: function (e, type) {
  3504. var targets = [],
  3505. target,
  3506. isHover = type === 'mouseout' || type === 'mouseover',
  3507. src = e.target || e.srcElement,
  3508. dragging = false;
  3509. while (src) {
  3510. target = this._targets[stamp(src)];
  3511. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3512. // Prevent firing click after you just dragged an object.
  3513. dragging = true;
  3514. break;
  3515. }
  3516. if (target && target.listens(type, true)) {
  3517. if (isHover && !isExternalTarget(src, e)) { break; }
  3518. targets.push(target);
  3519. if (isHover) { break; }
  3520. }
  3521. if (src === this._container) { break; }
  3522. src = src.parentNode;
  3523. }
  3524. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3525. targets = [this];
  3526. }
  3527. return targets;
  3528. },
  3529. _handleDOMEvent: function (e) {
  3530. if (!this._loaded || skipped(e)) { return; }
  3531. var type = e.type;
  3532. if (type === 'mousedown' || type === 'keypress') {
  3533. // prevents outline when clicking on keyboard-focusable element
  3534. preventOutline(e.target || e.srcElement);
  3535. }
  3536. this._fireDOMEvent(e, type);
  3537. },
  3538. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3539. _fireDOMEvent: function (e, type, targets) {
  3540. if (e.type === 'click') {
  3541. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3542. // @event preclick: MouseEvent
  3543. // Fired before mouse click on the map (sometimes useful when you
  3544. // want something to happen on click before any existing click
  3545. // handlers start running).
  3546. var synth = extend({}, e);
  3547. synth.type = 'preclick';
  3548. this._fireDOMEvent(synth, synth.type, targets);
  3549. }
  3550. if (e._stopped) { return; }
  3551. // Find the layer the event is propagating from and its parents.
  3552. targets = (targets || []).concat(this._findEventTargets(e, type));
  3553. if (!targets.length) { return; }
  3554. var target = targets[0];
  3555. if (type === 'contextmenu' && target.listens(type, true)) {
  3556. preventDefault(e);
  3557. }
  3558. var data = {
  3559. originalEvent: e
  3560. };
  3561. if (e.type !== 'keypress') {
  3562. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3563. data.containerPoint = isMarker ?
  3564. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3565. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3566. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3567. }
  3568. for (var i = 0; i < targets.length; i++) {
  3569. targets[i].fire(type, data, true);
  3570. if (data.originalEvent._stopped ||
  3571. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3572. }
  3573. },
  3574. _draggableMoved: function (obj) {
  3575. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3576. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3577. },
  3578. _clearHandlers: function () {
  3579. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3580. this._handlers[i].disable();
  3581. }
  3582. },
  3583. // @section Other Methods
  3584. // @method whenReady(fn: Function, context?: Object): this
  3585. // Runs the given function `fn` when the map gets initialized with
  3586. // a view (center and zoom) and at least one layer, or immediately
  3587. // if it's already initialized, optionally passing a function context.
  3588. whenReady: function (callback, context) {
  3589. if (this._loaded) {
  3590. callback.call(context || this, {target: this});
  3591. } else {
  3592. this.on('load', callback, context);
  3593. }
  3594. return this;
  3595. },
  3596. // private methods for getting map state
  3597. _getMapPanePos: function () {
  3598. return getPosition(this._mapPane) || new Point(0, 0);
  3599. },
  3600. _moved: function () {
  3601. var pos = this._getMapPanePos();
  3602. return pos && !pos.equals([0, 0]);
  3603. },
  3604. _getTopLeftPoint: function (center, zoom) {
  3605. var pixelOrigin = center && zoom !== undefined ?
  3606. this._getNewPixelOrigin(center, zoom) :
  3607. this.getPixelOrigin();
  3608. return pixelOrigin.subtract(this._getMapPanePos());
  3609. },
  3610. _getNewPixelOrigin: function (center, zoom) {
  3611. var viewHalf = this.getSize()._divideBy(2);
  3612. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3613. },
  3614. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3615. var topLeft = this._getNewPixelOrigin(center, zoom);
  3616. return this.project(latlng, zoom)._subtract(topLeft);
  3617. },
  3618. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3619. var topLeft = this._getNewPixelOrigin(center, zoom);
  3620. return toBounds([
  3621. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3622. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3623. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3624. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3625. ]);
  3626. },
  3627. // layer point of the current center
  3628. _getCenterLayerPoint: function () {
  3629. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3630. },
  3631. // offset of the specified place to the current center in pixels
  3632. _getCenterOffset: function (latlng) {
  3633. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3634. },
  3635. // adjust center for view to get inside bounds
  3636. _limitCenter: function (center, zoom, bounds) {
  3637. if (!bounds) { return center; }
  3638. var centerPoint = this.project(center, zoom),
  3639. viewHalf = this.getSize().divideBy(2),
  3640. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3641. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3642. // If offset is less than a pixel, ignore.
  3643. // This prevents unstable projections from getting into
  3644. // an infinite loop of tiny offsets.
  3645. if (offset.round().equals([0, 0])) {
  3646. return center;
  3647. }
  3648. return this.unproject(centerPoint.add(offset), zoom);
  3649. },
  3650. // adjust offset for view to get inside bounds
  3651. _limitOffset: function (offset, bounds) {
  3652. if (!bounds) { return offset; }
  3653. var viewBounds = this.getPixelBounds(),
  3654. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3655. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3656. },
  3657. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3658. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3659. var projectedMaxBounds = toBounds(
  3660. this.project(maxBounds.getNorthEast(), zoom),
  3661. this.project(maxBounds.getSouthWest(), zoom)
  3662. ),
  3663. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3664. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3665. dx = this._rebound(minOffset.x, -maxOffset.x),
  3666. dy = this._rebound(minOffset.y, -maxOffset.y);
  3667. return new Point(dx, dy);
  3668. },
  3669. _rebound: function (left, right) {
  3670. return left + right > 0 ?
  3671. Math.round(left - right) / 2 :
  3672. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3673. },
  3674. _limitZoom: function (zoom) {
  3675. var min = this.getMinZoom(),
  3676. max = this.getMaxZoom(),
  3677. snap = any3d ? this.options.zoomSnap : 1;
  3678. if (snap) {
  3679. zoom = Math.round(zoom / snap) * snap;
  3680. }
  3681. return Math.max(min, Math.min(max, zoom));
  3682. },
  3683. _onPanTransitionStep: function () {
  3684. this.fire('move');
  3685. },
  3686. _onPanTransitionEnd: function () {
  3687. removeClass(this._mapPane, 'leaflet-pan-anim');
  3688. this.fire('moveend');
  3689. },
  3690. _tryAnimatedPan: function (center, options) {
  3691. // difference between the new and current centers in pixels
  3692. var offset = this._getCenterOffset(center)._trunc();
  3693. // don't animate too far unless animate: true specified in options
  3694. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3695. this.panBy(offset, options);
  3696. return true;
  3697. },
  3698. _createAnimProxy: function () {
  3699. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3700. this._panes.mapPane.appendChild(proxy);
  3701. this.on('zoomanim', function (e) {
  3702. var prop = TRANSFORM,
  3703. transform = this._proxy.style[prop];
  3704. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3705. // workaround for case when transform is the same and so transitionend event is not fired
  3706. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3707. this._onZoomTransitionEnd();
  3708. }
  3709. }, this);
  3710. this.on('load moveend', function () {
  3711. var c = this.getCenter(),
  3712. z = this.getZoom();
  3713. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3714. }, this);
  3715. this._on('unload', this._destroyAnimProxy, this);
  3716. },
  3717. _destroyAnimProxy: function () {
  3718. remove(this._proxy);
  3719. delete this._proxy;
  3720. },
  3721. _catchTransitionEnd: function (e) {
  3722. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3723. this._onZoomTransitionEnd();
  3724. }
  3725. },
  3726. _nothingToAnimate: function () {
  3727. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3728. },
  3729. _tryAnimatedZoom: function (center, zoom, options) {
  3730. if (this._animatingZoom) { return true; }
  3731. options = options || {};
  3732. // don't animate if disabled, not supported or zoom difference is too large
  3733. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3734. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3735. // offset is the pixel coords of the zoom origin relative to the current center
  3736. var scale = this.getZoomScale(zoom),
  3737. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3738. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3739. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3740. requestAnimFrame(function () {
  3741. this
  3742. ._moveStart(true, false)
  3743. ._animateZoom(center, zoom, true);
  3744. }, this);
  3745. return true;
  3746. },
  3747. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3748. if (!this._mapPane) { return; }
  3749. if (startAnim) {
  3750. this._animatingZoom = true;
  3751. // remember what center/zoom to set after animation
  3752. this._animateToCenter = center;
  3753. this._animateToZoom = zoom;
  3754. addClass(this._mapPane, 'leaflet-zoom-anim');
  3755. }
  3756. // @event zoomanim: ZoomAnimEvent
  3757. // Fired on every frame of a zoom animation
  3758. this.fire('zoomanim', {
  3759. center: center,
  3760. zoom: zoom,
  3761. noUpdate: noUpdate
  3762. });
  3763. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3764. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3765. },
  3766. _onZoomTransitionEnd: function () {
  3767. if (!this._animatingZoom) { return; }
  3768. if (this._mapPane) {
  3769. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3770. }
  3771. this._animatingZoom = false;
  3772. this._move(this._animateToCenter, this._animateToZoom);
  3773. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3774. requestAnimFrame(function () {
  3775. this._moveEnd(true);
  3776. }, this);
  3777. }
  3778. });
  3779. // @section
  3780. // @factory L.map(id: String, options?: Map options)
  3781. // Instantiates a map object given the DOM ID of a `<div>` element
  3782. // and optionally an object literal with `Map options`.
  3783. //
  3784. // @alternative
  3785. // @factory L.map(el: HTMLElement, options?: Map options)
  3786. // Instantiates a map object given an instance of a `<div>` HTML element
  3787. // and optionally an object literal with `Map options`.
  3788. function createMap(id, options) {
  3789. return new Map(id, options);
  3790. }
  3791. /*
  3792. * @class Control
  3793. * @aka L.Control
  3794. * @inherits Class
  3795. *
  3796. * L.Control is a base class for implementing map controls. Handles positioning.
  3797. * All other controls extend from this class.
  3798. */
  3799. var Control = Class.extend({
  3800. // @section
  3801. // @aka Control options
  3802. options: {
  3803. // @option position: String = 'topright'
  3804. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3805. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3806. position: 'topright'
  3807. },
  3808. initialize: function (options) {
  3809. setOptions(this, options);
  3810. },
  3811. /* @section
  3812. * Classes extending L.Control will inherit the following methods:
  3813. *
  3814. * @method getPosition: string
  3815. * Returns the position of the control.
  3816. */
  3817. getPosition: function () {
  3818. return this.options.position;
  3819. },
  3820. // @method setPosition(position: string): this
  3821. // Sets the position of the control.
  3822. setPosition: function (position) {
  3823. var map = this._map;
  3824. if (map) {
  3825. map.removeControl(this);
  3826. }
  3827. this.options.position = position;
  3828. if (map) {
  3829. map.addControl(this);
  3830. }
  3831. return this;
  3832. },
  3833. // @method getContainer: HTMLElement
  3834. // Returns the HTMLElement that contains the control.
  3835. getContainer: function () {
  3836. return this._container;
  3837. },
  3838. // @method addTo(map: Map): this
  3839. // Adds the control to the given map.
  3840. addTo: function (map) {
  3841. this.remove();
  3842. this._map = map;
  3843. var container = this._container = this.onAdd(map),
  3844. pos = this.getPosition(),
  3845. corner = map._controlCorners[pos];
  3846. addClass(container, 'leaflet-control');
  3847. if (pos.indexOf('bottom') !== -1) {
  3848. corner.insertBefore(container, corner.firstChild);
  3849. } else {
  3850. corner.appendChild(container);
  3851. }
  3852. return this;
  3853. },
  3854. // @method remove: this
  3855. // Removes the control from the map it is currently active on.
  3856. remove: function () {
  3857. if (!this._map) {
  3858. return this;
  3859. }
  3860. remove(this._container);
  3861. if (this.onRemove) {
  3862. this.onRemove(this._map);
  3863. }
  3864. this._map = null;
  3865. return this;
  3866. },
  3867. _refocusOnMap: function (e) {
  3868. // if map exists and event is not a keyboard event
  3869. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3870. this._map.getContainer().focus();
  3871. }
  3872. }
  3873. });
  3874. var control = function (options) {
  3875. return new Control(options);
  3876. };
  3877. /* @section Extension methods
  3878. * @uninheritable
  3879. *
  3880. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3881. *
  3882. * @method onAdd(map: Map): HTMLElement
  3883. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3884. *
  3885. * @method onRemove(map: Map)
  3886. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3887. */
  3888. /* @namespace Map
  3889. * @section Methods for Layers and Controls
  3890. */
  3891. Map.include({
  3892. // @method addControl(control: Control): this
  3893. // Adds the given control to the map
  3894. addControl: function (control) {
  3895. control.addTo(this);
  3896. return this;
  3897. },
  3898. // @method removeControl(control: Control): this
  3899. // Removes the given control from the map
  3900. removeControl: function (control) {
  3901. control.remove();
  3902. return this;
  3903. },
  3904. _initControlPos: function () {
  3905. var corners = this._controlCorners = {},
  3906. l = 'leaflet-',
  3907. container = this._controlContainer =
  3908. create$1('div', l + 'control-container', this._container);
  3909. function createCorner(vSide, hSide) {
  3910. var className = l + vSide + ' ' + l + hSide;
  3911. corners[vSide + hSide] = create$1('div', className, container);
  3912. }
  3913. createCorner('top', 'left');
  3914. createCorner('top', 'right');
  3915. createCorner('bottom', 'left');
  3916. createCorner('bottom', 'right');
  3917. },
  3918. _clearControlPos: function () {
  3919. for (var i in this._controlCorners) {
  3920. remove(this._controlCorners[i]);
  3921. }
  3922. remove(this._controlContainer);
  3923. delete this._controlCorners;
  3924. delete this._controlContainer;
  3925. }
  3926. });
  3927. /*
  3928. * @class Control.Layers
  3929. * @aka L.Control.Layers
  3930. * @inherits Control
  3931. *
  3932. * The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](http://leafletjs.com/examples/layers-control/)). Extends `Control`.
  3933. *
  3934. * @example
  3935. *
  3936. * ```js
  3937. * var baseLayers = {
  3938. * "Mapbox": mapbox,
  3939. * "OpenStreetMap": osm
  3940. * };
  3941. *
  3942. * var overlays = {
  3943. * "Marker": marker,
  3944. * "Roads": roadsLayer
  3945. * };
  3946. *
  3947. * L.control.layers(baseLayers, overlays).addTo(map);
  3948. * ```
  3949. *
  3950. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  3951. *
  3952. * ```js
  3953. * {
  3954. * "<someName1>": layer1,
  3955. * "<someName2>": layer2
  3956. * }
  3957. * ```
  3958. *
  3959. * The layer names can contain HTML, which allows you to add additional styling to the items:
  3960. *
  3961. * ```js
  3962. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  3963. * ```
  3964. */
  3965. var Layers = Control.extend({
  3966. // @section
  3967. // @aka Control.Layers options
  3968. options: {
  3969. // @option collapsed: Boolean = true
  3970. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  3971. collapsed: true,
  3972. position: 'topright',
  3973. // @option autoZIndex: Boolean = true
  3974. // 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.
  3975. autoZIndex: true,
  3976. // @option hideSingleBase: Boolean = false
  3977. // If `true`, the base layers in the control will be hidden when there is only one.
  3978. hideSingleBase: false,
  3979. // @option sortLayers: Boolean = false
  3980. // Whether to sort the layers. When `false`, layers will keep the order
  3981. // in which they were added to the control.
  3982. sortLayers: false,
  3983. // @option sortFunction: Function = *
  3984. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  3985. // that will be used for sorting the layers, when `sortLayers` is `true`.
  3986. // The function receives both the `L.Layer` instances and their names, as in
  3987. // `sortFunction(layerA, layerB, nameA, nameB)`.
  3988. // By default, it sorts layers alphabetically by their name.
  3989. sortFunction: function (layerA, layerB, nameA, nameB) {
  3990. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  3991. }
  3992. },
  3993. initialize: function (baseLayers, overlays, options) {
  3994. setOptions(this, options);
  3995. this._layerControlInputs = [];
  3996. this._layers = [];
  3997. this._lastZIndex = 0;
  3998. this._handlingClick = false;
  3999. for (var i in baseLayers) {
  4000. this._addLayer(baseLayers[i], i);
  4001. }
  4002. for (i in overlays) {
  4003. this._addLayer(overlays[i], i, true);
  4004. }
  4005. },
  4006. onAdd: function (map) {
  4007. this._initLayout();
  4008. this._update();
  4009. this._map = map;
  4010. map.on('zoomend', this._checkDisabledLayers, this);
  4011. for (var i = 0; i < this._layers.length; i++) {
  4012. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4013. }
  4014. return this._container;
  4015. },
  4016. addTo: function (map) {
  4017. Control.prototype.addTo.call(this, map);
  4018. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4019. return this._expandIfNotCollapsed();
  4020. },
  4021. onRemove: function () {
  4022. this._map.off('zoomend', this._checkDisabledLayers, this);
  4023. for (var i = 0; i < this._layers.length; i++) {
  4024. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4025. }
  4026. },
  4027. // @method addBaseLayer(layer: Layer, name: String): this
  4028. // Adds a base layer (radio button entry) with the given name to the control.
  4029. addBaseLayer: function (layer, name) {
  4030. this._addLayer(layer, name);
  4031. return (this._map) ? this._update() : this;
  4032. },
  4033. // @method addOverlay(layer: Layer, name: String): this
  4034. // Adds an overlay (checkbox entry) with the given name to the control.
  4035. addOverlay: function (layer, name) {
  4036. this._addLayer(layer, name, true);
  4037. return (this._map) ? this._update() : this;
  4038. },
  4039. // @method removeLayer(layer: Layer): this
  4040. // Remove the given layer from the control.
  4041. removeLayer: function (layer) {
  4042. layer.off('add remove', this._onLayerChange, this);
  4043. var obj = this._getLayer(stamp(layer));
  4044. if (obj) {
  4045. this._layers.splice(this._layers.indexOf(obj), 1);
  4046. }
  4047. return (this._map) ? this._update() : this;
  4048. },
  4049. // @method expand(): this
  4050. // Expand the control container if collapsed.
  4051. expand: function () {
  4052. addClass(this._container, 'leaflet-control-layers-expanded');
  4053. this._form.style.height = null;
  4054. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4055. if (acceptableHeight < this._form.clientHeight) {
  4056. addClass(this._form, 'leaflet-control-layers-scrollbar');
  4057. this._form.style.height = acceptableHeight + 'px';
  4058. } else {
  4059. removeClass(this._form, 'leaflet-control-layers-scrollbar');
  4060. }
  4061. this._checkDisabledLayers();
  4062. return this;
  4063. },
  4064. // @method collapse(): this
  4065. // Collapse the control container if expanded.
  4066. collapse: function () {
  4067. removeClass(this._container, 'leaflet-control-layers-expanded');
  4068. return this;
  4069. },
  4070. _initLayout: function () {
  4071. var className = 'leaflet-control-layers',
  4072. container = this._container = create$1('div', className),
  4073. collapsed = this.options.collapsed;
  4074. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4075. container.setAttribute('aria-haspopup', true);
  4076. disableClickPropagation(container);
  4077. disableScrollPropagation(container);
  4078. var form = this._form = create$1('form', className + '-list');
  4079. if (collapsed) {
  4080. this._map.on('click', this.collapse, this);
  4081. if (!android) {
  4082. on(container, {
  4083. mouseenter: this.expand,
  4084. mouseleave: this.collapse
  4085. }, this);
  4086. }
  4087. }
  4088. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4089. link.href = '#';
  4090. link.title = 'Layers';
  4091. if (touch) {
  4092. on(link, 'click', stop);
  4093. on(link, 'click', this.expand, this);
  4094. } else {
  4095. on(link, 'focus', this.expand, this);
  4096. }
  4097. if (!collapsed) {
  4098. this.expand();
  4099. }
  4100. this._baseLayersList = create$1('div', className + '-base', form);
  4101. this._separator = create$1('div', className + '-separator', form);
  4102. this._overlaysList = create$1('div', className + '-overlays', form);
  4103. container.appendChild(form);
  4104. },
  4105. _getLayer: function (id) {
  4106. for (var i = 0; i < this._layers.length; i++) {
  4107. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4108. return this._layers[i];
  4109. }
  4110. }
  4111. },
  4112. _addLayer: function (layer, name, overlay) {
  4113. if (this._map) {
  4114. layer.on('add remove', this._onLayerChange, this);
  4115. }
  4116. this._layers.push({
  4117. layer: layer,
  4118. name: name,
  4119. overlay: overlay
  4120. });
  4121. if (this.options.sortLayers) {
  4122. this._layers.sort(bind(function (a, b) {
  4123. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4124. }, this));
  4125. }
  4126. if (this.options.autoZIndex && layer.setZIndex) {
  4127. this._lastZIndex++;
  4128. layer.setZIndex(this._lastZIndex);
  4129. }
  4130. this._expandIfNotCollapsed();
  4131. },
  4132. _update: function () {
  4133. if (!this._container) { return this; }
  4134. empty(this._baseLayersList);
  4135. empty(this._overlaysList);
  4136. this._layerControlInputs = [];
  4137. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4138. for (i = 0; i < this._layers.length; i++) {
  4139. obj = this._layers[i];
  4140. this._addItem(obj);
  4141. overlaysPresent = overlaysPresent || obj.overlay;
  4142. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4143. baseLayersCount += !obj.overlay ? 1 : 0;
  4144. }
  4145. // Hide base layers section if there's only one layer.
  4146. if (this.options.hideSingleBase) {
  4147. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4148. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4149. }
  4150. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4151. return this;
  4152. },
  4153. _onLayerChange: function (e) {
  4154. if (!this._handlingClick) {
  4155. this._update();
  4156. }
  4157. var obj = this._getLayer(stamp(e.target));
  4158. // @namespace Map
  4159. // @section Layer events
  4160. // @event baselayerchange: LayersControlEvent
  4161. // Fired when the base layer is changed through the [layer control](#control-layers).
  4162. // @event overlayadd: LayersControlEvent
  4163. // Fired when an overlay is selected through the [layer control](#control-layers).
  4164. // @event overlayremove: LayersControlEvent
  4165. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4166. // @namespace Control.Layers
  4167. var type = obj.overlay ?
  4168. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4169. (e.type === 'add' ? 'baselayerchange' : null);
  4170. if (type) {
  4171. this._map.fire(type, obj);
  4172. }
  4173. },
  4174. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4175. _createRadioElement: function (name, checked) {
  4176. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4177. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4178. var radioFragment = document.createElement('div');
  4179. radioFragment.innerHTML = radioHtml;
  4180. return radioFragment.firstChild;
  4181. },
  4182. _addItem: function (obj) {
  4183. var label = document.createElement('label'),
  4184. checked = this._map.hasLayer(obj.layer),
  4185. input;
  4186. if (obj.overlay) {
  4187. input = document.createElement('input');
  4188. input.type = 'checkbox';
  4189. input.className = 'leaflet-control-layers-selector';
  4190. input.defaultChecked = checked;
  4191. } else {
  4192. input = this._createRadioElement('leaflet-base-layers', checked);
  4193. }
  4194. this._layerControlInputs.push(input);
  4195. input.layerId = stamp(obj.layer);
  4196. on(input, 'click', this._onInputClick, this);
  4197. var name = document.createElement('span');
  4198. name.innerHTML = ' ' + obj.name;
  4199. // Helps from preventing layer control flicker when checkboxes are disabled
  4200. // https://github.com/Leaflet/Leaflet/issues/2771
  4201. var holder = document.createElement('div');
  4202. label.appendChild(holder);
  4203. holder.appendChild(input);
  4204. holder.appendChild(name);
  4205. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4206. container.appendChild(label);
  4207. this._checkDisabledLayers();
  4208. return label;
  4209. },
  4210. _onInputClick: function () {
  4211. var inputs = this._layerControlInputs,
  4212. input, layer;
  4213. var addedLayers = [],
  4214. removedLayers = [];
  4215. this._handlingClick = true;
  4216. for (var i = inputs.length - 1; i >= 0; i--) {
  4217. input = inputs[i];
  4218. layer = this._getLayer(input.layerId).layer;
  4219. if (input.checked) {
  4220. addedLayers.push(layer);
  4221. } else if (!input.checked) {
  4222. removedLayers.push(layer);
  4223. }
  4224. }
  4225. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4226. for (i = 0; i < removedLayers.length; i++) {
  4227. if (this._map.hasLayer(removedLayers[i])) {
  4228. this._map.removeLayer(removedLayers[i]);
  4229. }
  4230. }
  4231. for (i = 0; i < addedLayers.length; i++) {
  4232. if (!this._map.hasLayer(addedLayers[i])) {
  4233. this._map.addLayer(addedLayers[i]);
  4234. }
  4235. }
  4236. this._handlingClick = false;
  4237. this._refocusOnMap();
  4238. },
  4239. _checkDisabledLayers: function () {
  4240. var inputs = this._layerControlInputs,
  4241. input,
  4242. layer,
  4243. zoom = this._map.getZoom();
  4244. for (var i = inputs.length - 1; i >= 0; i--) {
  4245. input = inputs[i];
  4246. layer = this._getLayer(input.layerId).layer;
  4247. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4248. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4249. }
  4250. },
  4251. _expandIfNotCollapsed: function () {
  4252. if (this._map && !this.options.collapsed) {
  4253. this.expand();
  4254. }
  4255. return this;
  4256. },
  4257. _expand: function () {
  4258. // Backward compatibility, remove me in 1.1.
  4259. return this.expand();
  4260. },
  4261. _collapse: function () {
  4262. // Backward compatibility, remove me in 1.1.
  4263. return this.collapse();
  4264. }
  4265. });
  4266. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4267. // Creates an attribution control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.
  4268. var layers = function (baseLayers, overlays, options) {
  4269. return new Layers(baseLayers, overlays, options);
  4270. };
  4271. /*
  4272. * @class Control.Zoom
  4273. * @aka L.Control.Zoom
  4274. * @inherits Control
  4275. *
  4276. * 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`.
  4277. */
  4278. var Zoom = Control.extend({
  4279. // @section
  4280. // @aka Control.Zoom options
  4281. options: {
  4282. position: 'topleft',
  4283. // @option zoomInText: String = '+'
  4284. // The text set on the 'zoom in' button.
  4285. zoomInText: '+',
  4286. // @option zoomInTitle: String = 'Zoom in'
  4287. // The title set on the 'zoom in' button.
  4288. zoomInTitle: 'Zoom in',
  4289. // @option zoomOutText: String = '&#x2212;'
  4290. // The text set on the 'zoom out' button.
  4291. zoomOutText: '&#x2212;',
  4292. // @option zoomOutTitle: String = 'Zoom out'
  4293. // The title set on the 'zoom out' button.
  4294. zoomOutTitle: 'Zoom out'
  4295. },
  4296. onAdd: function (map) {
  4297. var zoomName = 'leaflet-control-zoom',
  4298. container = create$1('div', zoomName + ' leaflet-bar'),
  4299. options = this.options;
  4300. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4301. zoomName + '-in', container, this._zoomIn);
  4302. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4303. zoomName + '-out', container, this._zoomOut);
  4304. this._updateDisabled();
  4305. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4306. return container;
  4307. },
  4308. onRemove: function (map) {
  4309. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4310. },
  4311. disable: function () {
  4312. this._disabled = true;
  4313. this._updateDisabled();
  4314. return this;
  4315. },
  4316. enable: function () {
  4317. this._disabled = false;
  4318. this._updateDisabled();
  4319. return this;
  4320. },
  4321. _zoomIn: function (e) {
  4322. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4323. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4324. }
  4325. },
  4326. _zoomOut: function (e) {
  4327. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4328. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4329. }
  4330. },
  4331. _createButton: function (html, title, className, container, fn) {
  4332. var link = create$1('a', className, container);
  4333. link.innerHTML = html;
  4334. link.href = '#';
  4335. link.title = title;
  4336. /*
  4337. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4338. */
  4339. link.setAttribute('role', 'button');
  4340. link.setAttribute('aria-label', title);
  4341. disableClickPropagation(link);
  4342. on(link, 'click', stop);
  4343. on(link, 'click', fn, this);
  4344. on(link, 'click', this._refocusOnMap, this);
  4345. return link;
  4346. },
  4347. _updateDisabled: function () {
  4348. var map = this._map,
  4349. className = 'leaflet-disabled';
  4350. removeClass(this._zoomInButton, className);
  4351. removeClass(this._zoomOutButton, className);
  4352. if (this._disabled || map._zoom === map.getMinZoom()) {
  4353. addClass(this._zoomOutButton, className);
  4354. }
  4355. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4356. addClass(this._zoomInButton, className);
  4357. }
  4358. }
  4359. });
  4360. // @namespace Map
  4361. // @section Control options
  4362. // @option zoomControl: Boolean = true
  4363. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4364. Map.mergeOptions({
  4365. zoomControl: true
  4366. });
  4367. Map.addInitHook(function () {
  4368. if (this.options.zoomControl) {
  4369. this.zoomControl = new Zoom();
  4370. this.addControl(this.zoomControl);
  4371. }
  4372. });
  4373. // @namespace Control.Zoom
  4374. // @factory L.control.zoom(options: Control.Zoom options)
  4375. // Creates a zoom control
  4376. var zoom = function (options) {
  4377. return new Zoom(options);
  4378. };
  4379. /*
  4380. * @class Control.Scale
  4381. * @aka L.Control.Scale
  4382. * @inherits Control
  4383. *
  4384. * 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`.
  4385. *
  4386. * @example
  4387. *
  4388. * ```js
  4389. * L.control.scale().addTo(map);
  4390. * ```
  4391. */
  4392. var Scale = Control.extend({
  4393. // @section
  4394. // @aka Control.Scale options
  4395. options: {
  4396. position: 'bottomleft',
  4397. // @option maxWidth: Number = 100
  4398. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4399. maxWidth: 100,
  4400. // @option metric: Boolean = True
  4401. // Whether to show the metric scale line (m/km).
  4402. metric: true,
  4403. // @option imperial: Boolean = True
  4404. // Whether to show the imperial scale line (mi/ft).
  4405. imperial: true
  4406. // @option updateWhenIdle: Boolean = false
  4407. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4408. },
  4409. onAdd: function (map) {
  4410. var className = 'leaflet-control-scale',
  4411. container = create$1('div', className),
  4412. options = this.options;
  4413. this._addScales(options, className + '-line', container);
  4414. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4415. map.whenReady(this._update, this);
  4416. return container;
  4417. },
  4418. onRemove: function (map) {
  4419. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4420. },
  4421. _addScales: function (options, className, container) {
  4422. if (options.metric) {
  4423. this._mScale = create$1('div', className, container);
  4424. }
  4425. if (options.imperial) {
  4426. this._iScale = create$1('div', className, container);
  4427. }
  4428. },
  4429. _update: function () {
  4430. var map = this._map,
  4431. y = map.getSize().y / 2;
  4432. var maxMeters = map.distance(
  4433. map.containerPointToLatLng([0, y]),
  4434. map.containerPointToLatLng([this.options.maxWidth, y]));
  4435. this._updateScales(maxMeters);
  4436. },
  4437. _updateScales: function (maxMeters) {
  4438. if (this.options.metric && maxMeters) {
  4439. this._updateMetric(maxMeters);
  4440. }
  4441. if (this.options.imperial && maxMeters) {
  4442. this._updateImperial(maxMeters);
  4443. }
  4444. },
  4445. _updateMetric: function (maxMeters) {
  4446. var meters = this._getRoundNum(maxMeters),
  4447. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4448. this._updateScale(this._mScale, label, meters / maxMeters);
  4449. },
  4450. _updateImperial: function (maxMeters) {
  4451. var maxFeet = maxMeters * 3.2808399,
  4452. maxMiles, miles, feet;
  4453. if (maxFeet > 5280) {
  4454. maxMiles = maxFeet / 5280;
  4455. miles = this._getRoundNum(maxMiles);
  4456. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4457. } else {
  4458. feet = this._getRoundNum(maxFeet);
  4459. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4460. }
  4461. },
  4462. _updateScale: function (scale, text, ratio) {
  4463. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4464. scale.innerHTML = text;
  4465. },
  4466. _getRoundNum: function (num) {
  4467. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4468. d = num / pow10;
  4469. d = d >= 10 ? 10 :
  4470. d >= 5 ? 5 :
  4471. d >= 3 ? 3 :
  4472. d >= 2 ? 2 : 1;
  4473. return pow10 * d;
  4474. }
  4475. });
  4476. // @factory L.control.scale(options?: Control.Scale options)
  4477. // Creates an scale control with the given options.
  4478. var scale = function (options) {
  4479. return new Scale(options);
  4480. };
  4481. /*
  4482. * @class Control.Attribution
  4483. * @aka L.Control.Attribution
  4484. * @inherits Control
  4485. *
  4486. * 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.
  4487. */
  4488. var Attribution = Control.extend({
  4489. // @section
  4490. // @aka Control.Attribution options
  4491. options: {
  4492. position: 'bottomright',
  4493. // @option prefix: String = 'Leaflet'
  4494. // The HTML text shown before the attributions. Pass `false` to disable.
  4495. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4496. },
  4497. initialize: function (options) {
  4498. setOptions(this, options);
  4499. this._attributions = {};
  4500. },
  4501. onAdd: function (map) {
  4502. map.attributionControl = this;
  4503. this._container = create$1('div', 'leaflet-control-attribution');
  4504. disableClickPropagation(this._container);
  4505. // TODO ugly, refactor
  4506. for (var i in map._layers) {
  4507. if (map._layers[i].getAttribution) {
  4508. this.addAttribution(map._layers[i].getAttribution());
  4509. }
  4510. }
  4511. this._update();
  4512. return this._container;
  4513. },
  4514. // @method setPrefix(prefix: String): this
  4515. // Sets the text before the attributions.
  4516. setPrefix: function (prefix) {
  4517. this.options.prefix = prefix;
  4518. this._update();
  4519. return this;
  4520. },
  4521. // @method addAttribution(text: String): this
  4522. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4523. addAttribution: function (text) {
  4524. if (!text) { return this; }
  4525. if (!this._attributions[text]) {
  4526. this._attributions[text] = 0;
  4527. }
  4528. this._attributions[text]++;
  4529. this._update();
  4530. return this;
  4531. },
  4532. // @method removeAttribution(text: String): this
  4533. // Removes an attribution text.
  4534. removeAttribution: function (text) {
  4535. if (!text) { return this; }
  4536. if (this._attributions[text]) {
  4537. this._attributions[text]--;
  4538. this._update();
  4539. }
  4540. return this;
  4541. },
  4542. _update: function () {
  4543. if (!this._map) { return; }
  4544. var attribs = [];
  4545. for (var i in this._attributions) {
  4546. if (this._attributions[i]) {
  4547. attribs.push(i);
  4548. }
  4549. }
  4550. var prefixAndAttribs = [];
  4551. if (this.options.prefix) {
  4552. prefixAndAttribs.push(this.options.prefix);
  4553. }
  4554. if (attribs.length) {
  4555. prefixAndAttribs.push(attribs.join(', '));
  4556. }
  4557. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4558. }
  4559. });
  4560. // @namespace Map
  4561. // @section Control options
  4562. // @option attributionControl: Boolean = true
  4563. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4564. Map.mergeOptions({
  4565. attributionControl: true
  4566. });
  4567. Map.addInitHook(function () {
  4568. if (this.options.attributionControl) {
  4569. new Attribution().addTo(this);
  4570. }
  4571. });
  4572. // @namespace Control.Attribution
  4573. // @factory L.control.attribution(options: Control.Attribution options)
  4574. // Creates an attribution control.
  4575. var attribution = function (options) {
  4576. return new Attribution(options);
  4577. };
  4578. Control.Layers = Layers;
  4579. Control.Zoom = Zoom;
  4580. Control.Scale = Scale;
  4581. Control.Attribution = Attribution;
  4582. control.layers = layers;
  4583. control.zoom = zoom;
  4584. control.scale = scale;
  4585. control.attribution = attribution;
  4586. /*
  4587. L.Handler is a base class for handler classes that are used internally to inject
  4588. interaction features like dragging to classes like Map and Marker.
  4589. */
  4590. // @class Handler
  4591. // @aka L.Handler
  4592. // Abstract class for map interaction handlers
  4593. var Handler = Class.extend({
  4594. initialize: function (map) {
  4595. this._map = map;
  4596. },
  4597. // @method enable(): this
  4598. // Enables the handler
  4599. enable: function () {
  4600. if (this._enabled) { return this; }
  4601. this._enabled = true;
  4602. this.addHooks();
  4603. return this;
  4604. },
  4605. // @method disable(): this
  4606. // Disables the handler
  4607. disable: function () {
  4608. if (!this._enabled) { return this; }
  4609. this._enabled = false;
  4610. this.removeHooks();
  4611. return this;
  4612. },
  4613. // @method enabled(): Boolean
  4614. // Returns `true` if the handler is enabled
  4615. enabled: function () {
  4616. return !!this._enabled;
  4617. }
  4618. // @section Extension methods
  4619. // Classes inheriting from `Handler` must implement the two following methods:
  4620. // @method addHooks()
  4621. // Called when the handler is enabled, should add event hooks.
  4622. // @method removeHooks()
  4623. // Called when the handler is disabled, should remove the event hooks added previously.
  4624. });
  4625. // @section There is static function which can be called without instantiating L.Handler:
  4626. // @function addTo(map: Map, name: String): this
  4627. // Adds a new Handler to the given map with the given name.
  4628. Handler.addTo = function (map, name) {
  4629. map.addHandler(name, this);
  4630. return this;
  4631. };
  4632. var Mixin = {Events: Events};
  4633. /*
  4634. * @class Draggable
  4635. * @aka L.Draggable
  4636. * @inherits Evented
  4637. *
  4638. * A class for making DOM elements draggable (including touch support).
  4639. * Used internally for map and marker dragging. Only works for elements
  4640. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4641. *
  4642. * @example
  4643. * ```js
  4644. * var draggable = new L.Draggable(elementToDrag);
  4645. * draggable.enable();
  4646. * ```
  4647. */
  4648. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4649. var END = {
  4650. mousedown: 'mouseup',
  4651. touchstart: 'touchend',
  4652. pointerdown: 'touchend',
  4653. MSPointerDown: 'touchend'
  4654. };
  4655. var MOVE = {
  4656. mousedown: 'mousemove',
  4657. touchstart: 'touchmove',
  4658. pointerdown: 'touchmove',
  4659. MSPointerDown: 'touchmove'
  4660. };
  4661. var Draggable = Evented.extend({
  4662. options: {
  4663. // @section
  4664. // @aka Draggable options
  4665. // @option clickTolerance: Number = 3
  4666. // The max number of pixels a user can shift the mouse pointer during a click
  4667. // for it to be considered a valid click (as opposed to a mouse drag).
  4668. clickTolerance: 3
  4669. },
  4670. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4671. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4672. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4673. setOptions(this, options);
  4674. this._element = element;
  4675. this._dragStartTarget = dragStartTarget || element;
  4676. this._preventOutline = preventOutline$$1;
  4677. },
  4678. // @method enable()
  4679. // Enables the dragging ability
  4680. enable: function () {
  4681. if (this._enabled) { return; }
  4682. on(this._dragStartTarget, START, this._onDown, this);
  4683. this._enabled = true;
  4684. },
  4685. // @method disable()
  4686. // Disables the dragging ability
  4687. disable: function () {
  4688. if (!this._enabled) { return; }
  4689. // If we're currently dragging this draggable,
  4690. // disabling it counts as first ending the drag.
  4691. if (Draggable._dragging === this) {
  4692. this.finishDrag();
  4693. }
  4694. off(this._dragStartTarget, START, this._onDown, this);
  4695. this._enabled = false;
  4696. this._moved = false;
  4697. },
  4698. _onDown: function (e) {
  4699. // Ignore simulated events, since we handle both touch and
  4700. // mouse explicitly; otherwise we risk getting duplicates of
  4701. // touch events, see #4315.
  4702. // Also ignore the event if disabled; this happens in IE11
  4703. // under some circumstances, see #3666.
  4704. if (e._simulated || !this._enabled) { return; }
  4705. this._moved = false;
  4706. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4707. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4708. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4709. if (this._preventOutline) {
  4710. preventOutline(this._element);
  4711. }
  4712. disableImageDrag();
  4713. disableTextSelection();
  4714. if (this._moving) { return; }
  4715. // @event down: Event
  4716. // Fired when a drag is about to start.
  4717. this.fire('down');
  4718. var first = e.touches ? e.touches[0] : e;
  4719. this._startPoint = new Point(first.clientX, first.clientY);
  4720. on(document, MOVE[e.type], this._onMove, this);
  4721. on(document, END[e.type], this._onUp, this);
  4722. },
  4723. _onMove: function (e) {
  4724. // Ignore simulated events, since we handle both touch and
  4725. // mouse explicitly; otherwise we risk getting duplicates of
  4726. // touch events, see #4315.
  4727. // Also ignore the event if disabled; this happens in IE11
  4728. // under some circumstances, see #3666.
  4729. if (e._simulated || !this._enabled) { return; }
  4730. if (e.touches && e.touches.length > 1) {
  4731. this._moved = true;
  4732. return;
  4733. }
  4734. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4735. newPoint = new Point(first.clientX, first.clientY),
  4736. offset = newPoint.subtract(this._startPoint);
  4737. if (!offset.x && !offset.y) { return; }
  4738. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4739. preventDefault(e);
  4740. if (!this._moved) {
  4741. // @event dragstart: Event
  4742. // Fired when a drag starts
  4743. this.fire('dragstart');
  4744. this._moved = true;
  4745. this._startPos = getPosition(this._element).subtract(offset);
  4746. addClass(document.body, 'leaflet-dragging');
  4747. this._lastTarget = e.target || e.srcElement;
  4748. // IE and Edge do not give the <use> element, so fetch it
  4749. // if necessary
  4750. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4751. this._lastTarget = this._lastTarget.correspondingUseElement;
  4752. }
  4753. addClass(this._lastTarget, 'leaflet-drag-target');
  4754. }
  4755. this._newPos = this._startPos.add(offset);
  4756. this._moving = true;
  4757. cancelAnimFrame(this._animRequest);
  4758. this._lastEvent = e;
  4759. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4760. },
  4761. _updatePosition: function () {
  4762. var e = {originalEvent: this._lastEvent};
  4763. // @event predrag: Event
  4764. // Fired continuously during dragging *before* each corresponding
  4765. // update of the element's position.
  4766. this.fire('predrag', e);
  4767. setPosition(this._element, this._newPos);
  4768. // @event drag: Event
  4769. // Fired continuously during dragging.
  4770. this.fire('drag', e);
  4771. },
  4772. _onUp: function (e) {
  4773. // Ignore simulated events, since we handle both touch and
  4774. // mouse explicitly; otherwise we risk getting duplicates of
  4775. // touch events, see #4315.
  4776. // Also ignore the event if disabled; this happens in IE11
  4777. // under some circumstances, see #3666.
  4778. if (e._simulated || !this._enabled) { return; }
  4779. this.finishDrag();
  4780. },
  4781. finishDrag: function () {
  4782. removeClass(document.body, 'leaflet-dragging');
  4783. if (this._lastTarget) {
  4784. removeClass(this._lastTarget, 'leaflet-drag-target');
  4785. this._lastTarget = null;
  4786. }
  4787. for (var i in MOVE) {
  4788. off(document, MOVE[i], this._onMove, this);
  4789. off(document, END[i], this._onUp, this);
  4790. }
  4791. enableImageDrag();
  4792. enableTextSelection();
  4793. if (this._moved && this._moving) {
  4794. // ensure drag is not fired after dragend
  4795. cancelAnimFrame(this._animRequest);
  4796. // @event dragend: DragEndEvent
  4797. // Fired when the drag ends.
  4798. this.fire('dragend', {
  4799. distance: this._newPos.distanceTo(this._startPos)
  4800. });
  4801. }
  4802. this._moving = false;
  4803. Draggable._dragging = false;
  4804. }
  4805. });
  4806. /*
  4807. * @namespace LineUtil
  4808. *
  4809. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4810. */
  4811. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4812. // Improves rendering performance dramatically by lessening the number of points to draw.
  4813. // @function simplify(points: Point[], tolerance: Number): Point[]
  4814. // Dramatically reduces the number of points in a polyline while retaining
  4815. // its shape and returns a new array of simplified points, using the
  4816. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4817. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4818. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4819. // simplification (lesser value means higher quality but slower and with more points).
  4820. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4821. function simplify(points, tolerance) {
  4822. if (!tolerance || !points.length) {
  4823. return points.slice();
  4824. }
  4825. var sqTolerance = tolerance * tolerance;
  4826. // stage 1: vertex reduction
  4827. points = _reducePoints(points, sqTolerance);
  4828. // stage 2: Douglas-Peucker simplification
  4829. points = _simplifyDP(points, sqTolerance);
  4830. return points;
  4831. }
  4832. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4833. // Returns the distance between point `p` and segment `p1` to `p2`.
  4834. function pointToSegmentDistance(p, p1, p2) {
  4835. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4836. }
  4837. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4838. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4839. function closestPointOnSegment(p, p1, p2) {
  4840. return _sqClosestPointOnSegment(p, p1, p2);
  4841. }
  4842. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4843. function _simplifyDP(points, sqTolerance) {
  4844. var len = points.length,
  4845. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4846. markers = new ArrayConstructor(len);
  4847. markers[0] = markers[len - 1] = 1;
  4848. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4849. var i,
  4850. newPoints = [];
  4851. for (i = 0; i < len; i++) {
  4852. if (markers[i]) {
  4853. newPoints.push(points[i]);
  4854. }
  4855. }
  4856. return newPoints;
  4857. }
  4858. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4859. var maxSqDist = 0,
  4860. index, i, sqDist;
  4861. for (i = first + 1; i <= last - 1; i++) {
  4862. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4863. if (sqDist > maxSqDist) {
  4864. index = i;
  4865. maxSqDist = sqDist;
  4866. }
  4867. }
  4868. if (maxSqDist > sqTolerance) {
  4869. markers[index] = 1;
  4870. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4871. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4872. }
  4873. }
  4874. // reduce points that are too close to each other to a single point
  4875. function _reducePoints(points, sqTolerance) {
  4876. var reducedPoints = [points[0]];
  4877. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4878. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4879. reducedPoints.push(points[i]);
  4880. prev = i;
  4881. }
  4882. }
  4883. if (prev < len - 1) {
  4884. reducedPoints.push(points[len - 1]);
  4885. }
  4886. return reducedPoints;
  4887. }
  4888. var _lastCode;
  4889. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4890. // Clips the segment a to b by rectangular bounds with the
  4891. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4892. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4893. // points that are on the screen or near, increasing performance.
  4894. function clipSegment(a, b, bounds, useLastCode, round) {
  4895. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4896. codeB = _getBitCode(b, bounds),
  4897. codeOut, p, newCode;
  4898. // save 2nd code to avoid calculating it on the next segment
  4899. _lastCode = codeB;
  4900. while (true) {
  4901. // if a,b is inside the clip window (trivial accept)
  4902. if (!(codeA | codeB)) {
  4903. return [a, b];
  4904. }
  4905. // if a,b is outside the clip window (trivial reject)
  4906. if (codeA & codeB) {
  4907. return false;
  4908. }
  4909. // other cases
  4910. codeOut = codeA || codeB;
  4911. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4912. newCode = _getBitCode(p, bounds);
  4913. if (codeOut === codeA) {
  4914. a = p;
  4915. codeA = newCode;
  4916. } else {
  4917. b = p;
  4918. codeB = newCode;
  4919. }
  4920. }
  4921. }
  4922. function _getEdgeIntersection(a, b, code, bounds, round) {
  4923. var dx = b.x - a.x,
  4924. dy = b.y - a.y,
  4925. min = bounds.min,
  4926. max = bounds.max,
  4927. x, y;
  4928. if (code & 8) { // top
  4929. x = a.x + dx * (max.y - a.y) / dy;
  4930. y = max.y;
  4931. } else if (code & 4) { // bottom
  4932. x = a.x + dx * (min.y - a.y) / dy;
  4933. y = min.y;
  4934. } else if (code & 2) { // right
  4935. x = max.x;
  4936. y = a.y + dy * (max.x - a.x) / dx;
  4937. } else if (code & 1) { // left
  4938. x = min.x;
  4939. y = a.y + dy * (min.x - a.x) / dx;
  4940. }
  4941. return new Point(x, y, round);
  4942. }
  4943. function _getBitCode(p, bounds) {
  4944. var code = 0;
  4945. if (p.x < bounds.min.x) { // left
  4946. code |= 1;
  4947. } else if (p.x > bounds.max.x) { // right
  4948. code |= 2;
  4949. }
  4950. if (p.y < bounds.min.y) { // bottom
  4951. code |= 4;
  4952. } else if (p.y > bounds.max.y) { // top
  4953. code |= 8;
  4954. }
  4955. return code;
  4956. }
  4957. // square distance (to avoid unnecessary Math.sqrt calls)
  4958. function _sqDist(p1, p2) {
  4959. var dx = p2.x - p1.x,
  4960. dy = p2.y - p1.y;
  4961. return dx * dx + dy * dy;
  4962. }
  4963. // return closest point on segment or distance to that point
  4964. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  4965. var x = p1.x,
  4966. y = p1.y,
  4967. dx = p2.x - x,
  4968. dy = p2.y - y,
  4969. dot = dx * dx + dy * dy,
  4970. t;
  4971. if (dot > 0) {
  4972. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  4973. if (t > 1) {
  4974. x = p2.x;
  4975. y = p2.y;
  4976. } else if (t > 0) {
  4977. x += dx * t;
  4978. y += dy * t;
  4979. }
  4980. }
  4981. dx = p.x - x;
  4982. dy = p.y - y;
  4983. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  4984. }
  4985. // @function isFlat(latlngs: LatLng[]): Boolean
  4986. // Returns true if `latlngs` is a flat array, false is nested.
  4987. function isFlat(latlngs) {
  4988. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  4989. }
  4990. function _flat(latlngs) {
  4991. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  4992. return isFlat(latlngs);
  4993. }
  4994. var LineUtil = (Object.freeze || Object)({
  4995. simplify: simplify,
  4996. pointToSegmentDistance: pointToSegmentDistance,
  4997. closestPointOnSegment: closestPointOnSegment,
  4998. clipSegment: clipSegment,
  4999. _getEdgeIntersection: _getEdgeIntersection,
  5000. _getBitCode: _getBitCode,
  5001. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5002. isFlat: isFlat,
  5003. _flat: _flat
  5004. });
  5005. /*
  5006. * @namespace PolyUtil
  5007. * Various utility functions for polygon geometries.
  5008. */
  5009. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5010. * 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)).
  5011. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5012. * performance. Note that polygon points needs different algorithm for clipping
  5013. * than polyline, so there's a separate method for it.
  5014. */
  5015. function clipPolygon(points, bounds, round) {
  5016. var clippedPoints,
  5017. edges = [1, 4, 2, 8],
  5018. i, j, k,
  5019. a, b,
  5020. len, edge, p;
  5021. for (i = 0, len = points.length; i < len; i++) {
  5022. points[i]._code = _getBitCode(points[i], bounds);
  5023. }
  5024. // for each edge (left, bottom, right, top)
  5025. for (k = 0; k < 4; k++) {
  5026. edge = edges[k];
  5027. clippedPoints = [];
  5028. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5029. a = points[i];
  5030. b = points[j];
  5031. // if a is inside the clip window
  5032. if (!(a._code & edge)) {
  5033. // if b is outside the clip window (a->b goes out of screen)
  5034. if (b._code & edge) {
  5035. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5036. p._code = _getBitCode(p, bounds);
  5037. clippedPoints.push(p);
  5038. }
  5039. clippedPoints.push(a);
  5040. // else if b is inside the clip window (a->b enters the screen)
  5041. } else if (!(b._code & edge)) {
  5042. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5043. p._code = _getBitCode(p, bounds);
  5044. clippedPoints.push(p);
  5045. }
  5046. }
  5047. points = clippedPoints;
  5048. }
  5049. return points;
  5050. }
  5051. var PolyUtil = (Object.freeze || Object)({
  5052. clipPolygon: clipPolygon
  5053. });
  5054. /*
  5055. * @namespace Projection
  5056. * @section
  5057. * Leaflet comes with a set of already defined Projections out of the box:
  5058. *
  5059. * @projection L.Projection.LonLat
  5060. *
  5061. * Equirectangular, or Plate Carree projection — the most simple projection,
  5062. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5063. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5064. * `EPSG:4326` and `Simple` CRS.
  5065. */
  5066. var LonLat = {
  5067. project: function (latlng) {
  5068. return new Point(latlng.lng, latlng.lat);
  5069. },
  5070. unproject: function (point) {
  5071. return new LatLng(point.y, point.x);
  5072. },
  5073. bounds: new Bounds([-180, -90], [180, 90])
  5074. };
  5075. /*
  5076. * @namespace Projection
  5077. * @projection L.Projection.Mercator
  5078. *
  5079. * Elliptical Mercator projection — more complex than Spherical Mercator. Takes into account that Earth is a geoid, not a perfect sphere. Used by the EPSG:3395 CRS.
  5080. */
  5081. var Mercator = {
  5082. R: 6378137,
  5083. R_MINOR: 6356752.314245179,
  5084. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5085. project: function (latlng) {
  5086. var d = Math.PI / 180,
  5087. r = this.R,
  5088. y = latlng.lat * d,
  5089. tmp = this.R_MINOR / r,
  5090. e = Math.sqrt(1 - tmp * tmp),
  5091. con = e * Math.sin(y);
  5092. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5093. y = -r * Math.log(Math.max(ts, 1E-10));
  5094. return new Point(latlng.lng * d * r, y);
  5095. },
  5096. unproject: function (point) {
  5097. var d = 180 / Math.PI,
  5098. r = this.R,
  5099. tmp = this.R_MINOR / r,
  5100. e = Math.sqrt(1 - tmp * tmp),
  5101. ts = Math.exp(-point.y / r),
  5102. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5103. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5104. con = e * Math.sin(phi);
  5105. con = Math.pow((1 - con) / (1 + con), e / 2);
  5106. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5107. phi += dphi;
  5108. }
  5109. return new LatLng(phi * d, point.x * d / r);
  5110. }
  5111. };
  5112. /*
  5113. * @class Projection
  5114. * An object with methods for projecting geographical coordinates of the world onto
  5115. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5116. * @property bounds: Bounds
  5117. * The bounds (specified in CRS units) where the projection is valid
  5118. * @method project(latlng: LatLng): Point
  5119. * Projects geographical coordinates into a 2D point.
  5120. * Only accepts actual `L.LatLng` instances, not arrays.
  5121. * @method unproject(point: Point): LatLng
  5122. * The inverse of `project`. Projects a 2D point into a geographical location.
  5123. * Only accepts actual `L.Point` instances, not arrays.
  5124. * Note that the projection instances do not inherit from Leafet's `Class` object,
  5125. * and can't be instantiated. Also, new classes can't inherit from them,
  5126. * and methods can't be added to them with the `include` function.
  5127. */
  5128. var index = (Object.freeze || Object)({
  5129. LonLat: LonLat,
  5130. Mercator: Mercator,
  5131. SphericalMercator: SphericalMercator
  5132. });
  5133. /*
  5134. * @namespace CRS
  5135. * @crs L.CRS.EPSG3395
  5136. *
  5137. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5138. */
  5139. var EPSG3395 = extend({}, Earth, {
  5140. code: 'EPSG:3395',
  5141. projection: Mercator,
  5142. transformation: (function () {
  5143. var scale = 0.5 / (Math.PI * Mercator.R);
  5144. return toTransformation(scale, 0.5, -scale, 0.5);
  5145. }())
  5146. });
  5147. /*
  5148. * @namespace CRS
  5149. * @crs L.CRS.EPSG4326
  5150. *
  5151. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5152. *
  5153. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5154. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5155. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5156. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5157. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5158. */
  5159. var EPSG4326 = extend({}, Earth, {
  5160. code: 'EPSG:4326',
  5161. projection: LonLat,
  5162. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5163. });
  5164. /*
  5165. * @namespace CRS
  5166. * @crs L.CRS.Simple
  5167. *
  5168. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5169. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5170. * axis should still be inverted (going from bottom to top). `distance()` returns
  5171. * simple euclidean distance.
  5172. */
  5173. var Simple = extend({}, CRS, {
  5174. projection: LonLat,
  5175. transformation: toTransformation(1, 0, -1, 0),
  5176. scale: function (zoom) {
  5177. return Math.pow(2, zoom);
  5178. },
  5179. zoom: function (scale) {
  5180. return Math.log(scale) / Math.LN2;
  5181. },
  5182. distance: function (latlng1, latlng2) {
  5183. var dx = latlng2.lng - latlng1.lng,
  5184. dy = latlng2.lat - latlng1.lat;
  5185. return Math.sqrt(dx * dx + dy * dy);
  5186. },
  5187. infinite: true
  5188. });
  5189. CRS.Earth = Earth;
  5190. CRS.EPSG3395 = EPSG3395;
  5191. CRS.EPSG3857 = EPSG3857;
  5192. CRS.EPSG900913 = EPSG900913;
  5193. CRS.EPSG4326 = EPSG4326;
  5194. CRS.Simple = Simple;
  5195. /*
  5196. * @class Layer
  5197. * @inherits Evented
  5198. * @aka L.Layer
  5199. * @aka ILayer
  5200. *
  5201. * A set of methods from the Layer base class that all Leaflet layers use.
  5202. * Inherits all methods, options and events from `L.Evented`.
  5203. *
  5204. * @example
  5205. *
  5206. * ```js
  5207. * var layer = L.Marker(latlng).addTo(map);
  5208. * layer.addTo(map);
  5209. * layer.remove();
  5210. * ```
  5211. *
  5212. * @event add: Event
  5213. * Fired after the layer is added to a map
  5214. *
  5215. * @event remove: Event
  5216. * Fired after the layer is removed from a map
  5217. */
  5218. var Layer = Evented.extend({
  5219. // Classes extending `L.Layer` will inherit the following options:
  5220. options: {
  5221. // @option pane: String = 'overlayPane'
  5222. // 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.
  5223. pane: 'overlayPane',
  5224. // @option attribution: String = null
  5225. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  5226. attribution: null,
  5227. bubblingMouseEvents: true
  5228. },
  5229. /* @section
  5230. * Classes extending `L.Layer` will inherit the following methods:
  5231. *
  5232. * @method addTo(map: Map|LayerGroup): this
  5233. * Adds the layer to the given map or layer group.
  5234. */
  5235. addTo: function (map) {
  5236. map.addLayer(this);
  5237. return this;
  5238. },
  5239. // @method remove: this
  5240. // Removes the layer from the map it is currently active on.
  5241. remove: function () {
  5242. return this.removeFrom(this._map || this._mapToAdd);
  5243. },
  5244. // @method removeFrom(map: Map): this
  5245. // Removes the layer from the given map
  5246. removeFrom: function (obj) {
  5247. if (obj) {
  5248. obj.removeLayer(this);
  5249. }
  5250. return this;
  5251. },
  5252. // @method getPane(name? : String): HTMLElement
  5253. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5254. getPane: function (name) {
  5255. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5256. },
  5257. addInteractiveTarget: function (targetEl) {
  5258. this._map._targets[stamp(targetEl)] = this;
  5259. return this;
  5260. },
  5261. removeInteractiveTarget: function (targetEl) {
  5262. delete this._map._targets[stamp(targetEl)];
  5263. return this;
  5264. },
  5265. // @method getAttribution: String
  5266. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5267. getAttribution: function () {
  5268. return this.options.attribution;
  5269. },
  5270. _layerAdd: function (e) {
  5271. var map = e.target;
  5272. // check in case layer gets added and then removed before the map is ready
  5273. if (!map.hasLayer(this)) { return; }
  5274. this._map = map;
  5275. this._zoomAnimated = map._zoomAnimated;
  5276. if (this.getEvents) {
  5277. var events = this.getEvents();
  5278. map.on(events, this);
  5279. this.once('remove', function () {
  5280. map.off(events, this);
  5281. }, this);
  5282. }
  5283. this.onAdd(map);
  5284. if (this.getAttribution && map.attributionControl) {
  5285. map.attributionControl.addAttribution(this.getAttribution());
  5286. }
  5287. this.fire('add');
  5288. map.fire('layeradd', {layer: this});
  5289. }
  5290. });
  5291. /* @section Extension methods
  5292. * @uninheritable
  5293. *
  5294. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5295. *
  5296. * @method onAdd(map: Map): this
  5297. * 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).
  5298. *
  5299. * @method onRemove(map: Map): this
  5300. * 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).
  5301. *
  5302. * @method getEvents(): Object
  5303. * 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.
  5304. *
  5305. * @method getAttribution(): String
  5306. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5307. *
  5308. * @method beforeAdd(map: Map): this
  5309. * 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.
  5310. */
  5311. /* @namespace Map
  5312. * @section Layer events
  5313. *
  5314. * @event layeradd: LayerEvent
  5315. * Fired when a new layer is added to the map.
  5316. *
  5317. * @event layerremove: LayerEvent
  5318. * Fired when some layer is removed from the map
  5319. *
  5320. * @section Methods for Layers and Controls
  5321. */
  5322. Map.include({
  5323. // @method addLayer(layer: Layer): this
  5324. // Adds the given layer to the map
  5325. addLayer: function (layer) {
  5326. if (!layer._layerAdd) {
  5327. throw new Error('The provided object is not a Layer.');
  5328. }
  5329. var id = stamp(layer);
  5330. if (this._layers[id]) { return this; }
  5331. this._layers[id] = layer;
  5332. layer._mapToAdd = this;
  5333. if (layer.beforeAdd) {
  5334. layer.beforeAdd(this);
  5335. }
  5336. this.whenReady(layer._layerAdd, layer);
  5337. return this;
  5338. },
  5339. // @method removeLayer(layer: Layer): this
  5340. // Removes the given layer from the map.
  5341. removeLayer: function (layer) {
  5342. var id = stamp(layer);
  5343. if (!this._layers[id]) { return this; }
  5344. if (this._loaded) {
  5345. layer.onRemove(this);
  5346. }
  5347. if (layer.getAttribution && this.attributionControl) {
  5348. this.attributionControl.removeAttribution(layer.getAttribution());
  5349. }
  5350. delete this._layers[id];
  5351. if (this._loaded) {
  5352. this.fire('layerremove', {layer: layer});
  5353. layer.fire('remove');
  5354. }
  5355. layer._map = layer._mapToAdd = null;
  5356. return this;
  5357. },
  5358. // @method hasLayer(layer: Layer): Boolean
  5359. // Returns `true` if the given layer is currently added to the map
  5360. hasLayer: function (layer) {
  5361. return !!layer && (stamp(layer) in this._layers);
  5362. },
  5363. /* @method eachLayer(fn: Function, context?: Object): this
  5364. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5365. * ```
  5366. * map.eachLayer(function(layer){
  5367. * layer.bindPopup('Hello');
  5368. * });
  5369. * ```
  5370. */
  5371. eachLayer: function (method, context) {
  5372. for (var i in this._layers) {
  5373. method.call(context, this._layers[i]);
  5374. }
  5375. return this;
  5376. },
  5377. _addLayers: function (layers) {
  5378. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5379. for (var i = 0, len = layers.length; i < len; i++) {
  5380. this.addLayer(layers[i]);
  5381. }
  5382. },
  5383. _addZoomLimit: function (layer) {
  5384. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5385. this._zoomBoundLayers[stamp(layer)] = layer;
  5386. this._updateZoomLevels();
  5387. }
  5388. },
  5389. _removeZoomLimit: function (layer) {
  5390. var id = stamp(layer);
  5391. if (this._zoomBoundLayers[id]) {
  5392. delete this._zoomBoundLayers[id];
  5393. this._updateZoomLevels();
  5394. }
  5395. },
  5396. _updateZoomLevels: function () {
  5397. var minZoom = Infinity,
  5398. maxZoom = -Infinity,
  5399. oldZoomSpan = this._getZoomSpan();
  5400. for (var i in this._zoomBoundLayers) {
  5401. var options = this._zoomBoundLayers[i].options;
  5402. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5403. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5404. }
  5405. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5406. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5407. // @section Map state change events
  5408. // @event zoomlevelschange: Event
  5409. // Fired when the number of zoomlevels on the map is changed due
  5410. // to adding or removing a layer.
  5411. if (oldZoomSpan !== this._getZoomSpan()) {
  5412. this.fire('zoomlevelschange');
  5413. }
  5414. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5415. this.setZoom(this._layersMaxZoom);
  5416. }
  5417. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5418. this.setZoom(this._layersMinZoom);
  5419. }
  5420. }
  5421. });
  5422. /*
  5423. * @class LayerGroup
  5424. * @aka L.LayerGroup
  5425. * @inherits Layer
  5426. *
  5427. * Used to group several layers and handle them as one. If you add it to the map,
  5428. * any layers added or removed from the group will be added/removed on the map as
  5429. * well. Extends `Layer`.
  5430. *
  5431. * @example
  5432. *
  5433. * ```js
  5434. * L.layerGroup([marker1, marker2])
  5435. * .addLayer(polyline)
  5436. * .addTo(map);
  5437. * ```
  5438. */
  5439. var LayerGroup = Layer.extend({
  5440. initialize: function (layers, options) {
  5441. setOptions(this, options);
  5442. this._layers = {};
  5443. var i, len;
  5444. if (layers) {
  5445. for (i = 0, len = layers.length; i < len; i++) {
  5446. this.addLayer(layers[i]);
  5447. }
  5448. }
  5449. },
  5450. // @method addLayer(layer: Layer): this
  5451. // Adds the given layer to the group.
  5452. addLayer: function (layer) {
  5453. var id = this.getLayerId(layer);
  5454. this._layers[id] = layer;
  5455. if (this._map) {
  5456. this._map.addLayer(layer);
  5457. }
  5458. return this;
  5459. },
  5460. // @method removeLayer(layer: Layer): this
  5461. // Removes the given layer from the group.
  5462. // @alternative
  5463. // @method removeLayer(id: Number): this
  5464. // Removes the layer with the given internal ID from the group.
  5465. removeLayer: function (layer) {
  5466. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5467. if (this._map && this._layers[id]) {
  5468. this._map.removeLayer(this._layers[id]);
  5469. }
  5470. delete this._layers[id];
  5471. return this;
  5472. },
  5473. // @method hasLayer(layer: Layer): Boolean
  5474. // Returns `true` if the given layer is currently added to the group.
  5475. // @alternative
  5476. // @method hasLayer(id: Number): Boolean
  5477. // Returns `true` if the given internal ID is currently added to the group.
  5478. hasLayer: function (layer) {
  5479. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5480. },
  5481. // @method clearLayers(): this
  5482. // Removes all the layers from the group.
  5483. clearLayers: function () {
  5484. return this.eachLayer(this.removeLayer, this);
  5485. },
  5486. // @method invoke(methodName: String, …): this
  5487. // Calls `methodName` on every layer contained in this group, passing any
  5488. // additional parameters. Has no effect if the layers contained do not
  5489. // implement `methodName`.
  5490. invoke: function (methodName) {
  5491. var args = Array.prototype.slice.call(arguments, 1),
  5492. i, layer;
  5493. for (i in this._layers) {
  5494. layer = this._layers[i];
  5495. if (layer[methodName]) {
  5496. layer[methodName].apply(layer, args);
  5497. }
  5498. }
  5499. return this;
  5500. },
  5501. onAdd: function (map) {
  5502. this.eachLayer(map.addLayer, map);
  5503. },
  5504. onRemove: function (map) {
  5505. this.eachLayer(map.removeLayer, map);
  5506. },
  5507. // @method eachLayer(fn: Function, context?: Object): this
  5508. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5509. // ```js
  5510. // group.eachLayer(function (layer) {
  5511. // layer.bindPopup('Hello');
  5512. // });
  5513. // ```
  5514. eachLayer: function (method, context) {
  5515. for (var i in this._layers) {
  5516. method.call(context, this._layers[i]);
  5517. }
  5518. return this;
  5519. },
  5520. // @method getLayer(id: Number): Layer
  5521. // Returns the layer with the given internal ID.
  5522. getLayer: function (id) {
  5523. return this._layers[id];
  5524. },
  5525. // @method getLayers(): Layer[]
  5526. // Returns an array of all the layers added to the group.
  5527. getLayers: function () {
  5528. var layers = [];
  5529. this.eachLayer(layers.push, layers);
  5530. return layers;
  5531. },
  5532. // @method setZIndex(zIndex: Number): this
  5533. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5534. setZIndex: function (zIndex) {
  5535. return this.invoke('setZIndex', zIndex);
  5536. },
  5537. // @method getLayerId(layer: Layer): Number
  5538. // Returns the internal ID for a layer
  5539. getLayerId: function (layer) {
  5540. return stamp(layer);
  5541. }
  5542. });
  5543. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5544. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5545. var layerGroup = function (layers, options) {
  5546. return new LayerGroup(layers, options);
  5547. };
  5548. /*
  5549. * @class FeatureGroup
  5550. * @aka L.FeatureGroup
  5551. * @inherits LayerGroup
  5552. *
  5553. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5554. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5555. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5556. * handler, it will handle events from any of the layers. This includes mouse events
  5557. * and custom events.
  5558. * * Has `layeradd` and `layerremove` events
  5559. *
  5560. * @example
  5561. *
  5562. * ```js
  5563. * L.featureGroup([marker1, marker2, polyline])
  5564. * .bindPopup('Hello world!')
  5565. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5566. * .addTo(map);
  5567. * ```
  5568. */
  5569. var FeatureGroup = LayerGroup.extend({
  5570. addLayer: function (layer) {
  5571. if (this.hasLayer(layer)) {
  5572. return this;
  5573. }
  5574. layer.addEventParent(this);
  5575. LayerGroup.prototype.addLayer.call(this, layer);
  5576. // @event layeradd: LayerEvent
  5577. // Fired when a layer is added to this `FeatureGroup`
  5578. return this.fire('layeradd', {layer: layer});
  5579. },
  5580. removeLayer: function (layer) {
  5581. if (!this.hasLayer(layer)) {
  5582. return this;
  5583. }
  5584. if (layer in this._layers) {
  5585. layer = this._layers[layer];
  5586. }
  5587. layer.removeEventParent(this);
  5588. LayerGroup.prototype.removeLayer.call(this, layer);
  5589. // @event layerremove: LayerEvent
  5590. // Fired when a layer is removed from this `FeatureGroup`
  5591. return this.fire('layerremove', {layer: layer});
  5592. },
  5593. // @method setStyle(style: Path options): this
  5594. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5595. setStyle: function (style) {
  5596. return this.invoke('setStyle', style);
  5597. },
  5598. // @method bringToFront(): this
  5599. // Brings the layer group to the top of all other layers
  5600. bringToFront: function () {
  5601. return this.invoke('bringToFront');
  5602. },
  5603. // @method bringToBack(): this
  5604. // Brings the layer group to the back of all other layers
  5605. bringToBack: function () {
  5606. return this.invoke('bringToBack');
  5607. },
  5608. // @method getBounds(): LatLngBounds
  5609. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5610. getBounds: function () {
  5611. var bounds = new LatLngBounds();
  5612. for (var id in this._layers) {
  5613. var layer = this._layers[id];
  5614. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5615. }
  5616. return bounds;
  5617. }
  5618. });
  5619. // @factory L.featureGroup(layers: Layer[])
  5620. // Create a feature group, optionally given an initial set of layers.
  5621. var featureGroup = function (layers) {
  5622. return new FeatureGroup(layers);
  5623. };
  5624. /*
  5625. * @class Icon
  5626. * @aka L.Icon
  5627. *
  5628. * Represents an icon to provide when creating a marker.
  5629. *
  5630. * @example
  5631. *
  5632. * ```js
  5633. * var myIcon = L.icon({
  5634. * iconUrl: 'my-icon.png',
  5635. * iconRetinaUrl: 'my-icon@2x.png',
  5636. * iconSize: [38, 95],
  5637. * iconAnchor: [22, 94],
  5638. * popupAnchor: [-3, -76],
  5639. * shadowUrl: 'my-icon-shadow.png',
  5640. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5641. * shadowSize: [68, 95],
  5642. * shadowAnchor: [22, 94]
  5643. * });
  5644. *
  5645. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5646. * ```
  5647. *
  5648. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5649. *
  5650. */
  5651. var Icon = Class.extend({
  5652. /* @section
  5653. * @aka Icon options
  5654. *
  5655. * @option iconUrl: String = null
  5656. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5657. *
  5658. * @option iconRetinaUrl: String = null
  5659. * The URL to a retina sized version of the icon image (absolute or relative to your
  5660. * script path). Used for Retina screen devices.
  5661. *
  5662. * @option iconSize: Point = null
  5663. * Size of the icon image in pixels.
  5664. *
  5665. * @option iconAnchor: Point = null
  5666. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5667. * will be aligned so that this point is at the marker's geographical location. Centered
  5668. * by default if size is specified, also can be set in CSS with negative margins.
  5669. *
  5670. * @option popupAnchor: Point = [0, 0]
  5671. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5672. *
  5673. * @option tooltipAnchor: Point = [0, 0]
  5674. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5675. *
  5676. * @option shadowUrl: String = null
  5677. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5678. *
  5679. * @option shadowRetinaUrl: String = null
  5680. *
  5681. * @option shadowSize: Point = null
  5682. * Size of the shadow image in pixels.
  5683. *
  5684. * @option shadowAnchor: Point = null
  5685. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5686. * as iconAnchor if not specified).
  5687. *
  5688. * @option className: String = ''
  5689. * A custom class name to assign to both icon and shadow images. Empty by default.
  5690. */
  5691. options: {
  5692. popupAnchor: [0, 0],
  5693. tooltipAnchor: [0, 0],
  5694. },
  5695. initialize: function (options) {
  5696. setOptions(this, options);
  5697. },
  5698. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5699. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5700. // styled according to the options.
  5701. createIcon: function (oldIcon) {
  5702. return this._createIcon('icon', oldIcon);
  5703. },
  5704. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5705. // As `createIcon`, but for the shadow beneath it.
  5706. createShadow: function (oldIcon) {
  5707. return this._createIcon('shadow', oldIcon);
  5708. },
  5709. _createIcon: function (name, oldIcon) {
  5710. var src = this._getIconUrl(name);
  5711. if (!src) {
  5712. if (name === 'icon') {
  5713. throw new Error('iconUrl not set in Icon options (see the docs).');
  5714. }
  5715. return null;
  5716. }
  5717. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5718. this._setIconStyles(img, name);
  5719. return img;
  5720. },
  5721. _setIconStyles: function (img, name) {
  5722. var options = this.options;
  5723. var sizeOption = options[name + 'Size'];
  5724. if (typeof sizeOption === 'number') {
  5725. sizeOption = [sizeOption, sizeOption];
  5726. }
  5727. var size = toPoint(sizeOption),
  5728. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5729. size && size.divideBy(2, true));
  5730. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5731. if (anchor) {
  5732. img.style.marginLeft = (-anchor.x) + 'px';
  5733. img.style.marginTop = (-anchor.y) + 'px';
  5734. }
  5735. if (size) {
  5736. img.style.width = size.x + 'px';
  5737. img.style.height = size.y + 'px';
  5738. }
  5739. },
  5740. _createImg: function (src, el) {
  5741. el = el || document.createElement('img');
  5742. el.src = src;
  5743. return el;
  5744. },
  5745. _getIconUrl: function (name) {
  5746. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5747. }
  5748. });
  5749. // @factory L.icon(options: Icon options)
  5750. // Creates an icon instance with the given options.
  5751. function icon(options) {
  5752. return new Icon(options);
  5753. }
  5754. /*
  5755. * @miniclass Icon.Default (Icon)
  5756. * @aka L.Icon.Default
  5757. * @section
  5758. *
  5759. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5760. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5761. * releases.
  5762. *
  5763. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5764. * (which is a set of `Icon options`).
  5765. *
  5766. * If you want to _completely_ replace the default icon, override the
  5767. * `L.Marker.prototype.options.icon` with your own icon instead.
  5768. */
  5769. var IconDefault = Icon.extend({
  5770. options: {
  5771. iconUrl: 'marker-icon.png',
  5772. iconRetinaUrl: 'marker-icon-2x.png',
  5773. shadowUrl: 'marker-shadow.png',
  5774. iconSize: [25, 41],
  5775. iconAnchor: [12, 41],
  5776. popupAnchor: [1, -34],
  5777. tooltipAnchor: [16, -28],
  5778. shadowSize: [41, 41]
  5779. },
  5780. _getIconUrl: function (name) {
  5781. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5782. IconDefault.imagePath = this._detectIconPath();
  5783. }
  5784. // @option imagePath: String
  5785. // `Icon.Default` will try to auto-detect the location of the
  5786. // blue icon images. If you are placing these images in a non-standard
  5787. // way, set this option to point to the right path.
  5788. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5789. },
  5790. _detectIconPath: function () {
  5791. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5792. var path = getStyle(el, 'background-image') ||
  5793. getStyle(el, 'backgroundImage'); // IE8
  5794. document.body.removeChild(el);
  5795. if (path === null || path.indexOf('url') !== 0) {
  5796. path = '';
  5797. } else {
  5798. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5799. }
  5800. return path;
  5801. }
  5802. });
  5803. /*
  5804. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5805. */
  5806. /* @namespace Marker
  5807. * @section Interaction handlers
  5808. *
  5809. * 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:
  5810. *
  5811. * ```js
  5812. * marker.dragging.disable();
  5813. * ```
  5814. *
  5815. * @property dragging: Handler
  5816. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5817. */
  5818. var MarkerDrag = Handler.extend({
  5819. initialize: function (marker) {
  5820. this._marker = marker;
  5821. },
  5822. addHooks: function () {
  5823. var icon = this._marker._icon;
  5824. if (!this._draggable) {
  5825. this._draggable = new Draggable(icon, icon, true);
  5826. }
  5827. this._draggable.on({
  5828. dragstart: this._onDragStart,
  5829. predrag: this._onPreDrag,
  5830. drag: this._onDrag,
  5831. dragend: this._onDragEnd
  5832. }, this).enable();
  5833. addClass(icon, 'leaflet-marker-draggable');
  5834. },
  5835. removeHooks: function () {
  5836. this._draggable.off({
  5837. dragstart: this._onDragStart,
  5838. predrag: this._onPreDrag,
  5839. drag: this._onDrag,
  5840. dragend: this._onDragEnd
  5841. }, this).disable();
  5842. if (this._marker._icon) {
  5843. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5844. }
  5845. },
  5846. moved: function () {
  5847. return this._draggable && this._draggable._moved;
  5848. },
  5849. _adjustPan: function (e) {
  5850. var marker = this._marker,
  5851. map = marker._map,
  5852. speed = this._marker.options.autoPanSpeed,
  5853. padding = this._marker.options.autoPanPadding,
  5854. iconPos = L.DomUtil.getPosition(marker._icon),
  5855. bounds = map.getPixelBounds(),
  5856. origin = map.getPixelOrigin();
  5857. var panBounds = toBounds(
  5858. bounds.min._subtract(origin).add(padding),
  5859. bounds.max._subtract(origin).subtract(padding)
  5860. );
  5861. if (!panBounds.contains(iconPos)) {
  5862. // Compute incremental movement
  5863. var movement = toPoint(
  5864. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5865. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5866. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5867. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5868. ).multiplyBy(speed);
  5869. map.panBy(movement, {animate: false});
  5870. this._draggable._newPos._add(movement);
  5871. this._draggable._startPos._add(movement);
  5872. L.DomUtil.setPosition(marker._icon, this._draggable._newPos);
  5873. this._onDrag(e);
  5874. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5875. }
  5876. },
  5877. _onDragStart: function () {
  5878. // @section Dragging events
  5879. // @event dragstart: Event
  5880. // Fired when the user starts dragging the marker.
  5881. // @event movestart: Event
  5882. // Fired when the marker starts moving (because of dragging).
  5883. this._oldLatLng = this._marker.getLatLng();
  5884. this._marker
  5885. .closePopup()
  5886. .fire('movestart')
  5887. .fire('dragstart');
  5888. },
  5889. _onPreDrag: function (e) {
  5890. if (this._marker.options.autoPan) {
  5891. cancelAnimFrame(this._panRequest);
  5892. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5893. }
  5894. },
  5895. _onDrag: function (e) {
  5896. var marker = this._marker,
  5897. shadow = marker._shadow,
  5898. iconPos = getPosition(marker._icon),
  5899. latlng = marker._map.layerPointToLatLng(iconPos);
  5900. // update shadow position
  5901. if (shadow) {
  5902. setPosition(shadow, iconPos);
  5903. }
  5904. marker._latlng = latlng;
  5905. e.latlng = latlng;
  5906. e.oldLatLng = this._oldLatLng;
  5907. // @event drag: Event
  5908. // Fired repeatedly while the user drags the marker.
  5909. marker
  5910. .fire('move', e)
  5911. .fire('drag', e);
  5912. },
  5913. _onDragEnd: function (e) {
  5914. // @event dragend: DragEndEvent
  5915. // Fired when the user stops dragging the marker.
  5916. cancelAnimFrame(this._panRequest);
  5917. // @event moveend: Event
  5918. // Fired when the marker stops moving (because of dragging).
  5919. delete this._oldLatLng;
  5920. this._marker
  5921. .fire('moveend')
  5922. .fire('dragend', e);
  5923. }
  5924. });
  5925. /*
  5926. * @class Marker
  5927. * @inherits Interactive layer
  5928. * @aka L.Marker
  5929. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5930. *
  5931. * @example
  5932. *
  5933. * ```js
  5934. * L.marker([50.5, 30.5]).addTo(map);
  5935. * ```
  5936. */
  5937. var Marker = Layer.extend({
  5938. // @section
  5939. // @aka Marker options
  5940. options: {
  5941. // @option icon: Icon = *
  5942. // Icon instance to use for rendering the marker.
  5943. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  5944. // If not specified, a common instance of `L.Icon.Default` is used.
  5945. icon: new IconDefault(),
  5946. // Option inherited from "Interactive layer" abstract class
  5947. interactive: true,
  5948. // @option draggable: Boolean = false
  5949. // Whether the marker is draggable with mouse/touch or not.
  5950. draggable: false,
  5951. // @option autoPan: Boolean = false
  5952. // Set it to `true` if you want the map to do panning animation when marker hits the edges.
  5953. autoPan: false,
  5954. // @option autoPanPadding: Point = Point(50, 50)
  5955. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  5956. autoPanPadding: [50, 50],
  5957. // @option autoPanSpeed: Number = 10
  5958. // Number of pixels the map should move by.
  5959. autoPanSpeed: 10,
  5960. // @option keyboard: Boolean = true
  5961. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5962. keyboard: true,
  5963. // @option title: String = ''
  5964. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5965. title: '',
  5966. // @option alt: String = ''
  5967. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5968. alt: '',
  5969. // @option zIndexOffset: Number = 0
  5970. // 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).
  5971. zIndexOffset: 0,
  5972. // @option opacity: Number = 1.0
  5973. // The opacity of the marker.
  5974. opacity: 1,
  5975. // @option riseOnHover: Boolean = false
  5976. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5977. riseOnHover: false,
  5978. // @option riseOffset: Number = 250
  5979. // The z-index offset used for the `riseOnHover` feature.
  5980. riseOffset: 250,
  5981. // @option pane: String = 'markerPane'
  5982. // `Map pane` where the markers icon will be added.
  5983. pane: 'markerPane',
  5984. // @option bubblingMouseEvents: Boolean = false
  5985. // When `true`, a mouse event on this marker will trigger the same event on the map
  5986. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  5987. bubblingMouseEvents: false
  5988. },
  5989. /* @section
  5990. *
  5991. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5992. */
  5993. initialize: function (latlng, options) {
  5994. setOptions(this, options);
  5995. this._latlng = toLatLng(latlng);
  5996. },
  5997. onAdd: function (map) {
  5998. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  5999. if (this._zoomAnimated) {
  6000. map.on('zoomanim', this._animateZoom, this);
  6001. }
  6002. this._initIcon();
  6003. this.update();
  6004. },
  6005. onRemove: function (map) {
  6006. if (this.dragging && this.dragging.enabled()) {
  6007. this.options.draggable = true;
  6008. this.dragging.removeHooks();
  6009. }
  6010. delete this.dragging;
  6011. if (this._zoomAnimated) {
  6012. map.off('zoomanim', this._animateZoom, this);
  6013. }
  6014. this._removeIcon();
  6015. this._removeShadow();
  6016. },
  6017. getEvents: function () {
  6018. return {
  6019. zoom: this.update,
  6020. viewreset: this.update
  6021. };
  6022. },
  6023. // @method getLatLng: LatLng
  6024. // Returns the current geographical position of the marker.
  6025. getLatLng: function () {
  6026. return this._latlng;
  6027. },
  6028. // @method setLatLng(latlng: LatLng): this
  6029. // Changes the marker position to the given point.
  6030. setLatLng: function (latlng) {
  6031. var oldLatLng = this._latlng;
  6032. this._latlng = toLatLng(latlng);
  6033. this.update();
  6034. // @event move: Event
  6035. // 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`.
  6036. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6037. },
  6038. // @method setZIndexOffset(offset: Number): this
  6039. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6040. setZIndexOffset: function (offset) {
  6041. this.options.zIndexOffset = offset;
  6042. return this.update();
  6043. },
  6044. // @method setIcon(icon: Icon): this
  6045. // Changes the marker icon.
  6046. setIcon: function (icon) {
  6047. this.options.icon = icon;
  6048. if (this._map) {
  6049. this._initIcon();
  6050. this.update();
  6051. }
  6052. if (this._popup) {
  6053. this.bindPopup(this._popup, this._popup.options);
  6054. }
  6055. return this;
  6056. },
  6057. getElement: function () {
  6058. return this._icon;
  6059. },
  6060. update: function () {
  6061. if (this._icon && this._map) {
  6062. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6063. this._setPos(pos);
  6064. }
  6065. return this;
  6066. },
  6067. _initIcon: function () {
  6068. var options = this.options,
  6069. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6070. var icon = options.icon.createIcon(this._icon),
  6071. addIcon = false;
  6072. // if we're not reusing the icon, remove the old one and init new one
  6073. if (icon !== this._icon) {
  6074. if (this._icon) {
  6075. this._removeIcon();
  6076. }
  6077. addIcon = true;
  6078. if (options.title) {
  6079. icon.title = options.title;
  6080. }
  6081. if (icon.tagName === 'IMG') {
  6082. icon.alt = options.alt || '';
  6083. }
  6084. }
  6085. addClass(icon, classToAdd);
  6086. if (options.keyboard) {
  6087. icon.tabIndex = '0';
  6088. }
  6089. this._icon = icon;
  6090. if (options.riseOnHover) {
  6091. this.on({
  6092. mouseover: this._bringToFront,
  6093. mouseout: this._resetZIndex
  6094. });
  6095. }
  6096. var newShadow = options.icon.createShadow(this._shadow),
  6097. addShadow = false;
  6098. if (newShadow !== this._shadow) {
  6099. this._removeShadow();
  6100. addShadow = true;
  6101. }
  6102. if (newShadow) {
  6103. addClass(newShadow, classToAdd);
  6104. newShadow.alt = '';
  6105. }
  6106. this._shadow = newShadow;
  6107. if (options.opacity < 1) {
  6108. this._updateOpacity();
  6109. }
  6110. if (addIcon) {
  6111. this.getPane().appendChild(this._icon);
  6112. }
  6113. this._initInteraction();
  6114. if (newShadow && addShadow) {
  6115. this.getPane('shadowPane').appendChild(this._shadow);
  6116. }
  6117. },
  6118. _removeIcon: function () {
  6119. if (this.options.riseOnHover) {
  6120. this.off({
  6121. mouseover: this._bringToFront,
  6122. mouseout: this._resetZIndex
  6123. });
  6124. }
  6125. remove(this._icon);
  6126. this.removeInteractiveTarget(this._icon);
  6127. this._icon = null;
  6128. },
  6129. _removeShadow: function () {
  6130. if (this._shadow) {
  6131. remove(this._shadow);
  6132. }
  6133. this._shadow = null;
  6134. },
  6135. _setPos: function (pos) {
  6136. setPosition(this._icon, pos);
  6137. if (this._shadow) {
  6138. setPosition(this._shadow, pos);
  6139. }
  6140. this._zIndex = pos.y + this.options.zIndexOffset;
  6141. this._resetZIndex();
  6142. },
  6143. _updateZIndex: function (offset) {
  6144. this._icon.style.zIndex = this._zIndex + offset;
  6145. },
  6146. _animateZoom: function (opt) {
  6147. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6148. this._setPos(pos);
  6149. },
  6150. _initInteraction: function () {
  6151. if (!this.options.interactive) { return; }
  6152. addClass(this._icon, 'leaflet-interactive');
  6153. this.addInteractiveTarget(this._icon);
  6154. if (MarkerDrag) {
  6155. var draggable = this.options.draggable;
  6156. if (this.dragging) {
  6157. draggable = this.dragging.enabled();
  6158. this.dragging.disable();
  6159. }
  6160. this.dragging = new MarkerDrag(this);
  6161. if (draggable) {
  6162. this.dragging.enable();
  6163. }
  6164. }
  6165. },
  6166. // @method setOpacity(opacity: Number): this
  6167. // Changes the opacity of the marker.
  6168. setOpacity: function (opacity) {
  6169. this.options.opacity = opacity;
  6170. if (this._map) {
  6171. this._updateOpacity();
  6172. }
  6173. return this;
  6174. },
  6175. _updateOpacity: function () {
  6176. var opacity = this.options.opacity;
  6177. setOpacity(this._icon, opacity);
  6178. if (this._shadow) {
  6179. setOpacity(this._shadow, opacity);
  6180. }
  6181. },
  6182. _bringToFront: function () {
  6183. this._updateZIndex(this.options.riseOffset);
  6184. },
  6185. _resetZIndex: function () {
  6186. this._updateZIndex(0);
  6187. },
  6188. _getPopupAnchor: function () {
  6189. return this.options.icon.options.popupAnchor;
  6190. },
  6191. _getTooltipAnchor: function () {
  6192. return this.options.icon.options.tooltipAnchor;
  6193. }
  6194. });
  6195. // factory L.marker(latlng: LatLng, options? : Marker options)
  6196. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6197. // Instantiates a Marker object given a geographical point and optionally an options object.
  6198. function marker(latlng, options) {
  6199. return new Marker(latlng, options);
  6200. }
  6201. /*
  6202. * @class Path
  6203. * @aka L.Path
  6204. * @inherits Interactive layer
  6205. *
  6206. * An abstract class that contains options and constants shared between vector
  6207. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6208. */
  6209. var Path = Layer.extend({
  6210. // @section
  6211. // @aka Path options
  6212. options: {
  6213. // @option stroke: Boolean = true
  6214. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6215. stroke: true,
  6216. // @option color: String = '#3388ff'
  6217. // Stroke color
  6218. color: '#3388ff',
  6219. // @option weight: Number = 3
  6220. // Stroke width in pixels
  6221. weight: 3,
  6222. // @option opacity: Number = 1.0
  6223. // Stroke opacity
  6224. opacity: 1,
  6225. // @option lineCap: String= 'round'
  6226. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6227. lineCap: 'round',
  6228. // @option lineJoin: String = 'round'
  6229. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6230. lineJoin: 'round',
  6231. // @option dashArray: String = null
  6232. // 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).
  6233. dashArray: null,
  6234. // @option dashOffset: String = null
  6235. // 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).
  6236. dashOffset: null,
  6237. // @option fill: Boolean = depends
  6238. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6239. fill: false,
  6240. // @option fillColor: String = *
  6241. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6242. fillColor: null,
  6243. // @option fillOpacity: Number = 0.2
  6244. // Fill opacity.
  6245. fillOpacity: 0.2,
  6246. // @option fillRule: String = 'evenodd'
  6247. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6248. fillRule: 'evenodd',
  6249. // className: '',
  6250. // Option inherited from "Interactive layer" abstract class
  6251. interactive: true,
  6252. // @option bubblingMouseEvents: Boolean = true
  6253. // When `true`, a mouse event on this path will trigger the same event on the map
  6254. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6255. bubblingMouseEvents: true
  6256. },
  6257. beforeAdd: function (map) {
  6258. // Renderer is set here because we need to call renderer.getEvents
  6259. // before this.getEvents.
  6260. this._renderer = map.getRenderer(this);
  6261. },
  6262. onAdd: function () {
  6263. this._renderer._initPath(this);
  6264. this._reset();
  6265. this._renderer._addPath(this);
  6266. },
  6267. onRemove: function () {
  6268. this._renderer._removePath(this);
  6269. },
  6270. // @method redraw(): this
  6271. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6272. redraw: function () {
  6273. if (this._map) {
  6274. this._renderer._updatePath(this);
  6275. }
  6276. return this;
  6277. },
  6278. // @method setStyle(style: Path options): this
  6279. // Changes the appearance of a Path based on the options in the `Path options` object.
  6280. setStyle: function (style) {
  6281. setOptions(this, style);
  6282. if (this._renderer) {
  6283. this._renderer._updateStyle(this);
  6284. }
  6285. return this;
  6286. },
  6287. // @method bringToFront(): this
  6288. // Brings the layer to the top of all path layers.
  6289. bringToFront: function () {
  6290. if (this._renderer) {
  6291. this._renderer._bringToFront(this);
  6292. }
  6293. return this;
  6294. },
  6295. // @method bringToBack(): this
  6296. // Brings the layer to the bottom of all path layers.
  6297. bringToBack: function () {
  6298. if (this._renderer) {
  6299. this._renderer._bringToBack(this);
  6300. }
  6301. return this;
  6302. },
  6303. getElement: function () {
  6304. return this._path;
  6305. },
  6306. _reset: function () {
  6307. // defined in child classes
  6308. this._project();
  6309. this._update();
  6310. },
  6311. _clickTolerance: function () {
  6312. // used when doing hit detection for Canvas layers
  6313. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6314. }
  6315. });
  6316. /*
  6317. * @class CircleMarker
  6318. * @aka L.CircleMarker
  6319. * @inherits Path
  6320. *
  6321. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6322. */
  6323. var CircleMarker = Path.extend({
  6324. // @section
  6325. // @aka CircleMarker options
  6326. options: {
  6327. fill: true,
  6328. // @option radius: Number = 10
  6329. // Radius of the circle marker, in pixels
  6330. radius: 10
  6331. },
  6332. initialize: function (latlng, options) {
  6333. setOptions(this, options);
  6334. this._latlng = toLatLng(latlng);
  6335. this._radius = this.options.radius;
  6336. },
  6337. // @method setLatLng(latLng: LatLng): this
  6338. // Sets the position of a circle marker to a new location.
  6339. setLatLng: function (latlng) {
  6340. this._latlng = toLatLng(latlng);
  6341. this.redraw();
  6342. return this.fire('move', {latlng: this._latlng});
  6343. },
  6344. // @method getLatLng(): LatLng
  6345. // Returns the current geographical position of the circle marker
  6346. getLatLng: function () {
  6347. return this._latlng;
  6348. },
  6349. // @method setRadius(radius: Number): this
  6350. // Sets the radius of a circle marker. Units are in pixels.
  6351. setRadius: function (radius) {
  6352. this.options.radius = this._radius = radius;
  6353. return this.redraw();
  6354. },
  6355. // @method getRadius(): Number
  6356. // Returns the current radius of the circle
  6357. getRadius: function () {
  6358. return this._radius;
  6359. },
  6360. setStyle : function (options) {
  6361. var radius = options && options.radius || this._radius;
  6362. Path.prototype.setStyle.call(this, options);
  6363. this.setRadius(radius);
  6364. return this;
  6365. },
  6366. _project: function () {
  6367. this._point = this._map.latLngToLayerPoint(this._latlng);
  6368. this._updateBounds();
  6369. },
  6370. _updateBounds: function () {
  6371. var r = this._radius,
  6372. r2 = this._radiusY || r,
  6373. w = this._clickTolerance(),
  6374. p = [r + w, r2 + w];
  6375. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6376. },
  6377. _update: function () {
  6378. if (this._map) {
  6379. this._updatePath();
  6380. }
  6381. },
  6382. _updatePath: function () {
  6383. this._renderer._updateCircle(this);
  6384. },
  6385. _empty: function () {
  6386. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6387. },
  6388. // Needed by the `Canvas` renderer for interactivity
  6389. _containsPoint: function (p) {
  6390. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6391. }
  6392. });
  6393. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6394. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6395. function circleMarker(latlng, options) {
  6396. return new CircleMarker(latlng, options);
  6397. }
  6398. /*
  6399. * @class Circle
  6400. * @aka L.Circle
  6401. * @inherits CircleMarker
  6402. *
  6403. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6404. *
  6405. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6406. *
  6407. * @example
  6408. *
  6409. * ```js
  6410. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6411. * ```
  6412. */
  6413. var Circle = CircleMarker.extend({
  6414. initialize: function (latlng, options, legacyOptions) {
  6415. if (typeof options === 'number') {
  6416. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6417. options = extend({}, legacyOptions, {radius: options});
  6418. }
  6419. setOptions(this, options);
  6420. this._latlng = toLatLng(latlng);
  6421. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6422. // @section
  6423. // @aka Circle options
  6424. // @option radius: Number; Radius of the circle, in meters.
  6425. this._mRadius = this.options.radius;
  6426. },
  6427. // @method setRadius(radius: Number): this
  6428. // Sets the radius of a circle. Units are in meters.
  6429. setRadius: function (radius) {
  6430. this._mRadius = radius;
  6431. return this.redraw();
  6432. },
  6433. // @method getRadius(): Number
  6434. // Returns the current radius of a circle. Units are in meters.
  6435. getRadius: function () {
  6436. return this._mRadius;
  6437. },
  6438. // @method getBounds(): LatLngBounds
  6439. // Returns the `LatLngBounds` of the path.
  6440. getBounds: function () {
  6441. var half = [this._radius, this._radiusY || this._radius];
  6442. return new LatLngBounds(
  6443. this._map.layerPointToLatLng(this._point.subtract(half)),
  6444. this._map.layerPointToLatLng(this._point.add(half)));
  6445. },
  6446. setStyle: Path.prototype.setStyle,
  6447. _project: function () {
  6448. var lng = this._latlng.lng,
  6449. lat = this._latlng.lat,
  6450. map = this._map,
  6451. crs = map.options.crs;
  6452. if (crs.distance === Earth.distance) {
  6453. var d = Math.PI / 180,
  6454. latR = (this._mRadius / Earth.R) / d,
  6455. top = map.project([lat + latR, lng]),
  6456. bottom = map.project([lat - latR, lng]),
  6457. p = top.add(bottom).divideBy(2),
  6458. lat2 = map.unproject(p).lat,
  6459. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6460. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6461. if (isNaN(lngR) || lngR === 0) {
  6462. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6463. }
  6464. this._point = p.subtract(map.getPixelOrigin());
  6465. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6466. this._radiusY = p.y - top.y;
  6467. } else {
  6468. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6469. this._point = map.latLngToLayerPoint(this._latlng);
  6470. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6471. }
  6472. this._updateBounds();
  6473. }
  6474. });
  6475. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6476. // Instantiates a circle object given a geographical point, and an options object
  6477. // which contains the circle radius.
  6478. // @alternative
  6479. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6480. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6481. // Do not use in new applications or plugins.
  6482. function circle(latlng, options, legacyOptions) {
  6483. return new Circle(latlng, options, legacyOptions);
  6484. }
  6485. /*
  6486. * @class Polyline
  6487. * @aka L.Polyline
  6488. * @inherits Path
  6489. *
  6490. * A class for drawing polyline overlays on a map. Extends `Path`.
  6491. *
  6492. * @example
  6493. *
  6494. * ```js
  6495. * // create a red polyline from an array of LatLng points
  6496. * var latlngs = [
  6497. * [45.51, -122.68],
  6498. * [37.77, -122.43],
  6499. * [34.04, -118.2]
  6500. * ];
  6501. *
  6502. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6503. *
  6504. * // zoom the map to the polyline
  6505. * map.fitBounds(polyline.getBounds());
  6506. * ```
  6507. *
  6508. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6509. *
  6510. * ```js
  6511. * // create a red polyline from an array of arrays of LatLng points
  6512. * var latlngs = [
  6513. * [[45.51, -122.68],
  6514. * [37.77, -122.43],
  6515. * [34.04, -118.2]],
  6516. * [[40.78, -73.91],
  6517. * [41.83, -87.62],
  6518. * [32.76, -96.72]]
  6519. * ];
  6520. * ```
  6521. */
  6522. var Polyline = Path.extend({
  6523. // @section
  6524. // @aka Polyline options
  6525. options: {
  6526. // @option smoothFactor: Number = 1.0
  6527. // How much to simplify the polyline on each zoom level. More means
  6528. // better performance and smoother look, and less means more accurate representation.
  6529. smoothFactor: 1.0,
  6530. // @option noClip: Boolean = false
  6531. // Disable polyline clipping.
  6532. noClip: false
  6533. },
  6534. initialize: function (latlngs, options) {
  6535. setOptions(this, options);
  6536. this._setLatLngs(latlngs);
  6537. },
  6538. // @method getLatLngs(): LatLng[]
  6539. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6540. getLatLngs: function () {
  6541. return this._latlngs;
  6542. },
  6543. // @method setLatLngs(latlngs: LatLng[]): this
  6544. // Replaces all the points in the polyline with the given array of geographical points.
  6545. setLatLngs: function (latlngs) {
  6546. this._setLatLngs(latlngs);
  6547. return this.redraw();
  6548. },
  6549. // @method isEmpty(): Boolean
  6550. // Returns `true` if the Polyline has no LatLngs.
  6551. isEmpty: function () {
  6552. return !this._latlngs.length;
  6553. },
  6554. // @method closestLayerPoint: Point
  6555. // Returns the point closest to `p` on the Polyline.
  6556. closestLayerPoint: function (p) {
  6557. var minDistance = Infinity,
  6558. minPoint = null,
  6559. closest = _sqClosestPointOnSegment,
  6560. p1, p2;
  6561. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6562. var points = this._parts[j];
  6563. for (var i = 1, len = points.length; i < len; i++) {
  6564. p1 = points[i - 1];
  6565. p2 = points[i];
  6566. var sqDist = closest(p, p1, p2, true);
  6567. if (sqDist < minDistance) {
  6568. minDistance = sqDist;
  6569. minPoint = closest(p, p1, p2);
  6570. }
  6571. }
  6572. }
  6573. if (minPoint) {
  6574. minPoint.distance = Math.sqrt(minDistance);
  6575. }
  6576. return minPoint;
  6577. },
  6578. // @method getCenter(): LatLng
  6579. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6580. getCenter: function () {
  6581. // throws error when not yet added to map as this center calculation requires projected coordinates
  6582. if (!this._map) {
  6583. throw new Error('Must add layer to map before using getCenter()');
  6584. }
  6585. var i, halfDist, segDist, dist, p1, p2, ratio,
  6586. points = this._rings[0],
  6587. len = points.length;
  6588. if (!len) { return null; }
  6589. // polyline centroid algorithm; only uses the first ring if there are multiple
  6590. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6591. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6592. }
  6593. // The line is so small in the current view that all points are on the same pixel.
  6594. if (halfDist === 0) {
  6595. return this._map.layerPointToLatLng(points[0]);
  6596. }
  6597. for (i = 0, dist = 0; i < len - 1; i++) {
  6598. p1 = points[i];
  6599. p2 = points[i + 1];
  6600. segDist = p1.distanceTo(p2);
  6601. dist += segDist;
  6602. if (dist > halfDist) {
  6603. ratio = (dist - halfDist) / segDist;
  6604. return this._map.layerPointToLatLng([
  6605. p2.x - ratio * (p2.x - p1.x),
  6606. p2.y - ratio * (p2.y - p1.y)
  6607. ]);
  6608. }
  6609. }
  6610. },
  6611. // @method getBounds(): LatLngBounds
  6612. // Returns the `LatLngBounds` of the path.
  6613. getBounds: function () {
  6614. return this._bounds;
  6615. },
  6616. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6617. // Adds a given point to the polyline. By default, adds to the first ring of
  6618. // the polyline in case of a multi-polyline, but can be overridden by passing
  6619. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6620. addLatLng: function (latlng, latlngs) {
  6621. latlngs = latlngs || this._defaultShape();
  6622. latlng = toLatLng(latlng);
  6623. latlngs.push(latlng);
  6624. this._bounds.extend(latlng);
  6625. return this.redraw();
  6626. },
  6627. _setLatLngs: function (latlngs) {
  6628. this._bounds = new LatLngBounds();
  6629. this._latlngs = this._convertLatLngs(latlngs);
  6630. },
  6631. _defaultShape: function () {
  6632. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6633. },
  6634. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6635. _convertLatLngs: function (latlngs) {
  6636. var result = [],
  6637. flat = isFlat(latlngs);
  6638. for (var i = 0, len = latlngs.length; i < len; i++) {
  6639. if (flat) {
  6640. result[i] = toLatLng(latlngs[i]);
  6641. this._bounds.extend(result[i]);
  6642. } else {
  6643. result[i] = this._convertLatLngs(latlngs[i]);
  6644. }
  6645. }
  6646. return result;
  6647. },
  6648. _project: function () {
  6649. var pxBounds = new Bounds();
  6650. this._rings = [];
  6651. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6652. var w = this._clickTolerance(),
  6653. p = new Point(w, w);
  6654. if (this._bounds.isValid() && pxBounds.isValid()) {
  6655. pxBounds.min._subtract(p);
  6656. pxBounds.max._add(p);
  6657. this._pxBounds = pxBounds;
  6658. }
  6659. },
  6660. // recursively turns latlngs into a set of rings with projected coordinates
  6661. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6662. var flat = latlngs[0] instanceof LatLng,
  6663. len = latlngs.length,
  6664. i, ring;
  6665. if (flat) {
  6666. ring = [];
  6667. for (i = 0; i < len; i++) {
  6668. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6669. projectedBounds.extend(ring[i]);
  6670. }
  6671. result.push(ring);
  6672. } else {
  6673. for (i = 0; i < len; i++) {
  6674. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6675. }
  6676. }
  6677. },
  6678. // clip polyline by renderer bounds so that we have less to render for performance
  6679. _clipPoints: function () {
  6680. var bounds = this._renderer._bounds;
  6681. this._parts = [];
  6682. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6683. return;
  6684. }
  6685. if (this.options.noClip) {
  6686. this._parts = this._rings;
  6687. return;
  6688. }
  6689. var parts = this._parts,
  6690. i, j, k, len, len2, segment, points;
  6691. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6692. points = this._rings[i];
  6693. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6694. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6695. if (!segment) { continue; }
  6696. parts[k] = parts[k] || [];
  6697. parts[k].push(segment[0]);
  6698. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6699. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6700. parts[k].push(segment[1]);
  6701. k++;
  6702. }
  6703. }
  6704. }
  6705. },
  6706. // simplify each clipped part of the polyline for performance
  6707. _simplifyPoints: function () {
  6708. var parts = this._parts,
  6709. tolerance = this.options.smoothFactor;
  6710. for (var i = 0, len = parts.length; i < len; i++) {
  6711. parts[i] = simplify(parts[i], tolerance);
  6712. }
  6713. },
  6714. _update: function () {
  6715. if (!this._map) { return; }
  6716. this._clipPoints();
  6717. this._simplifyPoints();
  6718. this._updatePath();
  6719. },
  6720. _updatePath: function () {
  6721. this._renderer._updatePoly(this);
  6722. },
  6723. // Needed by the `Canvas` renderer for interactivity
  6724. _containsPoint: function (p, closed) {
  6725. var i, j, k, len, len2, part,
  6726. w = this._clickTolerance();
  6727. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6728. // hit detection for polylines
  6729. for (i = 0, len = this._parts.length; i < len; i++) {
  6730. part = this._parts[i];
  6731. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6732. if (!closed && (j === 0)) { continue; }
  6733. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6734. return true;
  6735. }
  6736. }
  6737. }
  6738. return false;
  6739. }
  6740. });
  6741. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6742. // Instantiates a polyline object given an array of geographical points and
  6743. // optionally an options object. You can create a `Polyline` object with
  6744. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6745. // of geographic points.
  6746. function polyline(latlngs, options) {
  6747. return new Polyline(latlngs, options);
  6748. }
  6749. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6750. Polyline._flat = _flat;
  6751. /*
  6752. * @class Polygon
  6753. * @aka L.Polygon
  6754. * @inherits Polyline
  6755. *
  6756. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6757. *
  6758. * 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.
  6759. *
  6760. *
  6761. * @example
  6762. *
  6763. * ```js
  6764. * // create a red polygon from an array of LatLng points
  6765. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6766. *
  6767. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6768. *
  6769. * // zoom the map to the polygon
  6770. * map.fitBounds(polygon.getBounds());
  6771. * ```
  6772. *
  6773. * 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:
  6774. *
  6775. * ```js
  6776. * var latlngs = [
  6777. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6778. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6779. * ];
  6780. * ```
  6781. *
  6782. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6783. *
  6784. * ```js
  6785. * var latlngs = [
  6786. * [ // first polygon
  6787. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6788. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6789. * ],
  6790. * [ // second polygon
  6791. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6792. * ]
  6793. * ];
  6794. * ```
  6795. */
  6796. var Polygon = Polyline.extend({
  6797. options: {
  6798. fill: true
  6799. },
  6800. isEmpty: function () {
  6801. return !this._latlngs.length || !this._latlngs[0].length;
  6802. },
  6803. getCenter: function () {
  6804. // throws error when not yet added to map as this center calculation requires projected coordinates
  6805. if (!this._map) {
  6806. throw new Error('Must add layer to map before using getCenter()');
  6807. }
  6808. var i, j, p1, p2, f, area, x, y, center,
  6809. points = this._rings[0],
  6810. len = points.length;
  6811. if (!len) { return null; }
  6812. // polygon centroid algorithm; only uses the first ring if there are multiple
  6813. area = x = y = 0;
  6814. for (i = 0, j = len - 1; i < len; j = i++) {
  6815. p1 = points[i];
  6816. p2 = points[j];
  6817. f = p1.y * p2.x - p2.y * p1.x;
  6818. x += (p1.x + p2.x) * f;
  6819. y += (p1.y + p2.y) * f;
  6820. area += f * 3;
  6821. }
  6822. if (area === 0) {
  6823. // Polygon is so small that all points are on same pixel.
  6824. center = points[0];
  6825. } else {
  6826. center = [x / area, y / area];
  6827. }
  6828. return this._map.layerPointToLatLng(center);
  6829. },
  6830. _convertLatLngs: function (latlngs) {
  6831. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6832. len = result.length;
  6833. // remove last point if it equals first one
  6834. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6835. result.pop();
  6836. }
  6837. return result;
  6838. },
  6839. _setLatLngs: function (latlngs) {
  6840. Polyline.prototype._setLatLngs.call(this, latlngs);
  6841. if (isFlat(this._latlngs)) {
  6842. this._latlngs = [this._latlngs];
  6843. }
  6844. },
  6845. _defaultShape: function () {
  6846. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6847. },
  6848. _clipPoints: function () {
  6849. // polygons need a different clipping algorithm so we redefine that
  6850. var bounds = this._renderer._bounds,
  6851. w = this.options.weight,
  6852. p = new Point(w, w);
  6853. // increase clip padding by stroke width to avoid stroke on clip edges
  6854. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6855. this._parts = [];
  6856. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6857. return;
  6858. }
  6859. if (this.options.noClip) {
  6860. this._parts = this._rings;
  6861. return;
  6862. }
  6863. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6864. clipped = clipPolygon(this._rings[i], bounds, true);
  6865. if (clipped.length) {
  6866. this._parts.push(clipped);
  6867. }
  6868. }
  6869. },
  6870. _updatePath: function () {
  6871. this._renderer._updatePoly(this, true);
  6872. },
  6873. // Needed by the `Canvas` renderer for interactivity
  6874. _containsPoint: function (p) {
  6875. var inside = false,
  6876. part, p1, p2, i, j, k, len, len2;
  6877. if (!this._pxBounds.contains(p)) { return false; }
  6878. // ray casting algorithm for detecting if point is in polygon
  6879. for (i = 0, len = this._parts.length; i < len; i++) {
  6880. part = this._parts[i];
  6881. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6882. p1 = part[j];
  6883. p2 = part[k];
  6884. 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)) {
  6885. inside = !inside;
  6886. }
  6887. }
  6888. }
  6889. // also check if it's on polygon stroke
  6890. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  6891. }
  6892. });
  6893. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6894. function polygon(latlngs, options) {
  6895. return new Polygon(latlngs, options);
  6896. }
  6897. /*
  6898. * @class GeoJSON
  6899. * @aka L.GeoJSON
  6900. * @inherits FeatureGroup
  6901. *
  6902. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  6903. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  6904. *
  6905. * @example
  6906. *
  6907. * ```js
  6908. * L.geoJSON(data, {
  6909. * style: function (feature) {
  6910. * return {color: feature.properties.color};
  6911. * }
  6912. * }).bindPopup(function (layer) {
  6913. * return layer.feature.properties.description;
  6914. * }).addTo(map);
  6915. * ```
  6916. */
  6917. var GeoJSON = FeatureGroup.extend({
  6918. /* @section
  6919. * @aka GeoJSON options
  6920. *
  6921. * @option pointToLayer: Function = *
  6922. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  6923. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  6924. * The default is to spawn a default `Marker`:
  6925. * ```js
  6926. * function(geoJsonPoint, latlng) {
  6927. * return L.marker(latlng);
  6928. * }
  6929. * ```
  6930. *
  6931. * @option style: Function = *
  6932. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  6933. * called internally when data is added.
  6934. * The default value is to not override any defaults:
  6935. * ```js
  6936. * function (geoJsonFeature) {
  6937. * return {}
  6938. * }
  6939. * ```
  6940. *
  6941. * @option onEachFeature: Function = *
  6942. * A `Function` that will be called once for each created `Feature`, after it has
  6943. * been created and styled. Useful for attaching events and popups to features.
  6944. * The default is to do nothing with the newly created layers:
  6945. * ```js
  6946. * function (feature, layer) {}
  6947. * ```
  6948. *
  6949. * @option filter: Function = *
  6950. * A `Function` that will be used to decide whether to include a feature or not.
  6951. * The default is to include all features:
  6952. * ```js
  6953. * function (geoJsonFeature) {
  6954. * return true;
  6955. * }
  6956. * ```
  6957. * Note: dynamically changing the `filter` option will have effect only on newly
  6958. * added data. It will _not_ re-evaluate already included features.
  6959. *
  6960. * @option coordsToLatLng: Function = *
  6961. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  6962. * The default is the `coordsToLatLng` static method.
  6963. */
  6964. initialize: function (geojson, options) {
  6965. setOptions(this, options);
  6966. this._layers = {};
  6967. if (geojson) {
  6968. this.addData(geojson);
  6969. }
  6970. },
  6971. // @method addData( <GeoJSON> data ): this
  6972. // Adds a GeoJSON object to the layer.
  6973. addData: function (geojson) {
  6974. var features = isArray(geojson) ? geojson : geojson.features,
  6975. i, len, feature;
  6976. if (features) {
  6977. for (i = 0, len = features.length; i < len; i++) {
  6978. // only add this if geometry or geometries are set and not null
  6979. feature = features[i];
  6980. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  6981. this.addData(feature);
  6982. }
  6983. }
  6984. return this;
  6985. }
  6986. var options = this.options;
  6987. if (options.filter && !options.filter(geojson)) { return this; }
  6988. var layer = geometryToLayer(geojson, options);
  6989. if (!layer) {
  6990. return this;
  6991. }
  6992. layer.feature = asFeature(geojson);
  6993. layer.defaultOptions = layer.options;
  6994. this.resetStyle(layer);
  6995. if (options.onEachFeature) {
  6996. options.onEachFeature(geojson, layer);
  6997. }
  6998. return this.addLayer(layer);
  6999. },
  7000. // @method resetStyle( <Path> layer ): this
  7001. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7002. resetStyle: function (layer) {
  7003. // reset any custom styles
  7004. layer.options = extend({}, layer.defaultOptions);
  7005. this._setLayerStyle(layer, this.options.style);
  7006. return this;
  7007. },
  7008. // @method setStyle( <Function> style ): this
  7009. // Changes styles of GeoJSON vector layers with the given style function.
  7010. setStyle: function (style) {
  7011. return this.eachLayer(function (layer) {
  7012. this._setLayerStyle(layer, style);
  7013. }, this);
  7014. },
  7015. _setLayerStyle: function (layer, style) {
  7016. if (typeof style === 'function') {
  7017. style = style(layer.feature);
  7018. }
  7019. if (layer.setStyle) {
  7020. layer.setStyle(style);
  7021. }
  7022. }
  7023. });
  7024. // @section
  7025. // There are several static functions which can be called without instantiating L.GeoJSON:
  7026. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7027. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7028. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7029. // functions if provided as options.
  7030. function geometryToLayer(geojson, options) {
  7031. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7032. coords = geometry ? geometry.coordinates : null,
  7033. layers = [],
  7034. pointToLayer = options && options.pointToLayer,
  7035. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7036. latlng, latlngs, i, len;
  7037. if (!coords && !geometry) {
  7038. return null;
  7039. }
  7040. switch (geometry.type) {
  7041. case 'Point':
  7042. latlng = _coordsToLatLng(coords);
  7043. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  7044. case 'MultiPoint':
  7045. for (i = 0, len = coords.length; i < len; i++) {
  7046. latlng = _coordsToLatLng(coords[i]);
  7047. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  7048. }
  7049. return new FeatureGroup(layers);
  7050. case 'LineString':
  7051. case 'MultiLineString':
  7052. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7053. return new Polyline(latlngs, options);
  7054. case 'Polygon':
  7055. case 'MultiPolygon':
  7056. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7057. return new Polygon(latlngs, options);
  7058. case 'GeometryCollection':
  7059. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7060. var layer = geometryToLayer({
  7061. geometry: geometry.geometries[i],
  7062. type: 'Feature',
  7063. properties: geojson.properties
  7064. }, options);
  7065. if (layer) {
  7066. layers.push(layer);
  7067. }
  7068. }
  7069. return new FeatureGroup(layers);
  7070. default:
  7071. throw new Error('Invalid GeoJSON object.');
  7072. }
  7073. }
  7074. // @function coordsToLatLng(coords: Array): LatLng
  7075. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7076. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7077. function coordsToLatLng(coords) {
  7078. return new LatLng(coords[1], coords[0], coords[2]);
  7079. }
  7080. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7081. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7082. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7083. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7084. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7085. var latlngs = [];
  7086. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7087. latlng = levelsDeep ?
  7088. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7089. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7090. latlngs.push(latlng);
  7091. }
  7092. return latlngs;
  7093. }
  7094. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7095. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7096. function latLngToCoords(latlng, precision) {
  7097. precision = typeof precision === 'number' ? precision : 6;
  7098. return latlng.alt !== undefined ?
  7099. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7100. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7101. }
  7102. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7103. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7104. // `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.
  7105. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7106. var coords = [];
  7107. for (var i = 0, len = latlngs.length; i < len; i++) {
  7108. coords.push(levelsDeep ?
  7109. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7110. latLngToCoords(latlngs[i], precision));
  7111. }
  7112. if (!levelsDeep && closed) {
  7113. coords.push(coords[0]);
  7114. }
  7115. return coords;
  7116. }
  7117. function getFeature(layer, newGeometry) {
  7118. return layer.feature ?
  7119. extend({}, layer.feature, {geometry: newGeometry}) :
  7120. asFeature(newGeometry);
  7121. }
  7122. // @function asFeature(geojson: Object): Object
  7123. // Normalize GeoJSON geometries/features into GeoJSON features.
  7124. function asFeature(geojson) {
  7125. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7126. return geojson;
  7127. }
  7128. return {
  7129. type: 'Feature',
  7130. properties: {},
  7131. geometry: geojson
  7132. };
  7133. }
  7134. var PointToGeoJSON = {
  7135. toGeoJSON: function (precision) {
  7136. return getFeature(this, {
  7137. type: 'Point',
  7138. coordinates: latLngToCoords(this.getLatLng(), precision)
  7139. });
  7140. }
  7141. };
  7142. // @namespace Marker
  7143. // @method toGeoJSON(): Object
  7144. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7145. Marker.include(PointToGeoJSON);
  7146. // @namespace CircleMarker
  7147. // @method toGeoJSON(): Object
  7148. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7149. Circle.include(PointToGeoJSON);
  7150. CircleMarker.include(PointToGeoJSON);
  7151. // @namespace Polyline
  7152. // @method toGeoJSON(): Object
  7153. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7154. Polyline.include({
  7155. toGeoJSON: function (precision) {
  7156. var multi = !isFlat(this._latlngs);
  7157. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7158. return getFeature(this, {
  7159. type: (multi ? 'Multi' : '') + 'LineString',
  7160. coordinates: coords
  7161. });
  7162. }
  7163. });
  7164. // @namespace Polygon
  7165. // @method toGeoJSON(): Object
  7166. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7167. Polygon.include({
  7168. toGeoJSON: function (precision) {
  7169. var holes = !isFlat(this._latlngs),
  7170. multi = holes && !isFlat(this._latlngs[0]);
  7171. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7172. if (!holes) {
  7173. coords = [coords];
  7174. }
  7175. return getFeature(this, {
  7176. type: (multi ? 'Multi' : '') + 'Polygon',
  7177. coordinates: coords
  7178. });
  7179. }
  7180. });
  7181. // @namespace LayerGroup
  7182. LayerGroup.include({
  7183. toMultiPoint: function (precision) {
  7184. var coords = [];
  7185. this.eachLayer(function (layer) {
  7186. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7187. });
  7188. return getFeature(this, {
  7189. type: 'MultiPoint',
  7190. coordinates: coords
  7191. });
  7192. },
  7193. // @method toGeoJSON(): Object
  7194. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7195. toGeoJSON: function (precision) {
  7196. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7197. if (type === 'MultiPoint') {
  7198. return this.toMultiPoint(precision);
  7199. }
  7200. var isGeometryCollection = type === 'GeometryCollection',
  7201. jsons = [];
  7202. this.eachLayer(function (layer) {
  7203. if (layer.toGeoJSON) {
  7204. var json = layer.toGeoJSON(precision);
  7205. if (isGeometryCollection) {
  7206. jsons.push(json.geometry);
  7207. } else {
  7208. var feature = asFeature(json);
  7209. // Squash nested feature collections
  7210. if (feature.type === 'FeatureCollection') {
  7211. jsons.push.apply(jsons, feature.features);
  7212. } else {
  7213. jsons.push(feature);
  7214. }
  7215. }
  7216. }
  7217. });
  7218. if (isGeometryCollection) {
  7219. return getFeature(this, {
  7220. geometries: jsons,
  7221. type: 'GeometryCollection'
  7222. });
  7223. }
  7224. return {
  7225. type: 'FeatureCollection',
  7226. features: jsons
  7227. };
  7228. }
  7229. });
  7230. // @namespace GeoJSON
  7231. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7232. // Creates a GeoJSON layer. Optionally accepts an object in
  7233. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7234. // (you can alternatively add it later with `addData` method) and an `options` object.
  7235. function geoJSON(geojson, options) {
  7236. return new GeoJSON(geojson, options);
  7237. }
  7238. // Backward compatibility.
  7239. var geoJson = geoJSON;
  7240. /*
  7241. * @class ImageOverlay
  7242. * @aka L.ImageOverlay
  7243. * @inherits Interactive layer
  7244. *
  7245. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7246. *
  7247. * @example
  7248. *
  7249. * ```js
  7250. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7251. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7252. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7253. * ```
  7254. */
  7255. var ImageOverlay = Layer.extend({
  7256. // @section
  7257. // @aka ImageOverlay options
  7258. options: {
  7259. // @option opacity: Number = 1.0
  7260. // The opacity of the image overlay.
  7261. opacity: 1,
  7262. // @option alt: String = ''
  7263. // Text for the `alt` attribute of the image (useful for accessibility).
  7264. alt: '',
  7265. // @option interactive: Boolean = false
  7266. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7267. interactive: false,
  7268. // @option crossOrigin: Boolean = false
  7269. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  7270. crossOrigin: false,
  7271. // @option errorOverlayUrl: String = ''
  7272. // URL to the overlay image to show in place of the overlay that failed to load.
  7273. errorOverlayUrl: '',
  7274. // @option zIndex: Number = 1
  7275. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer.
  7276. zIndex: 1,
  7277. // @option className: String = ''
  7278. // A custom class name to assign to the image. Empty by default.
  7279. className: '',
  7280. },
  7281. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7282. this._url = url;
  7283. this._bounds = toLatLngBounds(bounds);
  7284. setOptions(this, options);
  7285. },
  7286. onAdd: function () {
  7287. if (!this._image) {
  7288. this._initImage();
  7289. if (this.options.opacity < 1) {
  7290. this._updateOpacity();
  7291. }
  7292. }
  7293. if (this.options.interactive) {
  7294. addClass(this._image, 'leaflet-interactive');
  7295. this.addInteractiveTarget(this._image);
  7296. }
  7297. this.getPane().appendChild(this._image);
  7298. this._reset();
  7299. },
  7300. onRemove: function () {
  7301. remove(this._image);
  7302. if (this.options.interactive) {
  7303. this.removeInteractiveTarget(this._image);
  7304. }
  7305. },
  7306. // @method setOpacity(opacity: Number): this
  7307. // Sets the opacity of the overlay.
  7308. setOpacity: function (opacity) {
  7309. this.options.opacity = opacity;
  7310. if (this._image) {
  7311. this._updateOpacity();
  7312. }
  7313. return this;
  7314. },
  7315. setStyle: function (styleOpts) {
  7316. if (styleOpts.opacity) {
  7317. this.setOpacity(styleOpts.opacity);
  7318. }
  7319. return this;
  7320. },
  7321. // @method bringToFront(): this
  7322. // Brings the layer to the top of all overlays.
  7323. bringToFront: function () {
  7324. if (this._map) {
  7325. toFront(this._image);
  7326. }
  7327. return this;
  7328. },
  7329. // @method bringToBack(): this
  7330. // Brings the layer to the bottom of all overlays.
  7331. bringToBack: function () {
  7332. if (this._map) {
  7333. toBack(this._image);
  7334. }
  7335. return this;
  7336. },
  7337. // @method setUrl(url: String): this
  7338. // Changes the URL of the image.
  7339. setUrl: function (url) {
  7340. this._url = url;
  7341. if (this._image) {
  7342. this._image.src = url;
  7343. }
  7344. return this;
  7345. },
  7346. // @method setBounds(bounds: LatLngBounds): this
  7347. // Update the bounds that this ImageOverlay covers
  7348. setBounds: function (bounds) {
  7349. this._bounds = toLatLngBounds(bounds);
  7350. if (this._map) {
  7351. this._reset();
  7352. }
  7353. return this;
  7354. },
  7355. getEvents: function () {
  7356. var events = {
  7357. zoom: this._reset,
  7358. viewreset: this._reset
  7359. };
  7360. if (this._zoomAnimated) {
  7361. events.zoomanim = this._animateZoom;
  7362. }
  7363. return events;
  7364. },
  7365. // @method: setZIndex(value: Number) : this
  7366. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7367. setZIndex: function (value) {
  7368. this.options.zIndex = value;
  7369. this._updateZIndex();
  7370. return this;
  7371. },
  7372. // @method getBounds(): LatLngBounds
  7373. // Get the bounds that this ImageOverlay covers
  7374. getBounds: function () {
  7375. return this._bounds;
  7376. },
  7377. // @method getElement(): HTMLElement
  7378. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7379. // used by this overlay.
  7380. getElement: function () {
  7381. return this._image;
  7382. },
  7383. _initImage: function () {
  7384. var wasElementSupplied = this._url.tagName === 'IMG';
  7385. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7386. addClass(img, 'leaflet-image-layer');
  7387. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7388. if (this.options.className) { addClass(img, this.options.className); }
  7389. img.onselectstart = falseFn;
  7390. img.onmousemove = falseFn;
  7391. // @event load: Event
  7392. // Fired when the ImageOverlay layer has loaded its image
  7393. img.onload = bind(this.fire, this, 'load');
  7394. img.onerror = bind(this._overlayOnError, this, 'error');
  7395. if (this.options.crossOrigin) {
  7396. img.crossOrigin = '';
  7397. }
  7398. if (this.options.zIndex) {
  7399. this._updateZIndex();
  7400. }
  7401. if (wasElementSupplied) {
  7402. this._url = img.src;
  7403. return;
  7404. }
  7405. img.src = this._url;
  7406. img.alt = this.options.alt;
  7407. },
  7408. _animateZoom: function (e) {
  7409. var scale = this._map.getZoomScale(e.zoom),
  7410. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7411. setTransform(this._image, offset, scale);
  7412. },
  7413. _reset: function () {
  7414. var image = this._image,
  7415. bounds = new Bounds(
  7416. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7417. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7418. size = bounds.getSize();
  7419. setPosition(image, bounds.min);
  7420. image.style.width = size.x + 'px';
  7421. image.style.height = size.y + 'px';
  7422. },
  7423. _updateOpacity: function () {
  7424. setOpacity(this._image, this.options.opacity);
  7425. },
  7426. _updateZIndex: function () {
  7427. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7428. this._image.style.zIndex = this.options.zIndex;
  7429. }
  7430. },
  7431. _overlayOnError: function () {
  7432. // @event error: Event
  7433. // Fired when the ImageOverlay layer has loaded its image
  7434. this.fire('error');
  7435. var errorUrl = this.options.errorOverlayUrl;
  7436. if (errorUrl && this._url !== errorUrl) {
  7437. this._url = errorUrl;
  7438. this._image.src = errorUrl;
  7439. }
  7440. }
  7441. });
  7442. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7443. // Instantiates an image overlay object given the URL of the image and the
  7444. // geographical bounds it is tied to.
  7445. var imageOverlay = function (url, bounds, options) {
  7446. return new ImageOverlay(url, bounds, options);
  7447. };
  7448. /*
  7449. * @class VideoOverlay
  7450. * @aka L.VideoOverlay
  7451. * @inherits ImageOverlay
  7452. *
  7453. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7454. *
  7455. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7456. * HTML5 element.
  7457. *
  7458. * @example
  7459. *
  7460. * ```js
  7461. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7462. * videoBounds = [[ 32, -130], [ 13, -100]];
  7463. * L.VideoOverlay(videoUrl, videoBounds ).addTo(map);
  7464. * ```
  7465. */
  7466. var VideoOverlay = ImageOverlay.extend({
  7467. // @section
  7468. // @aka VideoOverlay options
  7469. options: {
  7470. // @option autoplay: Boolean = true
  7471. // Whether the video starts playing automatically when loaded.
  7472. autoplay: true,
  7473. // @option loop: Boolean = true
  7474. // Whether the video will loop back to the beginning when played.
  7475. loop: true
  7476. },
  7477. _initImage: function () {
  7478. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7479. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7480. addClass(vid, 'leaflet-image-layer');
  7481. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7482. vid.onselectstart = falseFn;
  7483. vid.onmousemove = falseFn;
  7484. // @event load: Event
  7485. // Fired when the video has finished loading the first frame
  7486. vid.onloadeddata = bind(this.fire, this, 'load');
  7487. if (wasElementSupplied) {
  7488. var sourceElements = vid.getElementsByTagName('source');
  7489. var sources = [];
  7490. for (var j = 0; j < sourceElements.length; j++) {
  7491. sources.push(sourceElements[j].src);
  7492. }
  7493. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7494. return;
  7495. }
  7496. if (!isArray(this._url)) { this._url = [this._url]; }
  7497. vid.autoplay = !!this.options.autoplay;
  7498. vid.loop = !!this.options.loop;
  7499. for (var i = 0; i < this._url.length; i++) {
  7500. var source = create$1('source');
  7501. source.src = this._url[i];
  7502. vid.appendChild(source);
  7503. }
  7504. }
  7505. // @method getElement(): HTMLVideoElement
  7506. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7507. // used by this overlay.
  7508. });
  7509. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7510. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7511. // geographical bounds it is tied to.
  7512. function videoOverlay(video, bounds, options) {
  7513. return new VideoOverlay(video, bounds, options);
  7514. }
  7515. /*
  7516. * @class DivOverlay
  7517. * @inherits Layer
  7518. * @aka L.DivOverlay
  7519. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7520. */
  7521. // @namespace DivOverlay
  7522. var DivOverlay = Layer.extend({
  7523. // @section
  7524. // @aka DivOverlay options
  7525. options: {
  7526. // @option offset: Point = Point(0, 7)
  7527. // The offset of the popup position. Useful to control the anchor
  7528. // of the popup when opening it on some overlays.
  7529. offset: [0, 7],
  7530. // @option className: String = ''
  7531. // A custom CSS class name to assign to the popup.
  7532. className: '',
  7533. // @option pane: String = 'popupPane'
  7534. // `Map pane` where the popup will be added.
  7535. pane: 'popupPane'
  7536. },
  7537. initialize: function (options, source) {
  7538. setOptions(this, options);
  7539. this._source = source;
  7540. },
  7541. onAdd: function (map) {
  7542. this._zoomAnimated = map._zoomAnimated;
  7543. if (!this._container) {
  7544. this._initLayout();
  7545. }
  7546. if (map._fadeAnimated) {
  7547. setOpacity(this._container, 0);
  7548. }
  7549. clearTimeout(this._removeTimeout);
  7550. this.getPane().appendChild(this._container);
  7551. this.update();
  7552. if (map._fadeAnimated) {
  7553. setOpacity(this._container, 1);
  7554. }
  7555. this.bringToFront();
  7556. },
  7557. onRemove: function (map) {
  7558. if (map._fadeAnimated) {
  7559. setOpacity(this._container, 0);
  7560. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7561. } else {
  7562. remove(this._container);
  7563. }
  7564. },
  7565. // @namespace Popup
  7566. // @method getLatLng: LatLng
  7567. // Returns the geographical point of popup.
  7568. getLatLng: function () {
  7569. return this._latlng;
  7570. },
  7571. // @method setLatLng(latlng: LatLng): this
  7572. // Sets the geographical point where the popup will open.
  7573. setLatLng: function (latlng) {
  7574. this._latlng = toLatLng(latlng);
  7575. if (this._map) {
  7576. this._updatePosition();
  7577. this._adjustPan();
  7578. }
  7579. return this;
  7580. },
  7581. // @method getContent: String|HTMLElement
  7582. // Returns the content of the popup.
  7583. getContent: function () {
  7584. return this._content;
  7585. },
  7586. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7587. // Sets the HTML content of the popup. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the popup.
  7588. setContent: function (content) {
  7589. this._content = content;
  7590. this.update();
  7591. return this;
  7592. },
  7593. // @method getElement: String|HTMLElement
  7594. // Alias for [getContent()](#popup-getcontent)
  7595. getElement: function () {
  7596. return this._container;
  7597. },
  7598. // @method update: null
  7599. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7600. update: function () {
  7601. if (!this._map) { return; }
  7602. this._container.style.visibility = 'hidden';
  7603. this._updateContent();
  7604. this._updateLayout();
  7605. this._updatePosition();
  7606. this._container.style.visibility = '';
  7607. this._adjustPan();
  7608. },
  7609. getEvents: function () {
  7610. var events = {
  7611. zoom: this._updatePosition,
  7612. viewreset: this._updatePosition
  7613. };
  7614. if (this._zoomAnimated) {
  7615. events.zoomanim = this._animateZoom;
  7616. }
  7617. return events;
  7618. },
  7619. // @method isOpen: Boolean
  7620. // Returns `true` when the popup is visible on the map.
  7621. isOpen: function () {
  7622. return !!this._map && this._map.hasLayer(this);
  7623. },
  7624. // @method bringToFront: this
  7625. // Brings this popup in front of other popups (in the same map pane).
  7626. bringToFront: function () {
  7627. if (this._map) {
  7628. toFront(this._container);
  7629. }
  7630. return this;
  7631. },
  7632. // @method bringToBack: this
  7633. // Brings this popup to the back of other popups (in the same map pane).
  7634. bringToBack: function () {
  7635. if (this._map) {
  7636. toBack(this._container);
  7637. }
  7638. return this;
  7639. },
  7640. _updateContent: function () {
  7641. if (!this._content) { return; }
  7642. var node = this._contentNode;
  7643. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7644. if (typeof content === 'string') {
  7645. node.innerHTML = content;
  7646. } else {
  7647. while (node.hasChildNodes()) {
  7648. node.removeChild(node.firstChild);
  7649. }
  7650. node.appendChild(content);
  7651. }
  7652. this.fire('contentupdate');
  7653. },
  7654. _updatePosition: function () {
  7655. if (!this._map) { return; }
  7656. var pos = this._map.latLngToLayerPoint(this._latlng),
  7657. offset = toPoint(this.options.offset),
  7658. anchor = this._getAnchor();
  7659. if (this._zoomAnimated) {
  7660. setPosition(this._container, pos.add(anchor));
  7661. } else {
  7662. offset = offset.add(pos).add(anchor);
  7663. }
  7664. var bottom = this._containerBottom = -offset.y,
  7665. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7666. // bottom position the popup in case the height of the popup changes (images loading etc)
  7667. this._container.style.bottom = bottom + 'px';
  7668. this._container.style.left = left + 'px';
  7669. },
  7670. _getAnchor: function () {
  7671. return [0, 0];
  7672. }
  7673. });
  7674. /*
  7675. * @class Popup
  7676. * @inherits DivOverlay
  7677. * @aka L.Popup
  7678. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7679. * open popups while making sure that only one popup is open at one time
  7680. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7681. *
  7682. * @example
  7683. *
  7684. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7685. *
  7686. * ```js
  7687. * marker.bindPopup(popupContent).openPopup();
  7688. * ```
  7689. * Path overlays like polylines also have a `bindPopup` method.
  7690. * Here's a more complicated way to open a popup on a map:
  7691. *
  7692. * ```js
  7693. * var popup = L.popup()
  7694. * .setLatLng(latlng)
  7695. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7696. * .openOn(map);
  7697. * ```
  7698. */
  7699. // @namespace Popup
  7700. var Popup = DivOverlay.extend({
  7701. // @section
  7702. // @aka Popup options
  7703. options: {
  7704. // @option maxWidth: Number = 300
  7705. // Max width of the popup, in pixels.
  7706. maxWidth: 300,
  7707. // @option minWidth: Number = 50
  7708. // Min width of the popup, in pixels.
  7709. minWidth: 50,
  7710. // @option maxHeight: Number = null
  7711. // If set, creates a scrollable container of the given height
  7712. // inside a popup if its content exceeds it.
  7713. maxHeight: null,
  7714. // @option autoPan: Boolean = true
  7715. // Set it to `false` if you don't want the map to do panning animation
  7716. // to fit the opened popup.
  7717. autoPan: true,
  7718. // @option autoPanPaddingTopLeft: Point = null
  7719. // The margin between the popup and the top left corner of the map
  7720. // view after autopanning was performed.
  7721. autoPanPaddingTopLeft: null,
  7722. // @option autoPanPaddingBottomRight: Point = null
  7723. // The margin between the popup and the bottom right corner of the map
  7724. // view after autopanning was performed.
  7725. autoPanPaddingBottomRight: null,
  7726. // @option autoPanPadding: Point = Point(5, 5)
  7727. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7728. autoPanPadding: [5, 5],
  7729. // @option keepInView: Boolean = false
  7730. // Set it to `true` if you want to prevent users from panning the popup
  7731. // off of the screen while it is open.
  7732. keepInView: false,
  7733. // @option closeButton: Boolean = true
  7734. // Controls the presence of a close button in the popup.
  7735. closeButton: true,
  7736. // @option autoClose: Boolean = true
  7737. // Set it to `false` if you want to override the default behavior of
  7738. // the popup closing when another popup is opened.
  7739. autoClose: true,
  7740. // @option closeOnEscapeKey: Boolean = true
  7741. // Set it to `false` if you want to override the default behavior of
  7742. // the ESC key for closing of the popup.
  7743. closeOnEscapeKey: true,
  7744. // @option closeOnClick: Boolean = *
  7745. // Set it if you want to override the default behavior of the popup closing when user clicks
  7746. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7747. // @option className: String = ''
  7748. // A custom CSS class name to assign to the popup.
  7749. className: ''
  7750. },
  7751. // @namespace Popup
  7752. // @method openOn(map: Map): this
  7753. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7754. openOn: function (map) {
  7755. map.openPopup(this);
  7756. return this;
  7757. },
  7758. onAdd: function (map) {
  7759. DivOverlay.prototype.onAdd.call(this, map);
  7760. // @namespace Map
  7761. // @section Popup events
  7762. // @event popupopen: PopupEvent
  7763. // Fired when a popup is opened in the map
  7764. map.fire('popupopen', {popup: this});
  7765. if (this._source) {
  7766. // @namespace Layer
  7767. // @section Popup events
  7768. // @event popupopen: PopupEvent
  7769. // Fired when a popup bound to this layer is opened
  7770. this._source.fire('popupopen', {popup: this}, true);
  7771. // For non-path layers, we toggle the popup when clicking
  7772. // again the layer, so prevent the map to reopen it.
  7773. if (!(this._source instanceof Path)) {
  7774. this._source.on('preclick', stopPropagation);
  7775. }
  7776. }
  7777. },
  7778. onRemove: function (map) {
  7779. DivOverlay.prototype.onRemove.call(this, map);
  7780. // @namespace Map
  7781. // @section Popup events
  7782. // @event popupclose: PopupEvent
  7783. // Fired when a popup in the map is closed
  7784. map.fire('popupclose', {popup: this});
  7785. if (this._source) {
  7786. // @namespace Layer
  7787. // @section Popup events
  7788. // @event popupclose: PopupEvent
  7789. // Fired when a popup bound to this layer is closed
  7790. this._source.fire('popupclose', {popup: this}, true);
  7791. if (!(this._source instanceof Path)) {
  7792. this._source.off('preclick', stopPropagation);
  7793. }
  7794. }
  7795. },
  7796. getEvents: function () {
  7797. var events = DivOverlay.prototype.getEvents.call(this);
  7798. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7799. events.preclick = this._close;
  7800. }
  7801. if (this.options.keepInView) {
  7802. events.moveend = this._adjustPan;
  7803. }
  7804. return events;
  7805. },
  7806. _close: function () {
  7807. if (this._map) {
  7808. this._map.closePopup(this);
  7809. }
  7810. },
  7811. _initLayout: function () {
  7812. var prefix = 'leaflet-popup',
  7813. container = this._container = create$1('div',
  7814. prefix + ' ' + (this.options.className || '') +
  7815. ' leaflet-zoom-animated');
  7816. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  7817. this._contentNode = create$1('div', prefix + '-content', wrapper);
  7818. disableClickPropagation(wrapper);
  7819. disableScrollPropagation(this._contentNode);
  7820. on(wrapper, 'contextmenu', stopPropagation);
  7821. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  7822. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  7823. if (this.options.closeButton) {
  7824. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  7825. closeButton.href = '#close';
  7826. closeButton.innerHTML = '&#215;';
  7827. on(closeButton, 'click', this._onCloseButtonClick, this);
  7828. }
  7829. },
  7830. _updateLayout: function () {
  7831. var container = this._contentNode,
  7832. style = container.style;
  7833. style.width = '';
  7834. style.whiteSpace = 'nowrap';
  7835. var width = container.offsetWidth;
  7836. width = Math.min(width, this.options.maxWidth);
  7837. width = Math.max(width, this.options.minWidth);
  7838. style.width = (width + 1) + 'px';
  7839. style.whiteSpace = '';
  7840. style.height = '';
  7841. var height = container.offsetHeight,
  7842. maxHeight = this.options.maxHeight,
  7843. scrolledClass = 'leaflet-popup-scrolled';
  7844. if (maxHeight && height > maxHeight) {
  7845. style.height = maxHeight + 'px';
  7846. addClass(container, scrolledClass);
  7847. } else {
  7848. removeClass(container, scrolledClass);
  7849. }
  7850. this._containerWidth = this._container.offsetWidth;
  7851. },
  7852. _animateZoom: function (e) {
  7853. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  7854. anchor = this._getAnchor();
  7855. setPosition(this._container, pos.add(anchor));
  7856. },
  7857. _adjustPan: function () {
  7858. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  7859. var map = this._map,
  7860. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  7861. containerHeight = this._container.offsetHeight + marginBottom,
  7862. containerWidth = this._containerWidth,
  7863. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  7864. layerPos._add(getPosition(this._container));
  7865. var containerPos = map.layerPointToContainerPoint(layerPos),
  7866. padding = toPoint(this.options.autoPanPadding),
  7867. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  7868. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  7869. size = map.getSize(),
  7870. dx = 0,
  7871. dy = 0;
  7872. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  7873. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  7874. }
  7875. if (containerPos.x - dx - paddingTL.x < 0) { // left
  7876. dx = containerPos.x - paddingTL.x;
  7877. }
  7878. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  7879. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  7880. }
  7881. if (containerPos.y - dy - paddingTL.y < 0) { // top
  7882. dy = containerPos.y - paddingTL.y;
  7883. }
  7884. // @namespace Map
  7885. // @section Popup events
  7886. // @event autopanstart: Event
  7887. // Fired when the map starts autopanning when opening a popup.
  7888. if (dx || dy) {
  7889. map
  7890. .fire('autopanstart')
  7891. .panBy([dx, dy]);
  7892. }
  7893. },
  7894. _onCloseButtonClick: function (e) {
  7895. this._close();
  7896. stop(e);
  7897. },
  7898. _getAnchor: function () {
  7899. // Where should we anchor the popup on the source layer?
  7900. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  7901. }
  7902. });
  7903. // @namespace Popup
  7904. // @factory L.popup(options?: Popup options, source?: Layer)
  7905. // 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.
  7906. var popup = function (options, source) {
  7907. return new Popup(options, source);
  7908. };
  7909. /* @namespace Map
  7910. * @section Interaction Options
  7911. * @option closePopupOnClick: Boolean = true
  7912. * Set it to `false` if you don't want popups to close when user clicks the map.
  7913. */
  7914. Map.mergeOptions({
  7915. closePopupOnClick: true
  7916. });
  7917. // @namespace Map
  7918. // @section Methods for Layers and Controls
  7919. Map.include({
  7920. // @method openPopup(popup: Popup): this
  7921. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  7922. // @alternative
  7923. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  7924. // Creates a popup with the specified content and options and opens it in the given point on a map.
  7925. openPopup: function (popup, latlng, options) {
  7926. if (!(popup instanceof Popup)) {
  7927. popup = new Popup(options).setContent(popup);
  7928. }
  7929. if (latlng) {
  7930. popup.setLatLng(latlng);
  7931. }
  7932. if (this.hasLayer(popup)) {
  7933. return this;
  7934. }
  7935. if (this._popup && this._popup.options.autoClose) {
  7936. this.closePopup();
  7937. }
  7938. this._popup = popup;
  7939. return this.addLayer(popup);
  7940. },
  7941. // @method closePopup(popup?: Popup): this
  7942. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  7943. closePopup: function (popup) {
  7944. if (!popup || popup === this._popup) {
  7945. popup = this._popup;
  7946. this._popup = null;
  7947. }
  7948. if (popup) {
  7949. this.removeLayer(popup);
  7950. }
  7951. return this;
  7952. }
  7953. });
  7954. /*
  7955. * @namespace Layer
  7956. * @section Popup methods example
  7957. *
  7958. * All layers share a set of methods convenient for binding popups to it.
  7959. *
  7960. * ```js
  7961. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  7962. * layer.openPopup();
  7963. * layer.closePopup();
  7964. * ```
  7965. *
  7966. * 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.
  7967. */
  7968. // @section Popup methods
  7969. Layer.include({
  7970. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  7971. // Binds a popup to the layer with the passed `content` and sets up the
  7972. // necessary event listeners. If a `Function` is passed it will receive
  7973. // the layer as the first argument and should return a `String` or `HTMLElement`.
  7974. bindPopup: function (content, options) {
  7975. if (content instanceof Popup) {
  7976. setOptions(content, options);
  7977. this._popup = content;
  7978. content._source = this;
  7979. } else {
  7980. if (!this._popup || options) {
  7981. this._popup = new Popup(options, this);
  7982. }
  7983. this._popup.setContent(content);
  7984. }
  7985. if (!this._popupHandlersAdded) {
  7986. this.on({
  7987. click: this._openPopup,
  7988. keypress: this._onKeyPress,
  7989. remove: this.closePopup,
  7990. move: this._movePopup
  7991. });
  7992. this._popupHandlersAdded = true;
  7993. }
  7994. return this;
  7995. },
  7996. // @method unbindPopup(): this
  7997. // Removes the popup previously bound with `bindPopup`.
  7998. unbindPopup: function () {
  7999. if (this._popup) {
  8000. this.off({
  8001. click: this._openPopup,
  8002. keypress: this._onKeyPress,
  8003. remove: this.closePopup,
  8004. move: this._movePopup
  8005. });
  8006. this._popupHandlersAdded = false;
  8007. this._popup = null;
  8008. }
  8009. return this;
  8010. },
  8011. // @method openPopup(latlng?: LatLng): this
  8012. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8013. openPopup: function (layer, latlng) {
  8014. if (!(layer instanceof Layer)) {
  8015. latlng = layer;
  8016. layer = this;
  8017. }
  8018. if (layer instanceof FeatureGroup) {
  8019. for (var id in this._layers) {
  8020. layer = this._layers[id];
  8021. break;
  8022. }
  8023. }
  8024. if (!latlng) {
  8025. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8026. }
  8027. if (this._popup && this._map) {
  8028. // set popup source to this layer
  8029. this._popup._source = layer;
  8030. // update the popup (content, layout, ect...)
  8031. this._popup.update();
  8032. // open the popup on the map
  8033. this._map.openPopup(this._popup, latlng);
  8034. }
  8035. return this;
  8036. },
  8037. // @method closePopup(): this
  8038. // Closes the popup bound to this layer if it is open.
  8039. closePopup: function () {
  8040. if (this._popup) {
  8041. this._popup._close();
  8042. }
  8043. return this;
  8044. },
  8045. // @method togglePopup(): this
  8046. // Opens or closes the popup bound to this layer depending on its current state.
  8047. togglePopup: function (target) {
  8048. if (this._popup) {
  8049. if (this._popup._map) {
  8050. this.closePopup();
  8051. } else {
  8052. this.openPopup(target);
  8053. }
  8054. }
  8055. return this;
  8056. },
  8057. // @method isPopupOpen(): boolean
  8058. // Returns `true` if the popup bound to this layer is currently open.
  8059. isPopupOpen: function () {
  8060. return (this._popup ? this._popup.isOpen() : false);
  8061. },
  8062. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8063. // Sets the content of the popup bound to this layer.
  8064. setPopupContent: function (content) {
  8065. if (this._popup) {
  8066. this._popup.setContent(content);
  8067. }
  8068. return this;
  8069. },
  8070. // @method getPopup(): Popup
  8071. // Returns the popup bound to this layer.
  8072. getPopup: function () {
  8073. return this._popup;
  8074. },
  8075. _openPopup: function (e) {
  8076. var layer = e.layer || e.target;
  8077. if (!this._popup) {
  8078. return;
  8079. }
  8080. if (!this._map) {
  8081. return;
  8082. }
  8083. // prevent map click
  8084. stop(e);
  8085. // if this inherits from Path its a vector and we can just
  8086. // open the popup at the new location
  8087. if (layer instanceof Path) {
  8088. this.openPopup(e.layer || e.target, e.latlng);
  8089. return;
  8090. }
  8091. // otherwise treat it like a marker and figure out
  8092. // if we should toggle it open/closed
  8093. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8094. this.closePopup();
  8095. } else {
  8096. this.openPopup(layer, e.latlng);
  8097. }
  8098. },
  8099. _movePopup: function (e) {
  8100. this._popup.setLatLng(e.latlng);
  8101. },
  8102. _onKeyPress: function (e) {
  8103. if (e.originalEvent.keyCode === 13) {
  8104. this._openPopup(e);
  8105. }
  8106. }
  8107. });
  8108. /*
  8109. * @class Tooltip
  8110. * @inherits DivOverlay
  8111. * @aka L.Tooltip
  8112. * Used to display small texts on top of map layers.
  8113. *
  8114. * @example
  8115. *
  8116. * ```js
  8117. * marker.bindTooltip("my tooltip text").openTooltip();
  8118. * ```
  8119. * Note about tooltip offset. Leaflet takes two options in consideration
  8120. * for computing tooltip offsetting:
  8121. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8122. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8123. * move it to the bottom. Negatives will move to the left and top.
  8124. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8125. * should adapt this value if you use a custom icon.
  8126. */
  8127. // @namespace Tooltip
  8128. var Tooltip = DivOverlay.extend({
  8129. // @section
  8130. // @aka Tooltip options
  8131. options: {
  8132. // @option pane: String = 'tooltipPane'
  8133. // `Map pane` where the tooltip will be added.
  8134. pane: 'tooltipPane',
  8135. // @option offset: Point = Point(0, 0)
  8136. // Optional offset of the tooltip position.
  8137. offset: [0, 0],
  8138. // @option direction: String = 'auto'
  8139. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8140. // `top`, `bottom`, `center`, `auto`.
  8141. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8142. // position on the map.
  8143. direction: 'auto',
  8144. // @option permanent: Boolean = false
  8145. // Whether to open the tooltip permanently or only on mouseover.
  8146. permanent: false,
  8147. // @option sticky: Boolean = false
  8148. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8149. sticky: false,
  8150. // @option interactive: Boolean = false
  8151. // If true, the tooltip will listen to the feature events.
  8152. interactive: false,
  8153. // @option opacity: Number = 0.9
  8154. // Tooltip container opacity.
  8155. opacity: 0.9
  8156. },
  8157. onAdd: function (map) {
  8158. DivOverlay.prototype.onAdd.call(this, map);
  8159. this.setOpacity(this.options.opacity);
  8160. // @namespace Map
  8161. // @section Tooltip events
  8162. // @event tooltipopen: TooltipEvent
  8163. // Fired when a tooltip is opened in the map.
  8164. map.fire('tooltipopen', {tooltip: this});
  8165. if (this._source) {
  8166. // @namespace Layer
  8167. // @section Tooltip events
  8168. // @event tooltipopen: TooltipEvent
  8169. // Fired when a tooltip bound to this layer is opened.
  8170. this._source.fire('tooltipopen', {tooltip: this}, true);
  8171. }
  8172. },
  8173. onRemove: function (map) {
  8174. DivOverlay.prototype.onRemove.call(this, map);
  8175. // @namespace Map
  8176. // @section Tooltip events
  8177. // @event tooltipclose: TooltipEvent
  8178. // Fired when a tooltip in the map is closed.
  8179. map.fire('tooltipclose', {tooltip: this});
  8180. if (this._source) {
  8181. // @namespace Layer
  8182. // @section Tooltip events
  8183. // @event tooltipclose: TooltipEvent
  8184. // Fired when a tooltip bound to this layer is closed.
  8185. this._source.fire('tooltipclose', {tooltip: this}, true);
  8186. }
  8187. },
  8188. getEvents: function () {
  8189. var events = DivOverlay.prototype.getEvents.call(this);
  8190. if (touch && !this.options.permanent) {
  8191. events.preclick = this._close;
  8192. }
  8193. return events;
  8194. },
  8195. _close: function () {
  8196. if (this._map) {
  8197. this._map.closeTooltip(this);
  8198. }
  8199. },
  8200. _initLayout: function () {
  8201. var prefix = 'leaflet-tooltip',
  8202. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8203. this._contentNode = this._container = create$1('div', className);
  8204. },
  8205. _updateLayout: function () {},
  8206. _adjustPan: function () {},
  8207. _setPosition: function (pos) {
  8208. var map = this._map,
  8209. container = this._container,
  8210. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8211. tooltipPoint = map.layerPointToContainerPoint(pos),
  8212. direction = this.options.direction,
  8213. tooltipWidth = container.offsetWidth,
  8214. tooltipHeight = container.offsetHeight,
  8215. offset = toPoint(this.options.offset),
  8216. anchor = this._getAnchor();
  8217. if (direction === 'top') {
  8218. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8219. } else if (direction === 'bottom') {
  8220. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8221. } else if (direction === 'center') {
  8222. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8223. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8224. direction = 'right';
  8225. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8226. } else {
  8227. direction = 'left';
  8228. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8229. }
  8230. removeClass(container, 'leaflet-tooltip-right');
  8231. removeClass(container, 'leaflet-tooltip-left');
  8232. removeClass(container, 'leaflet-tooltip-top');
  8233. removeClass(container, 'leaflet-tooltip-bottom');
  8234. addClass(container, 'leaflet-tooltip-' + direction);
  8235. setPosition(container, pos);
  8236. },
  8237. _updatePosition: function () {
  8238. var pos = this._map.latLngToLayerPoint(this._latlng);
  8239. this._setPosition(pos);
  8240. },
  8241. setOpacity: function (opacity) {
  8242. this.options.opacity = opacity;
  8243. if (this._container) {
  8244. setOpacity(this._container, opacity);
  8245. }
  8246. },
  8247. _animateZoom: function (e) {
  8248. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8249. this._setPosition(pos);
  8250. },
  8251. _getAnchor: function () {
  8252. // Where should we anchor the tooltip on the source layer?
  8253. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8254. }
  8255. });
  8256. // @namespace Tooltip
  8257. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8258. // 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.
  8259. var tooltip = function (options, source) {
  8260. return new Tooltip(options, source);
  8261. };
  8262. // @namespace Map
  8263. // @section Methods for Layers and Controls
  8264. Map.include({
  8265. // @method openTooltip(tooltip: Tooltip): this
  8266. // Opens the specified tooltip.
  8267. // @alternative
  8268. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8269. // Creates a tooltip with the specified content and options and open it.
  8270. openTooltip: function (tooltip, latlng, options) {
  8271. if (!(tooltip instanceof Tooltip)) {
  8272. tooltip = new Tooltip(options).setContent(tooltip);
  8273. }
  8274. if (latlng) {
  8275. tooltip.setLatLng(latlng);
  8276. }
  8277. if (this.hasLayer(tooltip)) {
  8278. return this;
  8279. }
  8280. return this.addLayer(tooltip);
  8281. },
  8282. // @method closeTooltip(tooltip?: Tooltip): this
  8283. // Closes the tooltip given as parameter.
  8284. closeTooltip: function (tooltip) {
  8285. if (tooltip) {
  8286. this.removeLayer(tooltip);
  8287. }
  8288. return this;
  8289. }
  8290. });
  8291. /*
  8292. * @namespace Layer
  8293. * @section Tooltip methods example
  8294. *
  8295. * All layers share a set of methods convenient for binding tooltips to it.
  8296. *
  8297. * ```js
  8298. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8299. * layer.openTooltip();
  8300. * layer.closeTooltip();
  8301. * ```
  8302. */
  8303. // @section Tooltip methods
  8304. Layer.include({
  8305. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8306. // Binds a tooltip to the layer with the passed `content` and sets up the
  8307. // necessary event listeners. If a `Function` is passed it will receive
  8308. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8309. bindTooltip: function (content, options) {
  8310. if (content instanceof Tooltip) {
  8311. setOptions(content, options);
  8312. this._tooltip = content;
  8313. content._source = this;
  8314. } else {
  8315. if (!this._tooltip || options) {
  8316. this._tooltip = new Tooltip(options, this);
  8317. }
  8318. this._tooltip.setContent(content);
  8319. }
  8320. this._initTooltipInteractions();
  8321. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8322. this.openTooltip();
  8323. }
  8324. return this;
  8325. },
  8326. // @method unbindTooltip(): this
  8327. // Removes the tooltip previously bound with `bindTooltip`.
  8328. unbindTooltip: function () {
  8329. if (this._tooltip) {
  8330. this._initTooltipInteractions(true);
  8331. this.closeTooltip();
  8332. this._tooltip = null;
  8333. }
  8334. return this;
  8335. },
  8336. _initTooltipInteractions: function (remove$$1) {
  8337. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8338. var onOff = remove$$1 ? 'off' : 'on',
  8339. events = {
  8340. remove: this.closeTooltip,
  8341. move: this._moveTooltip
  8342. };
  8343. if (!this._tooltip.options.permanent) {
  8344. events.mouseover = this._openTooltip;
  8345. events.mouseout = this.closeTooltip;
  8346. if (this._tooltip.options.sticky) {
  8347. events.mousemove = this._moveTooltip;
  8348. }
  8349. if (touch) {
  8350. events.click = this._openTooltip;
  8351. }
  8352. } else {
  8353. events.add = this._openTooltip;
  8354. }
  8355. this[onOff](events);
  8356. this._tooltipHandlersAdded = !remove$$1;
  8357. },
  8358. // @method openTooltip(latlng?: LatLng): this
  8359. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8360. openTooltip: function (layer, latlng) {
  8361. if (!(layer instanceof Layer)) {
  8362. latlng = layer;
  8363. layer = this;
  8364. }
  8365. if (layer instanceof FeatureGroup) {
  8366. for (var id in this._layers) {
  8367. layer = this._layers[id];
  8368. break;
  8369. }
  8370. }
  8371. if (!latlng) {
  8372. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8373. }
  8374. if (this._tooltip && this._map) {
  8375. // set tooltip source to this layer
  8376. this._tooltip._source = layer;
  8377. // update the tooltip (content, layout, ect...)
  8378. this._tooltip.update();
  8379. // open the tooltip on the map
  8380. this._map.openTooltip(this._tooltip, latlng);
  8381. // Tooltip container may not be defined if not permanent and never
  8382. // opened.
  8383. if (this._tooltip.options.interactive && this._tooltip._container) {
  8384. addClass(this._tooltip._container, 'leaflet-clickable');
  8385. this.addInteractiveTarget(this._tooltip._container);
  8386. }
  8387. }
  8388. return this;
  8389. },
  8390. // @method closeTooltip(): this
  8391. // Closes the tooltip bound to this layer if it is open.
  8392. closeTooltip: function () {
  8393. if (this._tooltip) {
  8394. this._tooltip._close();
  8395. if (this._tooltip.options.interactive && this._tooltip._container) {
  8396. removeClass(this._tooltip._container, 'leaflet-clickable');
  8397. this.removeInteractiveTarget(this._tooltip._container);
  8398. }
  8399. }
  8400. return this;
  8401. },
  8402. // @method toggleTooltip(): this
  8403. // Opens or closes the tooltip bound to this layer depending on its current state.
  8404. toggleTooltip: function (target) {
  8405. if (this._tooltip) {
  8406. if (this._tooltip._map) {
  8407. this.closeTooltip();
  8408. } else {
  8409. this.openTooltip(target);
  8410. }
  8411. }
  8412. return this;
  8413. },
  8414. // @method isTooltipOpen(): boolean
  8415. // Returns `true` if the tooltip bound to this layer is currently open.
  8416. isTooltipOpen: function () {
  8417. return this._tooltip.isOpen();
  8418. },
  8419. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8420. // Sets the content of the tooltip bound to this layer.
  8421. setTooltipContent: function (content) {
  8422. if (this._tooltip) {
  8423. this._tooltip.setContent(content);
  8424. }
  8425. return this;
  8426. },
  8427. // @method getTooltip(): Tooltip
  8428. // Returns the tooltip bound to this layer.
  8429. getTooltip: function () {
  8430. return this._tooltip;
  8431. },
  8432. _openTooltip: function (e) {
  8433. var layer = e.layer || e.target;
  8434. if (!this._tooltip || !this._map) {
  8435. return;
  8436. }
  8437. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8438. },
  8439. _moveTooltip: function (e) {
  8440. var latlng = e.latlng, containerPoint, layerPoint;
  8441. if (this._tooltip.options.sticky && e.originalEvent) {
  8442. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8443. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8444. latlng = this._map.layerPointToLatLng(layerPoint);
  8445. }
  8446. this._tooltip.setLatLng(latlng);
  8447. }
  8448. });
  8449. /*
  8450. * @class DivIcon
  8451. * @aka L.DivIcon
  8452. * @inherits Icon
  8453. *
  8454. * Represents a lightweight icon for markers that uses a simple `<div>`
  8455. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8456. *
  8457. * @example
  8458. * ```js
  8459. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8460. * // you can set .my-div-icon styles in CSS
  8461. *
  8462. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8463. * ```
  8464. *
  8465. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8466. */
  8467. var DivIcon = Icon.extend({
  8468. options: {
  8469. // @section
  8470. // @aka DivIcon options
  8471. iconSize: [12, 12], // also can be set through CSS
  8472. // iconAnchor: (Point),
  8473. // popupAnchor: (Point),
  8474. // @option html: String = ''
  8475. // Custom HTML code to put inside the div element, empty by default.
  8476. html: false,
  8477. // @option bgPos: Point = [0, 0]
  8478. // Optional relative position of the background, in pixels
  8479. bgPos: null,
  8480. className: 'leaflet-div-icon'
  8481. },
  8482. createIcon: function (oldIcon) {
  8483. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8484. options = this.options;
  8485. div.innerHTML = options.html !== false ? options.html : '';
  8486. if (options.bgPos) {
  8487. var bgPos = toPoint(options.bgPos);
  8488. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8489. }
  8490. this._setIconStyles(div, 'icon');
  8491. return div;
  8492. },
  8493. createShadow: function () {
  8494. return null;
  8495. }
  8496. });
  8497. // @factory L.divIcon(options: DivIcon options)
  8498. // Creates a `DivIcon` instance with the given options.
  8499. function divIcon(options) {
  8500. return new DivIcon(options);
  8501. }
  8502. Icon.Default = IconDefault;
  8503. /*
  8504. * @class GridLayer
  8505. * @inherits Layer
  8506. * @aka L.GridLayer
  8507. *
  8508. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8509. * 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.
  8510. *
  8511. *
  8512. * @section Synchronous usage
  8513. * @example
  8514. *
  8515. * 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.
  8516. *
  8517. * ```js
  8518. * var CanvasLayer = L.GridLayer.extend({
  8519. * createTile: function(coords){
  8520. * // create a <canvas> element for drawing
  8521. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8522. *
  8523. * // setup tile width and height according to the options
  8524. * var size = this.getTileSize();
  8525. * tile.width = size.x;
  8526. * tile.height = size.y;
  8527. *
  8528. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8529. * var ctx = tile.getContext('2d');
  8530. *
  8531. * // return the tile so it can be rendered on screen
  8532. * return tile;
  8533. * }
  8534. * });
  8535. * ```
  8536. *
  8537. * @section Asynchronous usage
  8538. * @example
  8539. *
  8540. * 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.
  8541. *
  8542. * ```js
  8543. * var CanvasLayer = L.GridLayer.extend({
  8544. * createTile: function(coords, done){
  8545. * var error;
  8546. *
  8547. * // create a <canvas> element for drawing
  8548. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8549. *
  8550. * // setup tile width and height according to the options
  8551. * var size = this.getTileSize();
  8552. * tile.width = size.x;
  8553. * tile.height = size.y;
  8554. *
  8555. * // draw something asynchronously and pass the tile to the done() callback
  8556. * setTimeout(function() {
  8557. * done(error, tile);
  8558. * }, 1000);
  8559. *
  8560. * return tile;
  8561. * }
  8562. * });
  8563. * ```
  8564. *
  8565. * @section
  8566. */
  8567. var GridLayer = Layer.extend({
  8568. // @section
  8569. // @aka GridLayer options
  8570. options: {
  8571. // @option tileSize: Number|Point = 256
  8572. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8573. tileSize: 256,
  8574. // @option opacity: Number = 1.0
  8575. // Opacity of the tiles. Can be used in the `createTile()` function.
  8576. opacity: 1,
  8577. // @option updateWhenIdle: Boolean = (depends)
  8578. // Load new tiles only when panning ends.
  8579. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8580. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8581. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8582. updateWhenIdle: mobile,
  8583. // @option updateWhenZooming: Boolean = true
  8584. // 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.
  8585. updateWhenZooming: true,
  8586. // @option updateInterval: Number = 200
  8587. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8588. updateInterval: 200,
  8589. // @option zIndex: Number = 1
  8590. // The explicit zIndex of the tile layer.
  8591. zIndex: 1,
  8592. // @option bounds: LatLngBounds = undefined
  8593. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8594. bounds: null,
  8595. // @option minZoom: Number = 0
  8596. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8597. minZoom: 0,
  8598. // @option maxZoom: Number = undefined
  8599. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8600. maxZoom: undefined,
  8601. // @option maxNativeZoom: Number = undefined
  8602. // Maximum zoom number the tile source has available. If it is specified,
  8603. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8604. // from `maxNativeZoom` level and auto-scaled.
  8605. maxNativeZoom: undefined,
  8606. // @option minNativeZoom: Number = undefined
  8607. // Minimum zoom number the tile source has available. If it is specified,
  8608. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8609. // from `minNativeZoom` level and auto-scaled.
  8610. minNativeZoom: undefined,
  8611. // @option noWrap: Boolean = false
  8612. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8613. // GridLayer will only be displayed once at low zoom levels. Has no
  8614. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8615. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8616. // tiles outside the CRS limits.
  8617. noWrap: false,
  8618. // @option pane: String = 'tilePane'
  8619. // `Map pane` where the grid layer will be added.
  8620. pane: 'tilePane',
  8621. // @option className: String = ''
  8622. // A custom class name to assign to the tile layer. Empty by default.
  8623. className: '',
  8624. // @option keepBuffer: Number = 2
  8625. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8626. keepBuffer: 2
  8627. },
  8628. initialize: function (options) {
  8629. setOptions(this, options);
  8630. },
  8631. onAdd: function () {
  8632. this._initContainer();
  8633. this._levels = {};
  8634. this._tiles = {};
  8635. this._resetView();
  8636. this._update();
  8637. },
  8638. beforeAdd: function (map) {
  8639. map._addZoomLimit(this);
  8640. },
  8641. onRemove: function (map) {
  8642. this._removeAllTiles();
  8643. remove(this._container);
  8644. map._removeZoomLimit(this);
  8645. this._container = null;
  8646. this._tileZoom = undefined;
  8647. },
  8648. // @method bringToFront: this
  8649. // Brings the tile layer to the top of all tile layers.
  8650. bringToFront: function () {
  8651. if (this._map) {
  8652. toFront(this._container);
  8653. this._setAutoZIndex(Math.max);
  8654. }
  8655. return this;
  8656. },
  8657. // @method bringToBack: this
  8658. // Brings the tile layer to the bottom of all tile layers.
  8659. bringToBack: function () {
  8660. if (this._map) {
  8661. toBack(this._container);
  8662. this._setAutoZIndex(Math.min);
  8663. }
  8664. return this;
  8665. },
  8666. // @method getContainer: HTMLElement
  8667. // Returns the HTML element that contains the tiles for this layer.
  8668. getContainer: function () {
  8669. return this._container;
  8670. },
  8671. // @method setOpacity(opacity: Number): this
  8672. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8673. setOpacity: function (opacity) {
  8674. this.options.opacity = opacity;
  8675. this._updateOpacity();
  8676. return this;
  8677. },
  8678. // @method setZIndex(zIndex: Number): this
  8679. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8680. setZIndex: function (zIndex) {
  8681. this.options.zIndex = zIndex;
  8682. this._updateZIndex();
  8683. return this;
  8684. },
  8685. // @method isLoading: Boolean
  8686. // Returns `true` if any tile in the grid layer has not finished loading.
  8687. isLoading: function () {
  8688. return this._loading;
  8689. },
  8690. // @method redraw: this
  8691. // Causes the layer to clear all the tiles and request them again.
  8692. redraw: function () {
  8693. if (this._map) {
  8694. this._removeAllTiles();
  8695. this._update();
  8696. }
  8697. return this;
  8698. },
  8699. getEvents: function () {
  8700. var events = {
  8701. viewprereset: this._invalidateAll,
  8702. viewreset: this._resetView,
  8703. zoom: this._resetView,
  8704. moveend: this._onMoveEnd
  8705. };
  8706. if (!this.options.updateWhenIdle) {
  8707. // update tiles on move, but not more often than once per given interval
  8708. if (!this._onMove) {
  8709. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8710. }
  8711. events.move = this._onMove;
  8712. }
  8713. if (this._zoomAnimated) {
  8714. events.zoomanim = this._animateZoom;
  8715. }
  8716. return events;
  8717. },
  8718. // @section Extension methods
  8719. // Layers extending `GridLayer` shall reimplement the following method.
  8720. // @method createTile(coords: Object, done?: Function): HTMLElement
  8721. // Called only internally, must be overridden by classes extending `GridLayer`.
  8722. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8723. // is specified, it must be called when the tile has finished loading and drawing.
  8724. createTile: function () {
  8725. return document.createElement('div');
  8726. },
  8727. // @section
  8728. // @method getTileSize: Point
  8729. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8730. getTileSize: function () {
  8731. var s = this.options.tileSize;
  8732. return s instanceof Point ? s : new Point(s, s);
  8733. },
  8734. _updateZIndex: function () {
  8735. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8736. this._container.style.zIndex = this.options.zIndex;
  8737. }
  8738. },
  8739. _setAutoZIndex: function (compare) {
  8740. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8741. var layers = this.getPane().children,
  8742. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8743. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8744. zIndex = layers[i].style.zIndex;
  8745. if (layers[i] !== this._container && zIndex) {
  8746. edgeZIndex = compare(edgeZIndex, +zIndex);
  8747. }
  8748. }
  8749. if (isFinite(edgeZIndex)) {
  8750. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8751. this._updateZIndex();
  8752. }
  8753. },
  8754. _updateOpacity: function () {
  8755. if (!this._map) { return; }
  8756. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8757. if (ielt9) { return; }
  8758. setOpacity(this._container, this.options.opacity);
  8759. var now = +new Date(),
  8760. nextFrame = false,
  8761. willPrune = false;
  8762. for (var key in this._tiles) {
  8763. var tile = this._tiles[key];
  8764. if (!tile.current || !tile.loaded) { continue; }
  8765. var fade = Math.min(1, (now - tile.loaded) / 200);
  8766. setOpacity(tile.el, fade);
  8767. if (fade < 1) {
  8768. nextFrame = true;
  8769. } else {
  8770. if (tile.active) {
  8771. willPrune = true;
  8772. } else {
  8773. this._onOpaqueTile(tile);
  8774. }
  8775. tile.active = true;
  8776. }
  8777. }
  8778. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8779. if (nextFrame) {
  8780. cancelAnimFrame(this._fadeFrame);
  8781. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8782. }
  8783. },
  8784. _onOpaqueTile: falseFn,
  8785. _initContainer: function () {
  8786. if (this._container) { return; }
  8787. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8788. this._updateZIndex();
  8789. if (this.options.opacity < 1) {
  8790. this._updateOpacity();
  8791. }
  8792. this.getPane().appendChild(this._container);
  8793. },
  8794. _updateLevels: function () {
  8795. var zoom = this._tileZoom,
  8796. maxZoom = this.options.maxZoom;
  8797. if (zoom === undefined) { return undefined; }
  8798. for (var z in this._levels) {
  8799. if (this._levels[z].el.children.length || z === zoom) {
  8800. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8801. this._onUpdateLevel(z);
  8802. } else {
  8803. remove(this._levels[z].el);
  8804. this._removeTilesAtZoom(z);
  8805. this._onRemoveLevel(z);
  8806. delete this._levels[z];
  8807. }
  8808. }
  8809. var level = this._levels[zoom],
  8810. map = this._map;
  8811. if (!level) {
  8812. level = this._levels[zoom] = {};
  8813. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8814. level.el.style.zIndex = maxZoom;
  8815. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8816. level.zoom = zoom;
  8817. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8818. // force the browser to consider the newly added element for transition
  8819. falseFn(level.el.offsetWidth);
  8820. this._onCreateLevel(level);
  8821. }
  8822. this._level = level;
  8823. return level;
  8824. },
  8825. _onUpdateLevel: falseFn,
  8826. _onRemoveLevel: falseFn,
  8827. _onCreateLevel: falseFn,
  8828. _pruneTiles: function () {
  8829. if (!this._map) {
  8830. return;
  8831. }
  8832. var key, tile;
  8833. var zoom = this._map.getZoom();
  8834. if (zoom > this.options.maxZoom ||
  8835. zoom < this.options.minZoom) {
  8836. this._removeAllTiles();
  8837. return;
  8838. }
  8839. for (key in this._tiles) {
  8840. tile = this._tiles[key];
  8841. tile.retain = tile.current;
  8842. }
  8843. for (key in this._tiles) {
  8844. tile = this._tiles[key];
  8845. if (tile.current && !tile.active) {
  8846. var coords = tile.coords;
  8847. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  8848. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  8849. }
  8850. }
  8851. }
  8852. for (key in this._tiles) {
  8853. if (!this._tiles[key].retain) {
  8854. this._removeTile(key);
  8855. }
  8856. }
  8857. },
  8858. _removeTilesAtZoom: function (zoom) {
  8859. for (var key in this._tiles) {
  8860. if (this._tiles[key].coords.z !== zoom) {
  8861. continue;
  8862. }
  8863. this._removeTile(key);
  8864. }
  8865. },
  8866. _removeAllTiles: function () {
  8867. for (var key in this._tiles) {
  8868. this._removeTile(key);
  8869. }
  8870. },
  8871. _invalidateAll: function () {
  8872. for (var z in this._levels) {
  8873. remove(this._levels[z].el);
  8874. this._onRemoveLevel(z);
  8875. delete this._levels[z];
  8876. }
  8877. this._removeAllTiles();
  8878. this._tileZoom = undefined;
  8879. },
  8880. _retainParent: function (x, y, z, minZoom) {
  8881. var x2 = Math.floor(x / 2),
  8882. y2 = Math.floor(y / 2),
  8883. z2 = z - 1,
  8884. coords2 = new Point(+x2, +y2);
  8885. coords2.z = +z2;
  8886. var key = this._tileCoordsToKey(coords2),
  8887. tile = this._tiles[key];
  8888. if (tile && tile.active) {
  8889. tile.retain = true;
  8890. return true;
  8891. } else if (tile && tile.loaded) {
  8892. tile.retain = true;
  8893. }
  8894. if (z2 > minZoom) {
  8895. return this._retainParent(x2, y2, z2, minZoom);
  8896. }
  8897. return false;
  8898. },
  8899. _retainChildren: function (x, y, z, maxZoom) {
  8900. for (var i = 2 * x; i < 2 * x + 2; i++) {
  8901. for (var j = 2 * y; j < 2 * y + 2; j++) {
  8902. var coords = new Point(i, j);
  8903. coords.z = z + 1;
  8904. var key = this._tileCoordsToKey(coords),
  8905. tile = this._tiles[key];
  8906. if (tile && tile.active) {
  8907. tile.retain = true;
  8908. continue;
  8909. } else if (tile && tile.loaded) {
  8910. tile.retain = true;
  8911. }
  8912. if (z + 1 < maxZoom) {
  8913. this._retainChildren(i, j, z + 1, maxZoom);
  8914. }
  8915. }
  8916. }
  8917. },
  8918. _resetView: function (e) {
  8919. var animating = e && (e.pinch || e.flyTo);
  8920. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  8921. },
  8922. _animateZoom: function (e) {
  8923. this._setView(e.center, e.zoom, true, e.noUpdate);
  8924. },
  8925. _clampZoom: function (zoom) {
  8926. var options = this.options;
  8927. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  8928. return options.minNativeZoom;
  8929. }
  8930. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  8931. return options.maxNativeZoom;
  8932. }
  8933. return zoom;
  8934. },
  8935. _setView: function (center, zoom, noPrune, noUpdate) {
  8936. var tileZoom = this._clampZoom(Math.round(zoom));
  8937. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  8938. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  8939. tileZoom = undefined;
  8940. }
  8941. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  8942. if (!noUpdate || tileZoomChanged) {
  8943. this._tileZoom = tileZoom;
  8944. if (this._abortLoading) {
  8945. this._abortLoading();
  8946. }
  8947. this._updateLevels();
  8948. this._resetGrid();
  8949. if (tileZoom !== undefined) {
  8950. this._update(center);
  8951. }
  8952. if (!noPrune) {
  8953. this._pruneTiles();
  8954. }
  8955. // Flag to prevent _updateOpacity from pruning tiles during
  8956. // a zoom anim or a pinch gesture
  8957. this._noPrune = !!noPrune;
  8958. }
  8959. this._setZoomTransforms(center, zoom);
  8960. },
  8961. _setZoomTransforms: function (center, zoom) {
  8962. for (var i in this._levels) {
  8963. this._setZoomTransform(this._levels[i], center, zoom);
  8964. }
  8965. },
  8966. _setZoomTransform: function (level, center, zoom) {
  8967. var scale = this._map.getZoomScale(zoom, level.zoom),
  8968. translate = level.origin.multiplyBy(scale)
  8969. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  8970. if (any3d) {
  8971. setTransform(level.el, translate, scale);
  8972. } else {
  8973. setPosition(level.el, translate);
  8974. }
  8975. },
  8976. _resetGrid: function () {
  8977. var map = this._map,
  8978. crs = map.options.crs,
  8979. tileSize = this._tileSize = this.getTileSize(),
  8980. tileZoom = this._tileZoom;
  8981. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  8982. if (bounds) {
  8983. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  8984. }
  8985. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  8986. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  8987. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  8988. ];
  8989. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  8990. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  8991. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  8992. ];
  8993. },
  8994. _onMoveEnd: function () {
  8995. if (!this._map || this._map._animatingZoom) { return; }
  8996. this._update();
  8997. },
  8998. _getTiledPixelBounds: function (center) {
  8999. var map = this._map,
  9000. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9001. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9002. pixelCenter = map.project(center, this._tileZoom).floor(),
  9003. halfSize = map.getSize().divideBy(scale * 2);
  9004. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9005. },
  9006. // Private method to load tiles in the grid's active zoom level according to map bounds
  9007. _update: function (center) {
  9008. var map = this._map;
  9009. if (!map) { return; }
  9010. var zoom = this._clampZoom(map.getZoom());
  9011. if (center === undefined) { center = map.getCenter(); }
  9012. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9013. var pixelBounds = this._getTiledPixelBounds(center),
  9014. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9015. tileCenter = tileRange.getCenter(),
  9016. queue = [],
  9017. margin = this.options.keepBuffer,
  9018. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9019. tileRange.getTopRight().add([margin, -margin]));
  9020. // Sanity check: panic if the tile range contains Infinity somewhere.
  9021. if (!(isFinite(tileRange.min.x) &&
  9022. isFinite(tileRange.min.y) &&
  9023. isFinite(tileRange.max.x) &&
  9024. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9025. for (var key in this._tiles) {
  9026. var c = this._tiles[key].coords;
  9027. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9028. this._tiles[key].current = false;
  9029. }
  9030. }
  9031. // _update just loads more tiles. If the tile zoom level differs too much
  9032. // from the map's, let _setView reset levels and prune old tiles.
  9033. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9034. // create a queue of coordinates to load tiles from
  9035. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9036. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9037. var coords = new Point(i, j);
  9038. coords.z = this._tileZoom;
  9039. if (!this._isValidTile(coords)) { continue; }
  9040. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9041. if (tile) {
  9042. tile.current = true;
  9043. } else {
  9044. queue.push(coords);
  9045. }
  9046. }
  9047. }
  9048. // sort tile queue to load tiles in order of their distance to center
  9049. queue.sort(function (a, b) {
  9050. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9051. });
  9052. if (queue.length !== 0) {
  9053. // if it's the first batch of tiles to load
  9054. if (!this._loading) {
  9055. this._loading = true;
  9056. // @event loading: Event
  9057. // Fired when the grid layer starts loading tiles.
  9058. this.fire('loading');
  9059. }
  9060. // create DOM fragment to append tiles in one batch
  9061. var fragment = document.createDocumentFragment();
  9062. for (i = 0; i < queue.length; i++) {
  9063. this._addTile(queue[i], fragment);
  9064. }
  9065. this._level.el.appendChild(fragment);
  9066. }
  9067. },
  9068. _isValidTile: function (coords) {
  9069. var crs = this._map.options.crs;
  9070. if (!crs.infinite) {
  9071. // don't load tile if it's out of bounds and not wrapped
  9072. var bounds = this._globalTileRange;
  9073. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9074. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9075. }
  9076. if (!this.options.bounds) { return true; }
  9077. // don't load tile if it doesn't intersect the bounds in options
  9078. var tileBounds = this._tileCoordsToBounds(coords);
  9079. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9080. },
  9081. _keyToBounds: function (key) {
  9082. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9083. },
  9084. _tileCoordsToNwSe: function (coords) {
  9085. var map = this._map,
  9086. tileSize = this.getTileSize(),
  9087. nwPoint = coords.scaleBy(tileSize),
  9088. sePoint = nwPoint.add(tileSize),
  9089. nw = map.unproject(nwPoint, coords.z),
  9090. se = map.unproject(sePoint, coords.z);
  9091. return [nw, se];
  9092. },
  9093. // converts tile coordinates to its geographical bounds
  9094. _tileCoordsToBounds: function (coords) {
  9095. var bp = this._tileCoordsToNwSe(coords),
  9096. bounds = new LatLngBounds(bp[0], bp[1]);
  9097. if (!this.options.noWrap) {
  9098. bounds = this._map.wrapLatLngBounds(bounds);
  9099. }
  9100. return bounds;
  9101. },
  9102. // converts tile coordinates to key for the tile cache
  9103. _tileCoordsToKey: function (coords) {
  9104. return coords.x + ':' + coords.y + ':' + coords.z;
  9105. },
  9106. // converts tile cache key to coordinates
  9107. _keyToTileCoords: function (key) {
  9108. var k = key.split(':'),
  9109. coords = new Point(+k[0], +k[1]);
  9110. coords.z = +k[2];
  9111. return coords;
  9112. },
  9113. _removeTile: function (key) {
  9114. var tile = this._tiles[key];
  9115. if (!tile) { return; }
  9116. // Cancels any pending http requests associated with the tile
  9117. // unless we're on Android's stock browser,
  9118. // see https://github.com/Leaflet/Leaflet/issues/137
  9119. if (!androidStock) {
  9120. tile.el.setAttribute('src', emptyImageUrl);
  9121. }
  9122. remove(tile.el);
  9123. delete this._tiles[key];
  9124. // @event tileunload: TileEvent
  9125. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9126. this.fire('tileunload', {
  9127. tile: tile.el,
  9128. coords: this._keyToTileCoords(key)
  9129. });
  9130. },
  9131. _initTile: function (tile) {
  9132. addClass(tile, 'leaflet-tile');
  9133. var tileSize = this.getTileSize();
  9134. tile.style.width = tileSize.x + 'px';
  9135. tile.style.height = tileSize.y + 'px';
  9136. tile.onselectstart = falseFn;
  9137. tile.onmousemove = falseFn;
  9138. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9139. if (ielt9 && this.options.opacity < 1) {
  9140. setOpacity(tile, this.options.opacity);
  9141. }
  9142. // without this hack, tiles disappear after zoom on Chrome for Android
  9143. // https://github.com/Leaflet/Leaflet/issues/2078
  9144. if (android && !android23) {
  9145. tile.style.WebkitBackfaceVisibility = 'hidden';
  9146. }
  9147. },
  9148. _addTile: function (coords, container) {
  9149. var tilePos = this._getTilePos(coords),
  9150. key = this._tileCoordsToKey(coords);
  9151. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9152. this._initTile(tile);
  9153. // if createTile is defined with a second argument ("done" callback),
  9154. // we know that tile is async and will be ready later; otherwise
  9155. if (this.createTile.length < 2) {
  9156. // mark tile as ready, but delay one frame for opacity animation to happen
  9157. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9158. }
  9159. setPosition(tile, tilePos);
  9160. // save tile in cache
  9161. this._tiles[key] = {
  9162. el: tile,
  9163. coords: coords,
  9164. current: true
  9165. };
  9166. container.appendChild(tile);
  9167. // @event tileloadstart: TileEvent
  9168. // Fired when a tile is requested and starts loading.
  9169. this.fire('tileloadstart', {
  9170. tile: tile,
  9171. coords: coords
  9172. });
  9173. },
  9174. _tileReady: function (coords, err, tile) {
  9175. if (!this._map) { return; }
  9176. if (err) {
  9177. // @event tileerror: TileErrorEvent
  9178. // Fired when there is an error loading a tile.
  9179. this.fire('tileerror', {
  9180. error: err,
  9181. tile: tile,
  9182. coords: coords
  9183. });
  9184. }
  9185. var key = this._tileCoordsToKey(coords);
  9186. tile = this._tiles[key];
  9187. if (!tile) { return; }
  9188. tile.loaded = +new Date();
  9189. if (this._map._fadeAnimated) {
  9190. setOpacity(tile.el, 0);
  9191. cancelAnimFrame(this._fadeFrame);
  9192. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9193. } else {
  9194. tile.active = true;
  9195. this._pruneTiles();
  9196. }
  9197. if (!err) {
  9198. addClass(tile.el, 'leaflet-tile-loaded');
  9199. // @event tileload: TileEvent
  9200. // Fired when a tile loads.
  9201. this.fire('tileload', {
  9202. tile: tile.el,
  9203. coords: coords
  9204. });
  9205. }
  9206. if (this._noTilesToLoad()) {
  9207. this._loading = false;
  9208. // @event load: Event
  9209. // Fired when the grid layer loaded all visible tiles.
  9210. this.fire('load');
  9211. if (ielt9 || !this._map._fadeAnimated) {
  9212. requestAnimFrame(this._pruneTiles, this);
  9213. } else {
  9214. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9215. // to trigger a pruning.
  9216. setTimeout(bind(this._pruneTiles, this), 250);
  9217. }
  9218. }
  9219. },
  9220. _getTilePos: function (coords) {
  9221. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9222. },
  9223. _wrapCoords: function (coords) {
  9224. var newCoords = new Point(
  9225. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9226. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9227. newCoords.z = coords.z;
  9228. return newCoords;
  9229. },
  9230. _pxBoundsToTileRange: function (bounds) {
  9231. var tileSize = this.getTileSize();
  9232. return new Bounds(
  9233. bounds.min.unscaleBy(tileSize).floor(),
  9234. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9235. },
  9236. _noTilesToLoad: function () {
  9237. for (var key in this._tiles) {
  9238. if (!this._tiles[key].loaded) { return false; }
  9239. }
  9240. return true;
  9241. }
  9242. });
  9243. // @factory L.gridLayer(options?: GridLayer options)
  9244. // Creates a new instance of GridLayer with the supplied options.
  9245. function gridLayer(options) {
  9246. return new GridLayer(options);
  9247. }
  9248. /*
  9249. * @class TileLayer
  9250. * @inherits GridLayer
  9251. * @aka L.TileLayer
  9252. * Used to load and display tile layers on the map. Extends `GridLayer`.
  9253. *
  9254. * @example
  9255. *
  9256. * ```js
  9257. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  9258. * ```
  9259. *
  9260. * @section URL template
  9261. * @example
  9262. *
  9263. * A string of the following form:
  9264. *
  9265. * ```
  9266. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9267. * ```
  9268. *
  9269. * `{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.
  9270. *
  9271. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9272. *
  9273. * ```
  9274. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9275. * ```
  9276. */
  9277. var TileLayer = GridLayer.extend({
  9278. // @section
  9279. // @aka TileLayer options
  9280. options: {
  9281. // @option minZoom: Number = 0
  9282. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9283. minZoom: 0,
  9284. // @option maxZoom: Number = 18
  9285. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9286. maxZoom: 18,
  9287. // @option subdomains: String|String[] = 'abc'
  9288. // 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.
  9289. subdomains: 'abc',
  9290. // @option errorTileUrl: String = ''
  9291. // URL to the tile image to show in place of the tile that failed to load.
  9292. errorTileUrl: '',
  9293. // @option zoomOffset: Number = 0
  9294. // The zoom number used in tile URLs will be offset with this value.
  9295. zoomOffset: 0,
  9296. // @option tms: Boolean = false
  9297. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9298. tms: false,
  9299. // @option zoomReverse: Boolean = false
  9300. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9301. zoomReverse: false,
  9302. // @option detectRetina: Boolean = false
  9303. // 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.
  9304. detectRetina: false,
  9305. // @option crossOrigin: Boolean = false
  9306. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  9307. crossOrigin: false
  9308. },
  9309. initialize: function (url, options) {
  9310. this._url = url;
  9311. options = setOptions(this, options);
  9312. // detecting retina displays, adjusting tileSize and zoom levels
  9313. if (options.detectRetina && retina && options.maxZoom > 0) {
  9314. options.tileSize = Math.floor(options.tileSize / 2);
  9315. if (!options.zoomReverse) {
  9316. options.zoomOffset++;
  9317. options.maxZoom--;
  9318. } else {
  9319. options.zoomOffset--;
  9320. options.minZoom++;
  9321. }
  9322. options.minZoom = Math.max(0, options.minZoom);
  9323. }
  9324. if (typeof options.subdomains === 'string') {
  9325. options.subdomains = options.subdomains.split('');
  9326. }
  9327. // for https://github.com/Leaflet/Leaflet/issues/137
  9328. if (!android) {
  9329. this.on('tileunload', this._onTileRemove);
  9330. }
  9331. },
  9332. // @method setUrl(url: String, noRedraw?: Boolean): this
  9333. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9334. setUrl: function (url, noRedraw) {
  9335. this._url = url;
  9336. if (!noRedraw) {
  9337. this.redraw();
  9338. }
  9339. return this;
  9340. },
  9341. // @method createTile(coords: Object, done?: Function): HTMLElement
  9342. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9343. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9344. // callback is called when the tile has been loaded.
  9345. createTile: function (coords, done) {
  9346. var tile = document.createElement('img');
  9347. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9348. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9349. if (this.options.crossOrigin) {
  9350. tile.crossOrigin = '';
  9351. }
  9352. /*
  9353. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9354. http://www.w3.org/TR/WCAG20-TECHS/H67
  9355. */
  9356. tile.alt = '';
  9357. /*
  9358. Set role="presentation" to force screen readers to ignore this
  9359. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9360. */
  9361. tile.setAttribute('role', 'presentation');
  9362. tile.src = this.getTileUrl(coords);
  9363. return tile;
  9364. },
  9365. // @section Extension methods
  9366. // @uninheritable
  9367. // Layers extending `TileLayer` might reimplement the following method.
  9368. // @method getTileUrl(coords: Object): String
  9369. // Called only internally, returns the URL for a tile given its coordinates.
  9370. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9371. getTileUrl: function (coords) {
  9372. var data = {
  9373. r: retina ? '@2x' : '',
  9374. s: this._getSubdomain(coords),
  9375. x: coords.x,
  9376. y: coords.y,
  9377. z: this._getZoomForUrl()
  9378. };
  9379. if (this._map && !this._map.options.crs.infinite) {
  9380. var invertedY = this._globalTileRange.max.y - coords.y;
  9381. if (this.options.tms) {
  9382. data['y'] = invertedY;
  9383. }
  9384. data['-y'] = invertedY;
  9385. }
  9386. return template(this._url, extend(data, this.options));
  9387. },
  9388. _tileOnLoad: function (done, tile) {
  9389. // For https://github.com/Leaflet/Leaflet/issues/3332
  9390. if (ielt9) {
  9391. setTimeout(bind(done, this, null, tile), 0);
  9392. } else {
  9393. done(null, tile);
  9394. }
  9395. },
  9396. _tileOnError: function (done, tile, e) {
  9397. var errorUrl = this.options.errorTileUrl;
  9398. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9399. tile.src = errorUrl;
  9400. }
  9401. done(e, tile);
  9402. },
  9403. _onTileRemove: function (e) {
  9404. e.tile.onload = null;
  9405. },
  9406. _getZoomForUrl: function () {
  9407. var zoom = this._tileZoom,
  9408. maxZoom = this.options.maxZoom,
  9409. zoomReverse = this.options.zoomReverse,
  9410. zoomOffset = this.options.zoomOffset;
  9411. if (zoomReverse) {
  9412. zoom = maxZoom - zoom;
  9413. }
  9414. return zoom + zoomOffset;
  9415. },
  9416. _getSubdomain: function (tilePoint) {
  9417. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9418. return this.options.subdomains[index];
  9419. },
  9420. // stops loading all tiles in the background layer
  9421. _abortLoading: function () {
  9422. var i, tile;
  9423. for (i in this._tiles) {
  9424. if (this._tiles[i].coords.z !== this._tileZoom) {
  9425. tile = this._tiles[i].el;
  9426. tile.onload = falseFn;
  9427. tile.onerror = falseFn;
  9428. if (!tile.complete) {
  9429. tile.src = emptyImageUrl;
  9430. remove(tile);
  9431. delete this._tiles[i];
  9432. }
  9433. }
  9434. }
  9435. }
  9436. });
  9437. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9438. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9439. function tileLayer(url, options) {
  9440. return new TileLayer(url, options);
  9441. }
  9442. /*
  9443. * @class TileLayer.WMS
  9444. * @inherits TileLayer
  9445. * @aka L.TileLayer.WMS
  9446. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9447. *
  9448. * @example
  9449. *
  9450. * ```js
  9451. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9452. * layers: 'nexrad-n0r-900913',
  9453. * format: 'image/png',
  9454. * transparent: true,
  9455. * attribution: "Weather data © 2012 IEM Nexrad"
  9456. * });
  9457. * ```
  9458. */
  9459. var TileLayerWMS = TileLayer.extend({
  9460. // @section
  9461. // @aka TileLayer.WMS options
  9462. // If any custom options not documented here are used, they will be sent to the
  9463. // WMS server as extra parameters in each request URL. This can be useful for
  9464. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9465. defaultWmsParams: {
  9466. service: 'WMS',
  9467. request: 'GetMap',
  9468. // @option layers: String = ''
  9469. // **(required)** Comma-separated list of WMS layers to show.
  9470. layers: '',
  9471. // @option styles: String = ''
  9472. // Comma-separated list of WMS styles.
  9473. styles: '',
  9474. // @option format: String = 'image/jpeg'
  9475. // WMS image format (use `'image/png'` for layers with transparency).
  9476. format: 'image/jpeg',
  9477. // @option transparent: Boolean = false
  9478. // If `true`, the WMS service will return images with transparency.
  9479. transparent: false,
  9480. // @option version: String = '1.1.1'
  9481. // Version of the WMS service to use
  9482. version: '1.1.1'
  9483. },
  9484. options: {
  9485. // @option crs: CRS = null
  9486. // Coordinate Reference System to use for the WMS requests, defaults to
  9487. // map CRS. Don't change this if you're not sure what it means.
  9488. crs: null,
  9489. // @option uppercase: Boolean = false
  9490. // If `true`, WMS request parameter keys will be uppercase.
  9491. uppercase: false
  9492. },
  9493. initialize: function (url, options) {
  9494. this._url = url;
  9495. var wmsParams = extend({}, this.defaultWmsParams);
  9496. // all keys that are not TileLayer options go to WMS params
  9497. for (var i in options) {
  9498. if (!(i in this.options)) {
  9499. wmsParams[i] = options[i];
  9500. }
  9501. }
  9502. options = setOptions(this, options);
  9503. var realRetina = options.detectRetina && retina ? 2 : 1;
  9504. var tileSize = this.getTileSize();
  9505. wmsParams.width = tileSize.x * realRetina;
  9506. wmsParams.height = tileSize.y * realRetina;
  9507. this.wmsParams = wmsParams;
  9508. },
  9509. onAdd: function (map) {
  9510. this._crs = this.options.crs || map.options.crs;
  9511. this._wmsVersion = parseFloat(this.wmsParams.version);
  9512. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9513. this.wmsParams[projectionKey] = this._crs.code;
  9514. TileLayer.prototype.onAdd.call(this, map);
  9515. },
  9516. getTileUrl: function (coords) {
  9517. var tileBounds = this._tileCoordsToNwSe(coords),
  9518. crs = this._crs,
  9519. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9520. min = bounds.min,
  9521. max = bounds.max,
  9522. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9523. [min.y, min.x, max.y, max.x] :
  9524. [min.x, min.y, max.x, max.y]).join(','),
  9525. url = L.TileLayer.prototype.getTileUrl.call(this, coords);
  9526. return url +
  9527. getParamString(this.wmsParams, url, this.options.uppercase) +
  9528. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9529. },
  9530. // @method setParams(params: Object, noRedraw?: Boolean): this
  9531. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9532. setParams: function (params, noRedraw) {
  9533. extend(this.wmsParams, params);
  9534. if (!noRedraw) {
  9535. this.redraw();
  9536. }
  9537. return this;
  9538. }
  9539. });
  9540. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9541. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9542. function tileLayerWMS(url, options) {
  9543. return new TileLayerWMS(url, options);
  9544. }
  9545. TileLayer.WMS = TileLayerWMS;
  9546. tileLayer.wms = tileLayerWMS;
  9547. /*
  9548. * @class Renderer
  9549. * @inherits Layer
  9550. * @aka L.Renderer
  9551. *
  9552. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9553. * DOM container of the renderer, its bounds, and its zoom animation.
  9554. *
  9555. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9556. * itself can be added or removed to the map. All paths use a renderer, which can
  9557. * be implicit (the map will decide the type of renderer and use it automatically)
  9558. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9559. *
  9560. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9561. *
  9562. * @event update: Event
  9563. * Fired when the renderer updates its bounds, center and zoom, for example when
  9564. * its map has moved
  9565. */
  9566. var Renderer = Layer.extend({
  9567. // @section
  9568. // @aka Renderer options
  9569. options: {
  9570. // @option padding: Number = 0.1
  9571. // How much to extend the clip area around the map view (relative to its size)
  9572. // e.g. 0.1 would be 10% of map view in each direction
  9573. padding: 0.1,
  9574. // @option tolerance: Number = 0
  9575. // How much to extend click tolerance round a path/object on the map
  9576. tolerance : 0
  9577. },
  9578. initialize: function (options) {
  9579. setOptions(this, options);
  9580. stamp(this);
  9581. this._layers = this._layers || {};
  9582. },
  9583. onAdd: function () {
  9584. if (!this._container) {
  9585. this._initContainer(); // defined by renderer implementations
  9586. if (this._zoomAnimated) {
  9587. addClass(this._container, 'leaflet-zoom-animated');
  9588. }
  9589. }
  9590. this.getPane().appendChild(this._container);
  9591. this._update();
  9592. this.on('update', this._updatePaths, this);
  9593. },
  9594. onRemove: function () {
  9595. this.off('update', this._updatePaths, this);
  9596. this._destroyContainer();
  9597. },
  9598. getEvents: function () {
  9599. var events = {
  9600. viewreset: this._reset,
  9601. zoom: this._onZoom,
  9602. moveend: this._update,
  9603. zoomend: this._onZoomEnd
  9604. };
  9605. if (this._zoomAnimated) {
  9606. events.zoomanim = this._onAnimZoom;
  9607. }
  9608. return events;
  9609. },
  9610. _onAnimZoom: function (ev) {
  9611. this._updateTransform(ev.center, ev.zoom);
  9612. },
  9613. _onZoom: function () {
  9614. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9615. },
  9616. _updateTransform: function (center, zoom) {
  9617. var scale = this._map.getZoomScale(zoom, this._zoom),
  9618. position = getPosition(this._container),
  9619. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9620. currentCenterPoint = this._map.project(this._center, zoom),
  9621. destCenterPoint = this._map.project(center, zoom),
  9622. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9623. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9624. if (any3d) {
  9625. setTransform(this._container, topLeftOffset, scale);
  9626. } else {
  9627. setPosition(this._container, topLeftOffset);
  9628. }
  9629. },
  9630. _reset: function () {
  9631. this._update();
  9632. this._updateTransform(this._center, this._zoom);
  9633. for (var id in this._layers) {
  9634. this._layers[id]._reset();
  9635. }
  9636. },
  9637. _onZoomEnd: function () {
  9638. for (var id in this._layers) {
  9639. this._layers[id]._project();
  9640. }
  9641. },
  9642. _updatePaths: function () {
  9643. for (var id in this._layers) {
  9644. this._layers[id]._update();
  9645. }
  9646. },
  9647. _update: function () {
  9648. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9649. // Subclasses are responsible of firing the 'update' event.
  9650. var p = this.options.padding,
  9651. size = this._map.getSize(),
  9652. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9653. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9654. this._center = this._map.getCenter();
  9655. this._zoom = this._map.getZoom();
  9656. }
  9657. });
  9658. /*
  9659. * @class Canvas
  9660. * @inherits Renderer
  9661. * @aka L.Canvas
  9662. *
  9663. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9664. * Inherits `Renderer`.
  9665. *
  9666. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9667. * available in all web browsers, notably IE8, and overlapping geometries might
  9668. * not display properly in some edge cases.
  9669. *
  9670. * @example
  9671. *
  9672. * Use Canvas by default for all paths in the map:
  9673. *
  9674. * ```js
  9675. * var map = L.map('map', {
  9676. * renderer: L.canvas()
  9677. * });
  9678. * ```
  9679. *
  9680. * Use a Canvas renderer with extra padding for specific vector geometries:
  9681. *
  9682. * ```js
  9683. * var map = L.map('map');
  9684. * var myRenderer = L.canvas({ padding: 0.5 });
  9685. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9686. * var circle = L.circle( center, { renderer: myRenderer } );
  9687. * ```
  9688. */
  9689. var Canvas = Renderer.extend({
  9690. getEvents: function () {
  9691. var events = Renderer.prototype.getEvents.call(this);
  9692. events.viewprereset = this._onViewPreReset;
  9693. return events;
  9694. },
  9695. _onViewPreReset: function () {
  9696. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9697. this._postponeUpdatePaths = true;
  9698. },
  9699. onAdd: function () {
  9700. Renderer.prototype.onAdd.call(this);
  9701. // Redraw vectors since canvas is cleared upon removal,
  9702. // in case of removing the renderer itself from the map.
  9703. this._draw();
  9704. },
  9705. _initContainer: function () {
  9706. var container = this._container = document.createElement('canvas');
  9707. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9708. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9709. on(container, 'mouseout', this._handleMouseOut, this);
  9710. this._ctx = container.getContext('2d');
  9711. },
  9712. _destroyContainer: function () {
  9713. delete this._ctx;
  9714. remove(this._container);
  9715. off(this._container);
  9716. delete this._container;
  9717. },
  9718. _updatePaths: function () {
  9719. if (this._postponeUpdatePaths) { return; }
  9720. var layer;
  9721. this._redrawBounds = null;
  9722. for (var id in this._layers) {
  9723. layer = this._layers[id];
  9724. layer._update();
  9725. }
  9726. this._redraw();
  9727. },
  9728. _update: function () {
  9729. if (this._map._animatingZoom && this._bounds) { return; }
  9730. this._drawnLayers = {};
  9731. Renderer.prototype._update.call(this);
  9732. var b = this._bounds,
  9733. container = this._container,
  9734. size = b.getSize(),
  9735. m = retina ? 2 : 1;
  9736. setPosition(container, b.min);
  9737. // set canvas size (also clearing it); use double size on retina
  9738. container.width = m * size.x;
  9739. container.height = m * size.y;
  9740. container.style.width = size.x + 'px';
  9741. container.style.height = size.y + 'px';
  9742. if (retina) {
  9743. this._ctx.scale(2, 2);
  9744. }
  9745. // translate so we use the same path coordinates after canvas element moves
  9746. this._ctx.translate(-b.min.x, -b.min.y);
  9747. // Tell paths to redraw themselves
  9748. this.fire('update');
  9749. },
  9750. _reset: function () {
  9751. Renderer.prototype._reset.call(this);
  9752. if (this._postponeUpdatePaths) {
  9753. this._postponeUpdatePaths = false;
  9754. this._updatePaths();
  9755. }
  9756. },
  9757. _initPath: function (layer) {
  9758. this._updateDashArray(layer);
  9759. this._layers[stamp(layer)] = layer;
  9760. var order = layer._order = {
  9761. layer: layer,
  9762. prev: this._drawLast,
  9763. next: null
  9764. };
  9765. if (this._drawLast) { this._drawLast.next = order; }
  9766. this._drawLast = order;
  9767. this._drawFirst = this._drawFirst || this._drawLast;
  9768. },
  9769. _addPath: function (layer) {
  9770. this._requestRedraw(layer);
  9771. },
  9772. _removePath: function (layer) {
  9773. var order = layer._order;
  9774. var next = order.next;
  9775. var prev = order.prev;
  9776. if (next) {
  9777. next.prev = prev;
  9778. } else {
  9779. this._drawLast = prev;
  9780. }
  9781. if (prev) {
  9782. prev.next = next;
  9783. } else {
  9784. this._drawFirst = next;
  9785. }
  9786. delete layer._order;
  9787. delete this._layers[L.stamp(layer)];
  9788. this._requestRedraw(layer);
  9789. },
  9790. _updatePath: function (layer) {
  9791. // Redraw the union of the layer's old pixel
  9792. // bounds and the new pixel bounds.
  9793. this._extendRedrawBounds(layer);
  9794. layer._project();
  9795. layer._update();
  9796. // The redraw will extend the redraw bounds
  9797. // with the new pixel bounds.
  9798. this._requestRedraw(layer);
  9799. },
  9800. _updateStyle: function (layer) {
  9801. this._updateDashArray(layer);
  9802. this._requestRedraw(layer);
  9803. },
  9804. _updateDashArray: function (layer) {
  9805. if (layer.options.dashArray) {
  9806. var parts = layer.options.dashArray.split(','),
  9807. dashArray = [],
  9808. i;
  9809. for (i = 0; i < parts.length; i++) {
  9810. dashArray.push(Number(parts[i]));
  9811. }
  9812. layer.options._dashArray = dashArray;
  9813. }
  9814. },
  9815. _requestRedraw: function (layer) {
  9816. if (!this._map) { return; }
  9817. this._extendRedrawBounds(layer);
  9818. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  9819. },
  9820. _extendRedrawBounds: function (layer) {
  9821. if (layer._pxBounds) {
  9822. var padding = (layer.options.weight || 0) + 1;
  9823. this._redrawBounds = this._redrawBounds || new Bounds();
  9824. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  9825. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  9826. }
  9827. },
  9828. _redraw: function () {
  9829. this._redrawRequest = null;
  9830. if (this._redrawBounds) {
  9831. this._redrawBounds.min._floor();
  9832. this._redrawBounds.max._ceil();
  9833. }
  9834. this._clear(); // clear layers in redraw bounds
  9835. this._draw(); // draw layers
  9836. this._redrawBounds = null;
  9837. },
  9838. _clear: function () {
  9839. var bounds = this._redrawBounds;
  9840. if (bounds) {
  9841. var size = bounds.getSize();
  9842. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  9843. } else {
  9844. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  9845. }
  9846. },
  9847. _draw: function () {
  9848. var layer, bounds = this._redrawBounds;
  9849. this._ctx.save();
  9850. if (bounds) {
  9851. var size = bounds.getSize();
  9852. this._ctx.beginPath();
  9853. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  9854. this._ctx.clip();
  9855. }
  9856. this._drawing = true;
  9857. for (var order = this._drawFirst; order; order = order.next) {
  9858. layer = order.layer;
  9859. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  9860. layer._updatePath();
  9861. }
  9862. }
  9863. this._drawing = false;
  9864. this._ctx.restore(); // Restore state before clipping.
  9865. },
  9866. _updatePoly: function (layer, closed) {
  9867. if (!this._drawing) { return; }
  9868. var i, j, len2, p,
  9869. parts = layer._parts,
  9870. len = parts.length,
  9871. ctx = this._ctx;
  9872. if (!len) { return; }
  9873. this._drawnLayers[layer._leaflet_id] = layer;
  9874. ctx.beginPath();
  9875. for (i = 0; i < len; i++) {
  9876. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  9877. p = parts[i][j];
  9878. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  9879. }
  9880. if (closed) {
  9881. ctx.closePath();
  9882. }
  9883. }
  9884. this._fillStroke(ctx, layer);
  9885. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  9886. },
  9887. _updateCircle: function (layer) {
  9888. if (!this._drawing || layer._empty()) { return; }
  9889. var p = layer._point,
  9890. ctx = this._ctx,
  9891. r = Math.max(Math.round(layer._radius), 1),
  9892. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  9893. this._drawnLayers[layer._leaflet_id] = layer;
  9894. if (s !== 1) {
  9895. ctx.save();
  9896. ctx.scale(1, s);
  9897. }
  9898. ctx.beginPath();
  9899. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  9900. if (s !== 1) {
  9901. ctx.restore();
  9902. }
  9903. this._fillStroke(ctx, layer);
  9904. },
  9905. _fillStroke: function (ctx, layer) {
  9906. var options = layer.options;
  9907. if (options.fill) {
  9908. ctx.globalAlpha = options.fillOpacity;
  9909. ctx.fillStyle = options.fillColor || options.color;
  9910. ctx.fill(options.fillRule || 'evenodd');
  9911. }
  9912. if (options.stroke && options.weight !== 0) {
  9913. if (ctx.setLineDash) {
  9914. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  9915. }
  9916. ctx.globalAlpha = options.opacity;
  9917. ctx.lineWidth = options.weight;
  9918. ctx.strokeStyle = options.color;
  9919. ctx.lineCap = options.lineCap;
  9920. ctx.lineJoin = options.lineJoin;
  9921. ctx.stroke();
  9922. }
  9923. },
  9924. // Canvas obviously doesn't have mouse events for individual drawn objects,
  9925. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  9926. _onClick: function (e) {
  9927. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  9928. for (var order = this._drawFirst; order; order = order.next) {
  9929. layer = order.layer;
  9930. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  9931. clickedLayer = layer;
  9932. }
  9933. }
  9934. if (clickedLayer) {
  9935. fakeStop(e);
  9936. this._fireEvent([clickedLayer], e);
  9937. }
  9938. },
  9939. _onMouseMove: function (e) {
  9940. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  9941. var point = this._map.mouseEventToLayerPoint(e);
  9942. this._handleMouseHover(e, point);
  9943. },
  9944. _handleMouseOut: function (e) {
  9945. var layer = this._hoveredLayer;
  9946. if (layer) {
  9947. // if we're leaving the layer, fire mouseout
  9948. removeClass(this._container, 'leaflet-interactive');
  9949. this._fireEvent([layer], e, 'mouseout');
  9950. this._hoveredLayer = null;
  9951. }
  9952. },
  9953. _handleMouseHover: function (e, point) {
  9954. var layer, candidateHoveredLayer;
  9955. for (var order = this._drawFirst; order; order = order.next) {
  9956. layer = order.layer;
  9957. if (layer.options.interactive && layer._containsPoint(point)) {
  9958. candidateHoveredLayer = layer;
  9959. }
  9960. }
  9961. if (candidateHoveredLayer !== this._hoveredLayer) {
  9962. this._handleMouseOut(e);
  9963. if (candidateHoveredLayer) {
  9964. addClass(this._container, 'leaflet-interactive'); // change cursor
  9965. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  9966. this._hoveredLayer = candidateHoveredLayer;
  9967. }
  9968. }
  9969. if (this._hoveredLayer) {
  9970. this._fireEvent([this._hoveredLayer], e);
  9971. }
  9972. },
  9973. _fireEvent: function (layers, e, type) {
  9974. this._map._fireDOMEvent(e, type || e.type, layers);
  9975. },
  9976. _bringToFront: function (layer) {
  9977. var order = layer._order;
  9978. var next = order.next;
  9979. var prev = order.prev;
  9980. if (next) {
  9981. next.prev = prev;
  9982. } else {
  9983. // Already last
  9984. return;
  9985. }
  9986. if (prev) {
  9987. prev.next = next;
  9988. } else if (next) {
  9989. // Update first entry unless this is the
  9990. // single entry
  9991. this._drawFirst = next;
  9992. }
  9993. order.prev = this._drawLast;
  9994. this._drawLast.next = order;
  9995. order.next = null;
  9996. this._drawLast = order;
  9997. this._requestRedraw(layer);
  9998. },
  9999. _bringToBack: function (layer) {
  10000. var order = layer._order;
  10001. var next = order.next;
  10002. var prev = order.prev;
  10003. if (prev) {
  10004. prev.next = next;
  10005. } else {
  10006. // Already first
  10007. return;
  10008. }
  10009. if (next) {
  10010. next.prev = prev;
  10011. } else if (prev) {
  10012. // Update last entry unless this is the
  10013. // single entry
  10014. this._drawLast = prev;
  10015. }
  10016. order.prev = null;
  10017. order.next = this._drawFirst;
  10018. this._drawFirst.prev = order;
  10019. this._drawFirst = order;
  10020. this._requestRedraw(layer);
  10021. }
  10022. });
  10023. // @factory L.canvas(options?: Renderer options)
  10024. // Creates a Canvas renderer with the given options.
  10025. function canvas$1(options) {
  10026. return canvas ? new Canvas(options) : null;
  10027. }
  10028. /*
  10029. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10030. */
  10031. var vmlCreate = (function () {
  10032. try {
  10033. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10034. return function (name) {
  10035. return document.createElement('<lvml:' + name + ' class="lvml">');
  10036. };
  10037. } catch (e) {
  10038. return function (name) {
  10039. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10040. };
  10041. }
  10042. })();
  10043. /*
  10044. * @class SVG
  10045. *
  10046. * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case.
  10047. *
  10048. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10049. * with old versions of Internet Explorer.
  10050. */
  10051. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10052. var vmlMixin = {
  10053. _initContainer: function () {
  10054. this._container = create$1('div', 'leaflet-vml-container');
  10055. },
  10056. _update: function () {
  10057. if (this._map._animatingZoom) { return; }
  10058. Renderer.prototype._update.call(this);
  10059. this.fire('update');
  10060. },
  10061. _initPath: function (layer) {
  10062. var container = layer._container = vmlCreate('shape');
  10063. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10064. container.coordsize = '1 1';
  10065. layer._path = vmlCreate('path');
  10066. container.appendChild(layer._path);
  10067. this._updateStyle(layer);
  10068. this._layers[stamp(layer)] = layer;
  10069. },
  10070. _addPath: function (layer) {
  10071. var container = layer._container;
  10072. this._container.appendChild(container);
  10073. if (layer.options.interactive) {
  10074. layer.addInteractiveTarget(container);
  10075. }
  10076. },
  10077. _removePath: function (layer) {
  10078. var container = layer._container;
  10079. remove(container);
  10080. layer.removeInteractiveTarget(container);
  10081. delete this._layers[stamp(layer)];
  10082. },
  10083. _updateStyle: function (layer) {
  10084. var stroke = layer._stroke,
  10085. fill = layer._fill,
  10086. options = layer.options,
  10087. container = layer._container;
  10088. container.stroked = !!options.stroke;
  10089. container.filled = !!options.fill;
  10090. if (options.stroke) {
  10091. if (!stroke) {
  10092. stroke = layer._stroke = vmlCreate('stroke');
  10093. }
  10094. container.appendChild(stroke);
  10095. stroke.weight = options.weight + 'px';
  10096. stroke.color = options.color;
  10097. stroke.opacity = options.opacity;
  10098. if (options.dashArray) {
  10099. stroke.dashStyle = isArray(options.dashArray) ?
  10100. options.dashArray.join(' ') :
  10101. options.dashArray.replace(/( *, *)/g, ' ');
  10102. } else {
  10103. stroke.dashStyle = '';
  10104. }
  10105. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10106. stroke.joinstyle = options.lineJoin;
  10107. } else if (stroke) {
  10108. container.removeChild(stroke);
  10109. layer._stroke = null;
  10110. }
  10111. if (options.fill) {
  10112. if (!fill) {
  10113. fill = layer._fill = vmlCreate('fill');
  10114. }
  10115. container.appendChild(fill);
  10116. fill.color = options.fillColor || options.color;
  10117. fill.opacity = options.fillOpacity;
  10118. } else if (fill) {
  10119. container.removeChild(fill);
  10120. layer._fill = null;
  10121. }
  10122. },
  10123. _updateCircle: function (layer) {
  10124. var p = layer._point.round(),
  10125. r = Math.round(layer._radius),
  10126. r2 = Math.round(layer._radiusY || r);
  10127. this._setPath(layer, layer._empty() ? 'M0 0' :
  10128. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10129. },
  10130. _setPath: function (layer, path) {
  10131. layer._path.v = path;
  10132. },
  10133. _bringToFront: function (layer) {
  10134. toFront(layer._container);
  10135. },
  10136. _bringToBack: function (layer) {
  10137. toBack(layer._container);
  10138. }
  10139. };
  10140. var create$2 = vml ? vmlCreate : svgCreate;
  10141. /*
  10142. * @class SVG
  10143. * @inherits Renderer
  10144. * @aka L.SVG
  10145. *
  10146. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10147. * Inherits `Renderer`.
  10148. *
  10149. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10150. * available in all web browsers, notably Android 2.x and 3.x.
  10151. *
  10152. * Although SVG is not available on IE7 and IE8, these browsers support
  10153. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10154. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10155. * this case.
  10156. *
  10157. * @example
  10158. *
  10159. * Use SVG by default for all paths in the map:
  10160. *
  10161. * ```js
  10162. * var map = L.map('map', {
  10163. * renderer: L.svg()
  10164. * });
  10165. * ```
  10166. *
  10167. * Use a SVG renderer with extra padding for specific vector geometries:
  10168. *
  10169. * ```js
  10170. * var map = L.map('map');
  10171. * var myRenderer = L.svg({ padding: 0.5 });
  10172. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10173. * var circle = L.circle( center, { renderer: myRenderer } );
  10174. * ```
  10175. */
  10176. var SVG = Renderer.extend({
  10177. getEvents: function () {
  10178. var events = Renderer.prototype.getEvents.call(this);
  10179. events.zoomstart = this._onZoomStart;
  10180. return events;
  10181. },
  10182. _initContainer: function () {
  10183. this._container = create$2('svg');
  10184. // makes it possible to click through svg root; we'll reset it back in individual paths
  10185. this._container.setAttribute('pointer-events', 'none');
  10186. this._rootGroup = create$2('g');
  10187. this._container.appendChild(this._rootGroup);
  10188. },
  10189. _destroyContainer: function () {
  10190. remove(this._container);
  10191. off(this._container);
  10192. delete this._container;
  10193. delete this._rootGroup;
  10194. delete this._svgSize;
  10195. },
  10196. _onZoomStart: function () {
  10197. // Drag-then-pinch interactions might mess up the center and zoom.
  10198. // In this case, the easiest way to prevent this is re-do the renderer
  10199. // bounds and padding when the zooming starts.
  10200. this._update();
  10201. },
  10202. _update: function () {
  10203. if (this._map._animatingZoom && this._bounds) { return; }
  10204. Renderer.prototype._update.call(this);
  10205. var b = this._bounds,
  10206. size = b.getSize(),
  10207. container = this._container;
  10208. // set size of svg-container if changed
  10209. if (!this._svgSize || !this._svgSize.equals(size)) {
  10210. this._svgSize = size;
  10211. container.setAttribute('width', size.x);
  10212. container.setAttribute('height', size.y);
  10213. }
  10214. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10215. setPosition(container, b.min);
  10216. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10217. this.fire('update');
  10218. },
  10219. // methods below are called by vector layers implementations
  10220. _initPath: function (layer) {
  10221. var path = layer._path = create$2('path');
  10222. // @namespace Path
  10223. // @option className: String = null
  10224. // Custom class name set on an element. Only for SVG renderer.
  10225. if (layer.options.className) {
  10226. addClass(path, layer.options.className);
  10227. }
  10228. if (layer.options.interactive) {
  10229. addClass(path, 'leaflet-interactive');
  10230. }
  10231. this._updateStyle(layer);
  10232. this._layers[stamp(layer)] = layer;
  10233. },
  10234. _addPath: function (layer) {
  10235. if (!this._rootGroup) { this._initContainer(); }
  10236. this._rootGroup.appendChild(layer._path);
  10237. layer.addInteractiveTarget(layer._path);
  10238. },
  10239. _removePath: function (layer) {
  10240. remove(layer._path);
  10241. layer.removeInteractiveTarget(layer._path);
  10242. delete this._layers[stamp(layer)];
  10243. },
  10244. _updatePath: function (layer) {
  10245. layer._project();
  10246. layer._update();
  10247. },
  10248. _updateStyle: function (layer) {
  10249. var path = layer._path,
  10250. options = layer.options;
  10251. if (!path) { return; }
  10252. if (options.stroke) {
  10253. path.setAttribute('stroke', options.color);
  10254. path.setAttribute('stroke-opacity', options.opacity);
  10255. path.setAttribute('stroke-width', options.weight);
  10256. path.setAttribute('stroke-linecap', options.lineCap);
  10257. path.setAttribute('stroke-linejoin', options.lineJoin);
  10258. if (options.dashArray) {
  10259. path.setAttribute('stroke-dasharray', options.dashArray);
  10260. } else {
  10261. path.removeAttribute('stroke-dasharray');
  10262. }
  10263. if (options.dashOffset) {
  10264. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10265. } else {
  10266. path.removeAttribute('stroke-dashoffset');
  10267. }
  10268. } else {
  10269. path.setAttribute('stroke', 'none');
  10270. }
  10271. if (options.fill) {
  10272. path.setAttribute('fill', options.fillColor || options.color);
  10273. path.setAttribute('fill-opacity', options.fillOpacity);
  10274. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10275. } else {
  10276. path.setAttribute('fill', 'none');
  10277. }
  10278. },
  10279. _updatePoly: function (layer, closed) {
  10280. this._setPath(layer, pointsToPath(layer._parts, closed));
  10281. },
  10282. _updateCircle: function (layer) {
  10283. var p = layer._point,
  10284. r = Math.max(Math.round(layer._radius), 1),
  10285. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10286. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10287. // drawing a circle with two half-arcs
  10288. var d = layer._empty() ? 'M0 0' :
  10289. 'M' + (p.x - r) + ',' + p.y +
  10290. arc + (r * 2) + ',0 ' +
  10291. arc + (-r * 2) + ',0 ';
  10292. this._setPath(layer, d);
  10293. },
  10294. _setPath: function (layer, path) {
  10295. layer._path.setAttribute('d', path);
  10296. },
  10297. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10298. _bringToFront: function (layer) {
  10299. toFront(layer._path);
  10300. },
  10301. _bringToBack: function (layer) {
  10302. toBack(layer._path);
  10303. }
  10304. });
  10305. if (vml) {
  10306. SVG.include(vmlMixin);
  10307. }
  10308. // @namespace SVG
  10309. // @factory L.svg(options?: Renderer options)
  10310. // Creates a SVG renderer with the given options.
  10311. function svg$1(options) {
  10312. return svg || vml ? new SVG(options) : null;
  10313. }
  10314. Map.include({
  10315. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10316. // Returns the instance of `Renderer` that should be used to render the given
  10317. // `Path`. It will ensure that the `renderer` options of the map and paths
  10318. // are respected, and that the renderers do exist on the map.
  10319. getRenderer: function (layer) {
  10320. // @namespace Path; @option renderer: Renderer
  10321. // Use this specific instance of `Renderer` for this path. Takes
  10322. // precedence over the map's [default renderer](#map-renderer).
  10323. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10324. if (!renderer) {
  10325. // @namespace Map; @option preferCanvas: Boolean = false
  10326. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10327. // By default, all `Path`s are rendered in a `SVG` renderer.
  10328. renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1();
  10329. }
  10330. if (!this.hasLayer(renderer)) {
  10331. this.addLayer(renderer);
  10332. }
  10333. return renderer;
  10334. },
  10335. _getPaneRenderer: function (name) {
  10336. if (name === 'overlayPane' || name === undefined) {
  10337. return false;
  10338. }
  10339. var renderer = this._paneRenderers[name];
  10340. if (renderer === undefined) {
  10341. renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name}));
  10342. this._paneRenderers[name] = renderer;
  10343. }
  10344. return renderer;
  10345. }
  10346. });
  10347. /*
  10348. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10349. */
  10350. /*
  10351. * @class Rectangle
  10352. * @aka L.Rectangle
  10353. * @inherits Polygon
  10354. *
  10355. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10356. *
  10357. * @example
  10358. *
  10359. * ```js
  10360. * // define rectangle geographical bounds
  10361. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10362. *
  10363. * // create an orange rectangle
  10364. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10365. *
  10366. * // zoom the map to the rectangle bounds
  10367. * map.fitBounds(bounds);
  10368. * ```
  10369. *
  10370. */
  10371. var Rectangle = Polygon.extend({
  10372. initialize: function (latLngBounds, options) {
  10373. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10374. },
  10375. // @method setBounds(latLngBounds: LatLngBounds): this
  10376. // Redraws the rectangle with the passed bounds.
  10377. setBounds: function (latLngBounds) {
  10378. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10379. },
  10380. _boundsToLatLngs: function (latLngBounds) {
  10381. latLngBounds = toLatLngBounds(latLngBounds);
  10382. return [
  10383. latLngBounds.getSouthWest(),
  10384. latLngBounds.getNorthWest(),
  10385. latLngBounds.getNorthEast(),
  10386. latLngBounds.getSouthEast()
  10387. ];
  10388. }
  10389. });
  10390. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10391. function rectangle(latLngBounds, options) {
  10392. return new Rectangle(latLngBounds, options);
  10393. }
  10394. SVG.create = create$2;
  10395. SVG.pointsToPath = pointsToPath;
  10396. GeoJSON.geometryToLayer = geometryToLayer;
  10397. GeoJSON.coordsToLatLng = coordsToLatLng;
  10398. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10399. GeoJSON.latLngToCoords = latLngToCoords;
  10400. GeoJSON.latLngsToCoords = latLngsToCoords;
  10401. GeoJSON.getFeature = getFeature;
  10402. GeoJSON.asFeature = asFeature;
  10403. /*
  10404. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10405. * (zoom to a selected bounding box), enabled by default.
  10406. */
  10407. // @namespace Map
  10408. // @section Interaction Options
  10409. Map.mergeOptions({
  10410. // @option boxZoom: Boolean = true
  10411. // Whether the map can be zoomed to a rectangular area specified by
  10412. // dragging the mouse while pressing the shift key.
  10413. boxZoom: true
  10414. });
  10415. var BoxZoom = Handler.extend({
  10416. initialize: function (map) {
  10417. this._map = map;
  10418. this._container = map._container;
  10419. this._pane = map._panes.overlayPane;
  10420. this._resetStateTimeout = 0;
  10421. map.on('unload', this._destroy, this);
  10422. },
  10423. addHooks: function () {
  10424. on(this._container, 'mousedown', this._onMouseDown, this);
  10425. },
  10426. removeHooks: function () {
  10427. off(this._container, 'mousedown', this._onMouseDown, this);
  10428. },
  10429. moved: function () {
  10430. return this._moved;
  10431. },
  10432. _destroy: function () {
  10433. remove(this._pane);
  10434. delete this._pane;
  10435. },
  10436. _resetState: function () {
  10437. this._resetStateTimeout = 0;
  10438. this._moved = false;
  10439. },
  10440. _clearDeferredResetState: function () {
  10441. if (this._resetStateTimeout !== 0) {
  10442. clearTimeout(this._resetStateTimeout);
  10443. this._resetStateTimeout = 0;
  10444. }
  10445. },
  10446. _onMouseDown: function (e) {
  10447. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10448. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10449. // will interrupt the interaction and orphan a box element in the container.
  10450. this._clearDeferredResetState();
  10451. this._resetState();
  10452. disableTextSelection();
  10453. disableImageDrag();
  10454. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10455. on(document, {
  10456. contextmenu: stop,
  10457. mousemove: this._onMouseMove,
  10458. mouseup: this._onMouseUp,
  10459. keydown: this._onKeyDown
  10460. }, this);
  10461. },
  10462. _onMouseMove: function (e) {
  10463. if (!this._moved) {
  10464. this._moved = true;
  10465. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10466. addClass(this._container, 'leaflet-crosshair');
  10467. this._map.fire('boxzoomstart');
  10468. }
  10469. this._point = this._map.mouseEventToContainerPoint(e);
  10470. var bounds = new Bounds(this._point, this._startPoint),
  10471. size = bounds.getSize();
  10472. setPosition(this._box, bounds.min);
  10473. this._box.style.width = size.x + 'px';
  10474. this._box.style.height = size.y + 'px';
  10475. },
  10476. _finish: function () {
  10477. if (this._moved) {
  10478. remove(this._box);
  10479. removeClass(this._container, 'leaflet-crosshair');
  10480. }
  10481. enableTextSelection();
  10482. enableImageDrag();
  10483. off(document, {
  10484. contextmenu: stop,
  10485. mousemove: this._onMouseMove,
  10486. mouseup: this._onMouseUp,
  10487. keydown: this._onKeyDown
  10488. }, this);
  10489. },
  10490. _onMouseUp: function (e) {
  10491. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10492. this._finish();
  10493. if (!this._moved) { return; }
  10494. // Postpone to next JS tick so internal click event handling
  10495. // still see it as "moved".
  10496. this._clearDeferredResetState();
  10497. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10498. var bounds = new LatLngBounds(
  10499. this._map.containerPointToLatLng(this._startPoint),
  10500. this._map.containerPointToLatLng(this._point));
  10501. this._map
  10502. .fitBounds(bounds)
  10503. .fire('boxzoomend', {boxZoomBounds: bounds});
  10504. },
  10505. _onKeyDown: function (e) {
  10506. if (e.keyCode === 27) {
  10507. this._finish();
  10508. }
  10509. }
  10510. });
  10511. // @section Handlers
  10512. // @property boxZoom: Handler
  10513. // Box (shift-drag with mouse) zoom handler.
  10514. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10515. /*
  10516. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10517. */
  10518. // @namespace Map
  10519. // @section Interaction Options
  10520. Map.mergeOptions({
  10521. // @option doubleClickZoom: Boolean|String = true
  10522. // Whether the map can be zoomed in by double clicking on it and
  10523. // zoomed out by double clicking while holding shift. If passed
  10524. // `'center'`, double-click zoom will zoom to the center of the
  10525. // view regardless of where the mouse was.
  10526. doubleClickZoom: true
  10527. });
  10528. var DoubleClickZoom = Handler.extend({
  10529. addHooks: function () {
  10530. this._map.on('dblclick', this._onDoubleClick, this);
  10531. },
  10532. removeHooks: function () {
  10533. this._map.off('dblclick', this._onDoubleClick, this);
  10534. },
  10535. _onDoubleClick: function (e) {
  10536. var map = this._map,
  10537. oldZoom = map.getZoom(),
  10538. delta = map.options.zoomDelta,
  10539. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10540. if (map.options.doubleClickZoom === 'center') {
  10541. map.setZoom(zoom);
  10542. } else {
  10543. map.setZoomAround(e.containerPoint, zoom);
  10544. }
  10545. }
  10546. });
  10547. // @section Handlers
  10548. //
  10549. // Map properties include interaction handlers that allow you to control
  10550. // interaction behavior in runtime, enabling or disabling certain features such
  10551. // as dragging or touch zoom (see `Handler` methods). For example:
  10552. //
  10553. // ```js
  10554. // map.doubleClickZoom.disable();
  10555. // ```
  10556. //
  10557. // @property doubleClickZoom: Handler
  10558. // Double click zoom handler.
  10559. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10560. /*
  10561. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10562. */
  10563. // @namespace Map
  10564. // @section Interaction Options
  10565. Map.mergeOptions({
  10566. // @option dragging: Boolean = true
  10567. // Whether the map be draggable with mouse/touch or not.
  10568. dragging: true,
  10569. // @section Panning Inertia Options
  10570. // @option inertia: Boolean = *
  10571. // If enabled, panning of the map will have an inertia effect where
  10572. // the map builds momentum while dragging and continues moving in
  10573. // the same direction for some time. Feels especially nice on touch
  10574. // devices. Enabled by default unless running on old Android devices.
  10575. inertia: !android23,
  10576. // @option inertiaDeceleration: Number = 3000
  10577. // The rate with which the inertial movement slows down, in pixels/second².
  10578. inertiaDeceleration: 3400, // px/s^2
  10579. // @option inertiaMaxSpeed: Number = Infinity
  10580. // Max speed of the inertial movement, in pixels/second.
  10581. inertiaMaxSpeed: Infinity, // px/s
  10582. // @option easeLinearity: Number = 0.2
  10583. easeLinearity: 0.2,
  10584. // TODO refactor, move to CRS
  10585. // @option worldCopyJump: Boolean = false
  10586. // With this option enabled, the map tracks when you pan to another "copy"
  10587. // of the world and seamlessly jumps to the original one so that all overlays
  10588. // like markers and vector layers are still visible.
  10589. worldCopyJump: false,
  10590. // @option maxBoundsViscosity: Number = 0.0
  10591. // If `maxBounds` is set, this option will control how solid the bounds
  10592. // are when dragging the map around. The default value of `0.0` allows the
  10593. // user to drag outside the bounds at normal speed, higher values will
  10594. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10595. // solid, preventing the user from dragging outside the bounds.
  10596. maxBoundsViscosity: 0.0
  10597. });
  10598. var Drag = Handler.extend({
  10599. addHooks: function () {
  10600. if (!this._draggable) {
  10601. var map = this._map;
  10602. this._draggable = new Draggable(map._mapPane, map._container);
  10603. this._draggable.on({
  10604. dragstart: this._onDragStart,
  10605. drag: this._onDrag,
  10606. dragend: this._onDragEnd
  10607. }, this);
  10608. this._draggable.on('predrag', this._onPreDragLimit, this);
  10609. if (map.options.worldCopyJump) {
  10610. this._draggable.on('predrag', this._onPreDragWrap, this);
  10611. map.on('zoomend', this._onZoomEnd, this);
  10612. map.whenReady(this._onZoomEnd, this);
  10613. }
  10614. }
  10615. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10616. this._draggable.enable();
  10617. this._positions = [];
  10618. this._times = [];
  10619. },
  10620. removeHooks: function () {
  10621. removeClass(this._map._container, 'leaflet-grab');
  10622. removeClass(this._map._container, 'leaflet-touch-drag');
  10623. this._draggable.disable();
  10624. },
  10625. moved: function () {
  10626. return this._draggable && this._draggable._moved;
  10627. },
  10628. moving: function () {
  10629. return this._draggable && this._draggable._moving;
  10630. },
  10631. _onDragStart: function () {
  10632. var map = this._map;
  10633. map._stop();
  10634. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10635. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10636. this._offsetLimit = toBounds(
  10637. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10638. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10639. .add(this._map.getSize()));
  10640. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10641. } else {
  10642. this._offsetLimit = null;
  10643. }
  10644. map
  10645. .fire('movestart')
  10646. .fire('dragstart');
  10647. if (map.options.inertia) {
  10648. this._positions = [];
  10649. this._times = [];
  10650. }
  10651. },
  10652. _onDrag: function (e) {
  10653. if (this._map.options.inertia) {
  10654. var time = this._lastTime = +new Date(),
  10655. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10656. this._positions.push(pos);
  10657. this._times.push(time);
  10658. this._prunePositions(time);
  10659. }
  10660. this._map
  10661. .fire('move', e)
  10662. .fire('drag', e);
  10663. },
  10664. _prunePositions: function (time) {
  10665. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10666. this._positions.shift();
  10667. this._times.shift();
  10668. }
  10669. },
  10670. _onZoomEnd: function () {
  10671. var pxCenter = this._map.getSize().divideBy(2),
  10672. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10673. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10674. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10675. },
  10676. _viscousLimit: function (value, threshold) {
  10677. return value - (value - threshold) * this._viscosity;
  10678. },
  10679. _onPreDragLimit: function () {
  10680. if (!this._viscosity || !this._offsetLimit) { return; }
  10681. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10682. var limit = this._offsetLimit;
  10683. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10684. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10685. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10686. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10687. this._draggable._newPos = this._draggable._startPos.add(offset);
  10688. },
  10689. _onPreDragWrap: function () {
  10690. // TODO refactor to be able to adjust map pane position after zoom
  10691. var worldWidth = this._worldWidth,
  10692. halfWidth = Math.round(worldWidth / 2),
  10693. dx = this._initialWorldOffset,
  10694. x = this._draggable._newPos.x,
  10695. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10696. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10697. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10698. this._draggable._absPos = this._draggable._newPos.clone();
  10699. this._draggable._newPos.x = newX;
  10700. },
  10701. _onDragEnd: function (e) {
  10702. var map = this._map,
  10703. options = map.options,
  10704. noInertia = !options.inertia || this._times.length < 2;
  10705. map.fire('dragend', e);
  10706. if (noInertia) {
  10707. map.fire('moveend');
  10708. } else {
  10709. this._prunePositions(+new Date());
  10710. var direction = this._lastPos.subtract(this._positions[0]),
  10711. duration = (this._lastTime - this._times[0]) / 1000,
  10712. ease = options.easeLinearity,
  10713. speedVector = direction.multiplyBy(ease / duration),
  10714. speed = speedVector.distanceTo([0, 0]),
  10715. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10716. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10717. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10718. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10719. if (!offset.x && !offset.y) {
  10720. map.fire('moveend');
  10721. } else {
  10722. offset = map._limitOffset(offset, map.options.maxBounds);
  10723. requestAnimFrame(function () {
  10724. map.panBy(offset, {
  10725. duration: decelerationDuration,
  10726. easeLinearity: ease,
  10727. noMoveStart: true,
  10728. animate: true
  10729. });
  10730. });
  10731. }
  10732. }
  10733. }
  10734. });
  10735. // @section Handlers
  10736. // @property dragging: Handler
  10737. // Map dragging handler (by both mouse and touch).
  10738. Map.addInitHook('addHandler', 'dragging', Drag);
  10739. /*
  10740. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10741. */
  10742. // @namespace Map
  10743. // @section Keyboard Navigation Options
  10744. Map.mergeOptions({
  10745. // @option keyboard: Boolean = true
  10746. // Makes the map focusable and allows users to navigate the map with keyboard
  10747. // arrows and `+`/`-` keys.
  10748. keyboard: true,
  10749. // @option keyboardPanDelta: Number = 80
  10750. // Amount of pixels to pan when pressing an arrow key.
  10751. keyboardPanDelta: 80
  10752. });
  10753. var Keyboard = Handler.extend({
  10754. keyCodes: {
  10755. left: [37],
  10756. right: [39],
  10757. down: [40],
  10758. up: [38],
  10759. zoomIn: [187, 107, 61, 171],
  10760. zoomOut: [189, 109, 54, 173]
  10761. },
  10762. initialize: function (map) {
  10763. this._map = map;
  10764. this._setPanDelta(map.options.keyboardPanDelta);
  10765. this._setZoomDelta(map.options.zoomDelta);
  10766. },
  10767. addHooks: function () {
  10768. var container = this._map._container;
  10769. // make the container focusable by tabbing
  10770. if (container.tabIndex <= 0) {
  10771. container.tabIndex = '0';
  10772. }
  10773. on(container, {
  10774. focus: this._onFocus,
  10775. blur: this._onBlur,
  10776. mousedown: this._onMouseDown
  10777. }, this);
  10778. this._map.on({
  10779. focus: this._addHooks,
  10780. blur: this._removeHooks
  10781. }, this);
  10782. },
  10783. removeHooks: function () {
  10784. this._removeHooks();
  10785. off(this._map._container, {
  10786. focus: this._onFocus,
  10787. blur: this._onBlur,
  10788. mousedown: this._onMouseDown
  10789. }, this);
  10790. this._map.off({
  10791. focus: this._addHooks,
  10792. blur: this._removeHooks
  10793. }, this);
  10794. },
  10795. _onMouseDown: function () {
  10796. if (this._focused) { return; }
  10797. var body = document.body,
  10798. docEl = document.documentElement,
  10799. top = body.scrollTop || docEl.scrollTop,
  10800. left = body.scrollLeft || docEl.scrollLeft;
  10801. this._map._container.focus();
  10802. window.scrollTo(left, top);
  10803. },
  10804. _onFocus: function () {
  10805. this._focused = true;
  10806. this._map.fire('focus');
  10807. },
  10808. _onBlur: function () {
  10809. this._focused = false;
  10810. this._map.fire('blur');
  10811. },
  10812. _setPanDelta: function (panDelta) {
  10813. var keys = this._panKeys = {},
  10814. codes = this.keyCodes,
  10815. i, len;
  10816. for (i = 0, len = codes.left.length; i < len; i++) {
  10817. keys[codes.left[i]] = [-1 * panDelta, 0];
  10818. }
  10819. for (i = 0, len = codes.right.length; i < len; i++) {
  10820. keys[codes.right[i]] = [panDelta, 0];
  10821. }
  10822. for (i = 0, len = codes.down.length; i < len; i++) {
  10823. keys[codes.down[i]] = [0, panDelta];
  10824. }
  10825. for (i = 0, len = codes.up.length; i < len; i++) {
  10826. keys[codes.up[i]] = [0, -1 * panDelta];
  10827. }
  10828. },
  10829. _setZoomDelta: function (zoomDelta) {
  10830. var keys = this._zoomKeys = {},
  10831. codes = this.keyCodes,
  10832. i, len;
  10833. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  10834. keys[codes.zoomIn[i]] = zoomDelta;
  10835. }
  10836. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  10837. keys[codes.zoomOut[i]] = -zoomDelta;
  10838. }
  10839. },
  10840. _addHooks: function () {
  10841. on(document, 'keydown', this._onKeyDown, this);
  10842. },
  10843. _removeHooks: function () {
  10844. off(document, 'keydown', this._onKeyDown, this);
  10845. },
  10846. _onKeyDown: function (e) {
  10847. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  10848. var key = e.keyCode,
  10849. map = this._map,
  10850. offset;
  10851. if (key in this._panKeys) {
  10852. if (map._panAnim && map._panAnim._inProgress) { return; }
  10853. offset = this._panKeys[key];
  10854. if (e.shiftKey) {
  10855. offset = toPoint(offset).multiplyBy(3);
  10856. }
  10857. map.panBy(offset);
  10858. if (map.options.maxBounds) {
  10859. map.panInsideBounds(map.options.maxBounds);
  10860. }
  10861. } else if (key in this._zoomKeys) {
  10862. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  10863. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  10864. map.closePopup();
  10865. } else {
  10866. return;
  10867. }
  10868. stop(e);
  10869. }
  10870. });
  10871. // @section Handlers
  10872. // @section Handlers
  10873. // @property keyboard: Handler
  10874. // Keyboard navigation handler.
  10875. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  10876. /*
  10877. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  10878. */
  10879. // @namespace Map
  10880. // @section Interaction Options
  10881. Map.mergeOptions({
  10882. // @section Mousewheel options
  10883. // @option scrollWheelZoom: Boolean|String = true
  10884. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  10885. // it will zoom to the center of the view regardless of where the mouse was.
  10886. scrollWheelZoom: true,
  10887. // @option wheelDebounceTime: Number = 40
  10888. // Limits the rate at which a wheel can fire (in milliseconds). By default
  10889. // user can't zoom via wheel more often than once per 40 ms.
  10890. wheelDebounceTime: 40,
  10891. // @option wheelPxPerZoomLevel: Number = 60
  10892. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  10893. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  10894. // faster (and vice versa).
  10895. wheelPxPerZoomLevel: 60
  10896. });
  10897. var ScrollWheelZoom = Handler.extend({
  10898. addHooks: function () {
  10899. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10900. this._delta = 0;
  10901. },
  10902. removeHooks: function () {
  10903. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10904. },
  10905. _onWheelScroll: function (e) {
  10906. var delta = getWheelDelta(e);
  10907. var debounce = this._map.options.wheelDebounceTime;
  10908. this._delta += delta;
  10909. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  10910. if (!this._startTime) {
  10911. this._startTime = +new Date();
  10912. }
  10913. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  10914. clearTimeout(this._timer);
  10915. this._timer = setTimeout(bind(this._performZoom, this), left);
  10916. stop(e);
  10917. },
  10918. _performZoom: function () {
  10919. var map = this._map,
  10920. zoom = map.getZoom(),
  10921. snap = this._map.options.zoomSnap || 0;
  10922. map._stop(); // stop panning and fly animations if any
  10923. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  10924. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  10925. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  10926. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  10927. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  10928. this._delta = 0;
  10929. this._startTime = null;
  10930. if (!delta) { return; }
  10931. if (map.options.scrollWheelZoom === 'center') {
  10932. map.setZoom(zoom + delta);
  10933. } else {
  10934. map.setZoomAround(this._lastMousePos, zoom + delta);
  10935. }
  10936. }
  10937. });
  10938. // @section Handlers
  10939. // @property scrollWheelZoom: Handler
  10940. // Scroll wheel zoom handler.
  10941. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  10942. /*
  10943. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  10944. */
  10945. // @namespace Map
  10946. // @section Interaction Options
  10947. Map.mergeOptions({
  10948. // @section Touch interaction options
  10949. // @option tap: Boolean = true
  10950. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  10951. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  10952. tap: true,
  10953. // @option tapTolerance: Number = 15
  10954. // The max number of pixels a user can shift his finger during touch
  10955. // for it to be considered a valid tap.
  10956. tapTolerance: 15
  10957. });
  10958. var Tap = Handler.extend({
  10959. addHooks: function () {
  10960. on(this._map._container, 'touchstart', this._onDown, this);
  10961. },
  10962. removeHooks: function () {
  10963. off(this._map._container, 'touchstart', this._onDown, this);
  10964. },
  10965. _onDown: function (e) {
  10966. if (!e.touches) { return; }
  10967. preventDefault(e);
  10968. this._fireClick = true;
  10969. // don't simulate click or track longpress if more than 1 touch
  10970. if (e.touches.length > 1) {
  10971. this._fireClick = false;
  10972. clearTimeout(this._holdTimeout);
  10973. return;
  10974. }
  10975. var first = e.touches[0],
  10976. el = first.target;
  10977. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  10978. // if touching a link, highlight it
  10979. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  10980. addClass(el, 'leaflet-active');
  10981. }
  10982. // simulate long hold but setting a timeout
  10983. this._holdTimeout = setTimeout(bind(function () {
  10984. if (this._isTapValid()) {
  10985. this._fireClick = false;
  10986. this._onUp();
  10987. this._simulateEvent('contextmenu', first);
  10988. }
  10989. }, this), 1000);
  10990. this._simulateEvent('mousedown', first);
  10991. on(document, {
  10992. touchmove: this._onMove,
  10993. touchend: this._onUp
  10994. }, this);
  10995. },
  10996. _onUp: function (e) {
  10997. clearTimeout(this._holdTimeout);
  10998. off(document, {
  10999. touchmove: this._onMove,
  11000. touchend: this._onUp
  11001. }, this);
  11002. if (this._fireClick && e && e.changedTouches) {
  11003. var first = e.changedTouches[0],
  11004. el = first.target;
  11005. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11006. removeClass(el, 'leaflet-active');
  11007. }
  11008. this._simulateEvent('mouseup', first);
  11009. // simulate click if the touch didn't move too much
  11010. if (this._isTapValid()) {
  11011. this._simulateEvent('click', first);
  11012. }
  11013. }
  11014. },
  11015. _isTapValid: function () {
  11016. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11017. },
  11018. _onMove: function (e) {
  11019. var first = e.touches[0];
  11020. this._newPos = new Point(first.clientX, first.clientY);
  11021. this._simulateEvent('mousemove', first);
  11022. },
  11023. _simulateEvent: function (type, e) {
  11024. var simulatedEvent = document.createEvent('MouseEvents');
  11025. simulatedEvent._simulated = true;
  11026. e.target._simulatedClick = true;
  11027. simulatedEvent.initMouseEvent(
  11028. type, true, true, window, 1,
  11029. e.screenX, e.screenY,
  11030. e.clientX, e.clientY,
  11031. false, false, false, false, 0, null);
  11032. e.target.dispatchEvent(simulatedEvent);
  11033. }
  11034. });
  11035. // @section Handlers
  11036. // @property tap: Handler
  11037. // Mobile touch hacks (quick tap and touch hold) handler.
  11038. if (touch && !pointer) {
  11039. Map.addInitHook('addHandler', 'tap', Tap);
  11040. }
  11041. /*
  11042. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11043. */
  11044. // @namespace Map
  11045. // @section Interaction Options
  11046. Map.mergeOptions({
  11047. // @section Touch interaction options
  11048. // @option touchZoom: Boolean|String = *
  11049. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11050. // passed `'center'`, it will zoom to the center of the view regardless of
  11051. // where the touch events (fingers) were. Enabled for touch-capable web
  11052. // browsers except for old Androids.
  11053. touchZoom: touch && !android23,
  11054. // @option bounceAtZoomLimits: Boolean = true
  11055. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11056. // and then bounce back when pinch-zooming.
  11057. bounceAtZoomLimits: true
  11058. });
  11059. var TouchZoom = Handler.extend({
  11060. addHooks: function () {
  11061. addClass(this._map._container, 'leaflet-touch-zoom');
  11062. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11063. },
  11064. removeHooks: function () {
  11065. removeClass(this._map._container, 'leaflet-touch-zoom');
  11066. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11067. },
  11068. _onTouchStart: function (e) {
  11069. var map = this._map;
  11070. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11071. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11072. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11073. this._centerPoint = map.getSize()._divideBy(2);
  11074. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11075. if (map.options.touchZoom !== 'center') {
  11076. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11077. }
  11078. this._startDist = p1.distanceTo(p2);
  11079. this._startZoom = map.getZoom();
  11080. this._moved = false;
  11081. this._zooming = true;
  11082. map._stop();
  11083. on(document, 'touchmove', this._onTouchMove, this);
  11084. on(document, 'touchend', this._onTouchEnd, this);
  11085. preventDefault(e);
  11086. },
  11087. _onTouchMove: function (e) {
  11088. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11089. var map = this._map,
  11090. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11091. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11092. scale = p1.distanceTo(p2) / this._startDist;
  11093. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11094. if (!map.options.bounceAtZoomLimits && (
  11095. (this._zoom < map.getMinZoom() && scale < 1) ||
  11096. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11097. this._zoom = map._limitZoom(this._zoom);
  11098. }
  11099. if (map.options.touchZoom === 'center') {
  11100. this._center = this._startLatLng;
  11101. if (scale === 1) { return; }
  11102. } else {
  11103. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11104. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11105. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11106. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11107. }
  11108. if (!this._moved) {
  11109. map._moveStart(true, false);
  11110. this._moved = true;
  11111. }
  11112. cancelAnimFrame(this._animRequest);
  11113. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11114. this._animRequest = requestAnimFrame(moveFn, this, true);
  11115. preventDefault(e);
  11116. },
  11117. _onTouchEnd: function () {
  11118. if (!this._moved || !this._zooming) {
  11119. this._zooming = false;
  11120. return;
  11121. }
  11122. this._zooming = false;
  11123. cancelAnimFrame(this._animRequest);
  11124. off(document, 'touchmove', this._onTouchMove);
  11125. off(document, 'touchend', this._onTouchEnd);
  11126. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11127. if (this._map.options.zoomAnimation) {
  11128. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11129. } else {
  11130. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11131. }
  11132. }
  11133. });
  11134. // @section Handlers
  11135. // @property touchZoom: Handler
  11136. // Touch zoom handler.
  11137. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11138. Map.BoxZoom = BoxZoom;
  11139. Map.DoubleClickZoom = DoubleClickZoom;
  11140. Map.Drag = Drag;
  11141. Map.Keyboard = Keyboard;
  11142. Map.ScrollWheelZoom = ScrollWheelZoom;
  11143. Map.Tap = Tap;
  11144. Map.TouchZoom = TouchZoom;
  11145. // misc
  11146. var oldL = window.L;
  11147. function noConflict() {
  11148. window.L = oldL;
  11149. return this;
  11150. }
  11151. // Always export us to window global (see #2364)
  11152. window.L = exports;
  11153. Object.freeze = freeze;
  11154. exports.version = version;
  11155. exports.noConflict = noConflict;
  11156. exports.Control = Control;
  11157. exports.control = control;
  11158. exports.Browser = Browser;
  11159. exports.Evented = Evented;
  11160. exports.Mixin = Mixin;
  11161. exports.Util = Util;
  11162. exports.Class = Class;
  11163. exports.Handler = Handler;
  11164. exports.extend = extend;
  11165. exports.bind = bind;
  11166. exports.stamp = stamp;
  11167. exports.setOptions = setOptions;
  11168. exports.DomEvent = DomEvent;
  11169. exports.DomUtil = DomUtil;
  11170. exports.PosAnimation = PosAnimation;
  11171. exports.Draggable = Draggable;
  11172. exports.LineUtil = LineUtil;
  11173. exports.PolyUtil = PolyUtil;
  11174. exports.Point = Point;
  11175. exports.point = toPoint;
  11176. exports.Bounds = Bounds;
  11177. exports.bounds = toBounds;
  11178. exports.Transformation = Transformation;
  11179. exports.transformation = toTransformation;
  11180. exports.Projection = index;
  11181. exports.LatLng = LatLng;
  11182. exports.latLng = toLatLng;
  11183. exports.LatLngBounds = LatLngBounds;
  11184. exports.latLngBounds = toLatLngBounds;
  11185. exports.CRS = CRS;
  11186. exports.GeoJSON = GeoJSON;
  11187. exports.geoJSON = geoJSON;
  11188. exports.geoJson = geoJson;
  11189. exports.Layer = Layer;
  11190. exports.LayerGroup = LayerGroup;
  11191. exports.layerGroup = layerGroup;
  11192. exports.FeatureGroup = FeatureGroup;
  11193. exports.featureGroup = featureGroup;
  11194. exports.ImageOverlay = ImageOverlay;
  11195. exports.imageOverlay = imageOverlay;
  11196. exports.VideoOverlay = VideoOverlay;
  11197. exports.videoOverlay = videoOverlay;
  11198. exports.DivOverlay = DivOverlay;
  11199. exports.Popup = Popup;
  11200. exports.popup = popup;
  11201. exports.Tooltip = Tooltip;
  11202. exports.tooltip = tooltip;
  11203. exports.Icon = Icon;
  11204. exports.icon = icon;
  11205. exports.DivIcon = DivIcon;
  11206. exports.divIcon = divIcon;
  11207. exports.Marker = Marker;
  11208. exports.marker = marker;
  11209. exports.TileLayer = TileLayer;
  11210. exports.tileLayer = tileLayer;
  11211. exports.GridLayer = GridLayer;
  11212. exports.gridLayer = gridLayer;
  11213. exports.SVG = SVG;
  11214. exports.svg = svg$1;
  11215. exports.Renderer = Renderer;
  11216. exports.Canvas = Canvas;
  11217. exports.canvas = canvas$1;
  11218. exports.Path = Path;
  11219. exports.CircleMarker = CircleMarker;
  11220. exports.circleMarker = circleMarker;
  11221. exports.Circle = Circle;
  11222. exports.circle = circle;
  11223. exports.Polyline = Polyline;
  11224. exports.polyline = polyline;
  11225. exports.Polygon = Polygon;
  11226. exports.polygon = polygon;
  11227. exports.Rectangle = Rectangle;
  11228. exports.rectangle = rectangle;
  11229. exports.Map = Map;
  11230. exports.map = createMap;
  11231. })));
  11232. //# sourceMappingURL=leaflet-src.js.map