leaflet-src.js 380 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805
  1. /*!
  2. * Copyright (c) 2010-2018, Vladimir Agafonkin
  3. * Copyright (c) 2010-2011, CloudMade
  4. * leaflet.(https://github.com/Leaflet/Leaflet)
  5. * license: BSD-2-Clause
  6. * version: v1.3.1
  7. */
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  10. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  11. (factory((global.L = {})));
  12. }(this, (function (exports) { 'use strict';
  13. var version = "1.3.1";
  14. /*
  15. * @namespace Util
  16. *
  17. * Various utility functions, used by Leaflet internally.
  18. */
  19. var freeze = Object.freeze;
  20. Object.freeze = function (obj) { return obj; };
  21. // @function extend(dest: Object, src?: Object): Object
  22. // Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut.
  23. function extend(dest) {
  24. var i, j, len, src;
  25. for (j = 1, len = arguments.length; j < len; j++) {
  26. src = arguments[j];
  27. for (i in src) {
  28. dest[i] = src[i];
  29. }
  30. }
  31. return dest;
  32. }
  33. // @function create(proto: Object, properties?: Object): Object
  34. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  35. var create = Object.create || (function () {
  36. function F() {}
  37. return function (proto) {
  38. F.prototype = proto;
  39. return new F();
  40. };
  41. })();
  42. // @function bind(fn: Function, …): Function
  43. // 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).
  44. // Has a `L.bind()` shortcut.
  45. function bind(fn, obj) {
  46. var slice = Array.prototype.slice;
  47. if (fn.bind) {
  48. return fn.bind.apply(fn, slice.call(arguments, 1));
  49. }
  50. var args = slice.call(arguments, 2);
  51. return function () {
  52. return fn.apply(obj, args.length ? args.concat(slice.call(arguments)) : arguments);
  53. };
  54. }
  55. // @property lastId: Number
  56. // Last unique ID used by [`stamp()`](#util-stamp)
  57. var lastId = 0;
  58. // @function stamp(obj: Object): Number
  59. // Returns the unique ID of an object, assigning it one if it doesn't have it.
  60. function stamp(obj) {
  61. /*eslint-disable */
  62. obj._leaflet_id = obj._leaflet_id || ++lastId;
  63. return obj._leaflet_id;
  64. /* eslint-enable */
  65. }
  66. // @function throttle(fn: Function, time: Number, context: Object): Function
  67. // Returns a function which executes function `fn` with the given scope `context`
  68. // (so that the `this` keyword refers to `context` inside `fn`'s code). The function
  69. // `fn` will be called no more than one time per given amount of `time`. The arguments
  70. // received by the bound function will be any arguments passed when binding the
  71. // function, followed by any arguments passed when invoking the bound function.
  72. // Has an `L.throttle` shortcut.
  73. function throttle(fn, time, context) {
  74. var lock, args, wrapperFn, later;
  75. later = function () {
  76. // reset lock and call if queued
  77. lock = false;
  78. if (args) {
  79. wrapperFn.apply(context, args);
  80. args = false;
  81. }
  82. };
  83. wrapperFn = function () {
  84. if (lock) {
  85. // called too soon, queue to call later
  86. args = arguments;
  87. } else {
  88. // call and lock until later
  89. fn.apply(context, arguments);
  90. setTimeout(later, time);
  91. lock = true;
  92. }
  93. };
  94. return wrapperFn;
  95. }
  96. // @function wrapNum(num: Number, range: Number[], includeMax?: Boolean): Number
  97. // Returns the number `num` modulo `range` in such a way so it lies within
  98. // `range[0]` and `range[1]`. The returned value will be always smaller than
  99. // `range[1]` unless `includeMax` is set to `true`.
  100. function wrapNum(x, range, includeMax) {
  101. var max = range[1],
  102. min = range[0],
  103. d = max - min;
  104. return x === max && includeMax ? x : ((x - min) % d + d) % d + min;
  105. }
  106. // @function falseFn(): Function
  107. // Returns a function which always returns `false`.
  108. function falseFn() { return false; }
  109. // @function formatNum(num: Number, digits?: Number): Number
  110. // Returns the number `num` rounded to `digits` decimals, or to 6 decimals by default.
  111. function formatNum(num, digits) {
  112. var pow = Math.pow(10, (digits === undefined ? 6 : digits));
  113. return Math.round(num * pow) / pow;
  114. }
  115. // @function trim(str: String): String
  116. // Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  117. function trim(str) {
  118. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  119. }
  120. // @function splitWords(str: String): String[]
  121. // Trims and splits the string on whitespace and returns the array of parts.
  122. function splitWords(str) {
  123. return trim(str).split(/\s+/);
  124. }
  125. // @function setOptions(obj: Object, options: Object): Object
  126. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  127. function setOptions(obj, options) {
  128. if (!obj.hasOwnProperty('options')) {
  129. obj.options = obj.options ? create(obj.options) : {};
  130. }
  131. for (var i in options) {
  132. obj.options[i] = options[i];
  133. }
  134. return obj.options;
  135. }
  136. // @function getParamString(obj: Object, existingUrl?: String, uppercase?: Boolean): String
  137. // Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}`
  138. // translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will
  139. // be appended at the end. If `uppercase` is `true`, the parameter names will
  140. // be uppercased (e.g. `'?A=foo&B=bar'`)
  141. function getParamString(obj, existingUrl, uppercase) {
  142. var params = [];
  143. for (var i in obj) {
  144. params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
  145. }
  146. return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
  147. }
  148. var templateRe = /\{ *([\w_-]+) *\}/g;
  149. // @function template(str: String, data: Object): String
  150. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  151. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  152. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  153. // data values — they will be evaluated passing `data` as an argument.
  154. function template(str, data) {
  155. return str.replace(templateRe, function (str, key) {
  156. var value = data[key];
  157. if (value === undefined) {
  158. throw new Error('No value provided for variable ' + str);
  159. } else if (typeof value === 'function') {
  160. value = value(data);
  161. }
  162. return value;
  163. });
  164. }
  165. // @function isArray(obj): Boolean
  166. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  167. var isArray = Array.isArray || function (obj) {
  168. return (Object.prototype.toString.call(obj) === '[object Array]');
  169. };
  170. // @function indexOf(array: Array, el: Object): Number
  171. // Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  172. function indexOf(array, el) {
  173. for (var i = 0; i < array.length; i++) {
  174. if (array[i] === el) { return i; }
  175. }
  176. return -1;
  177. }
  178. // @property emptyImageUrl: String
  179. // Data URI string containing a base64-encoded empty GIF image.
  180. // Used as a hack to free memory from unused images on WebKit-powered
  181. // mobile devices (by setting image `src` to this string).
  182. var emptyImageUrl = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
  183. // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  184. function getPrefixed(name) {
  185. return window['webkit' + name] || window['moz' + name] || window['ms' + name];
  186. }
  187. var lastTime = 0;
  188. // fallback for IE 7-8
  189. function timeoutDefer(fn) {
  190. var time = +new Date(),
  191. timeToCall = Math.max(0, 16 - (time - lastTime));
  192. lastTime = time + timeToCall;
  193. return window.setTimeout(fn, timeToCall);
  194. }
  195. var requestFn = window.requestAnimationFrame || getPrefixed('RequestAnimationFrame') || timeoutDefer;
  196. var cancelFn = window.cancelAnimationFrame || getPrefixed('CancelAnimationFrame') ||
  197. getPrefixed('CancelRequestAnimationFrame') || function (id) { window.clearTimeout(id); };
  198. // @function requestAnimFrame(fn: Function, context?: Object, immediate?: Boolean): Number
  199. // Schedules `fn` to be executed when the browser repaints. `fn` is bound to
  200. // `context` if given. When `immediate` is set, `fn` is called immediately if
  201. // the browser doesn't have native support for
  202. // [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame),
  203. // otherwise it's delayed. Returns a request ID that can be used to cancel the request.
  204. function requestAnimFrame(fn, context, immediate) {
  205. if (immediate && requestFn === timeoutDefer) {
  206. fn.call(context);
  207. } else {
  208. return requestFn.call(window, bind(fn, context));
  209. }
  210. }
  211. // @function cancelAnimFrame(id: Number): undefined
  212. // Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame).
  213. function cancelAnimFrame(id) {
  214. if (id) {
  215. cancelFn.call(window, id);
  216. }
  217. }
  218. var Util = (Object.freeze || Object)({
  219. freeze: freeze,
  220. extend: extend,
  221. create: create,
  222. bind: bind,
  223. lastId: lastId,
  224. stamp: stamp,
  225. throttle: throttle,
  226. wrapNum: wrapNum,
  227. falseFn: falseFn,
  228. formatNum: formatNum,
  229. trim: trim,
  230. splitWords: splitWords,
  231. setOptions: setOptions,
  232. getParamString: getParamString,
  233. template: template,
  234. isArray: isArray,
  235. indexOf: indexOf,
  236. emptyImageUrl: emptyImageUrl,
  237. requestFn: requestFn,
  238. cancelFn: cancelFn,
  239. requestAnimFrame: requestAnimFrame,
  240. cancelAnimFrame: cancelAnimFrame
  241. });
  242. // @class Class
  243. // @aka L.Class
  244. // @section
  245. // @uninheritable
  246. // Thanks to John Resig and Dean Edwards for inspiration!
  247. function Class() {}
  248. Class.extend = function (props) {
  249. // @function extend(props: Object): Function
  250. // [Extends the current class](#class-inheritance) given the properties to be included.
  251. // Returns a Javascript function that is a class constructor (to be called with `new`).
  252. var NewClass = function () {
  253. // call the constructor
  254. if (this.initialize) {
  255. this.initialize.apply(this, arguments);
  256. }
  257. // call all constructor hooks
  258. this.callInitHooks();
  259. };
  260. var parentProto = NewClass.__super__ = this.prototype;
  261. var proto = create(parentProto);
  262. proto.constructor = NewClass;
  263. NewClass.prototype = proto;
  264. // inherit parent's statics
  265. for (var i in this) {
  266. if (this.hasOwnProperty(i) && i !== 'prototype' && i !== '__super__') {
  267. NewClass[i] = this[i];
  268. }
  269. }
  270. // mix static properties into the class
  271. if (props.statics) {
  272. extend(NewClass, props.statics);
  273. delete props.statics;
  274. }
  275. // mix includes into the prototype
  276. if (props.includes) {
  277. checkDeprecatedMixinEvents(props.includes);
  278. extend.apply(null, [proto].concat(props.includes));
  279. delete props.includes;
  280. }
  281. // merge options
  282. if (proto.options) {
  283. props.options = extend(create(proto.options), props.options);
  284. }
  285. // mix given properties into the prototype
  286. extend(proto, props);
  287. proto._initHooks = [];
  288. // add method for calling all hooks
  289. proto.callInitHooks = function () {
  290. if (this._initHooksCalled) { return; }
  291. if (parentProto.callInitHooks) {
  292. parentProto.callInitHooks.call(this);
  293. }
  294. this._initHooksCalled = true;
  295. for (var i = 0, len = proto._initHooks.length; i < len; i++) {
  296. proto._initHooks[i].call(this);
  297. }
  298. };
  299. return NewClass;
  300. };
  301. // @function include(properties: Object): this
  302. // [Includes a mixin](#class-includes) into the current class.
  303. Class.include = function (props) {
  304. extend(this.prototype, props);
  305. return this;
  306. };
  307. // @function mergeOptions(options: Object): this
  308. // [Merges `options`](#class-options) into the defaults of the class.
  309. Class.mergeOptions = function (options) {
  310. extend(this.prototype.options, options);
  311. return this;
  312. };
  313. // @function addInitHook(fn: Function): this
  314. // Adds a [constructor hook](#class-constructor-hooks) to the class.
  315. Class.addInitHook = function (fn) { // (Function) || (String, args...)
  316. var args = Array.prototype.slice.call(arguments, 1);
  317. var init = typeof fn === 'function' ? fn : function () {
  318. this[fn].apply(this, args);
  319. };
  320. this.prototype._initHooks = this.prototype._initHooks || [];
  321. this.prototype._initHooks.push(init);
  322. return this;
  323. };
  324. function checkDeprecatedMixinEvents(includes) {
  325. if (typeof L === 'undefined' || !L || !L.Mixin) { return; }
  326. includes = isArray(includes) ? includes : [includes];
  327. for (var i = 0; i < includes.length; i++) {
  328. if (includes[i] === L.Mixin.Events) {
  329. console.warn('Deprecated include of L.Mixin.Events: ' +
  330. 'this property will be removed in future releases, ' +
  331. 'please inherit from L.Evented instead.', new Error().stack);
  332. }
  333. }
  334. }
  335. /*
  336. * @class Evented
  337. * @aka L.Evented
  338. * @inherits Class
  339. *
  340. * 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).
  341. *
  342. * @example
  343. *
  344. * ```js
  345. * map.on('click', function(e) {
  346. * alert(e.latlng);
  347. * } );
  348. * ```
  349. *
  350. * Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:
  351. *
  352. * ```js
  353. * function onClick(e) { ... }
  354. *
  355. * map.on('click', onClick);
  356. * map.off('click', onClick);
  357. * ```
  358. */
  359. var Events = {
  360. /* @method on(type: String, fn: Function, context?: Object): this
  361. * 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'`).
  362. *
  363. * @alternative
  364. * @method on(eventMap: Object): this
  365. * Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  366. */
  367. on: function (types, fn, context) {
  368. // types can be a map of types/handlers
  369. if (typeof types === 'object') {
  370. for (var type in types) {
  371. // we don't process space-separated events here for performance;
  372. // it's a hot path since Layer uses the on(obj) syntax
  373. this._on(type, types[type], fn);
  374. }
  375. } else {
  376. // types can be a string of space-separated words
  377. types = splitWords(types);
  378. for (var i = 0, len = types.length; i < len; i++) {
  379. this._on(types[i], fn, context);
  380. }
  381. }
  382. return this;
  383. },
  384. /* @method off(type: String, fn?: Function, context?: Object): this
  385. * 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.
  386. *
  387. * @alternative
  388. * @method off(eventMap: Object): this
  389. * Removes a set of type/listener pairs.
  390. *
  391. * @alternative
  392. * @method off: this
  393. * Removes all listeners to all events on the object.
  394. */
  395. off: function (types, fn, context) {
  396. if (!types) {
  397. // clear all listeners if called without arguments
  398. delete this._events;
  399. } else if (typeof types === 'object') {
  400. for (var type in types) {
  401. this._off(type, types[type], fn);
  402. }
  403. } else {
  404. types = splitWords(types);
  405. for (var i = 0, len = types.length; i < len; i++) {
  406. this._off(types[i], fn, context);
  407. }
  408. }
  409. return this;
  410. },
  411. // attach listener (without syntactic sugar now)
  412. _on: function (type, fn, context) {
  413. this._events = this._events || {};
  414. /* get/init listeners for type */
  415. var typeListeners = this._events[type];
  416. if (!typeListeners) {
  417. typeListeners = [];
  418. this._events[type] = typeListeners;
  419. }
  420. if (context === this) {
  421. // Less memory footprint.
  422. context = undefined;
  423. }
  424. var newListener = {fn: fn, ctx: context},
  425. listeners = typeListeners;
  426. // check if fn already there
  427. for (var i = 0, len = listeners.length; i < len; i++) {
  428. if (listeners[i].fn === fn && listeners[i].ctx === context) {
  429. return;
  430. }
  431. }
  432. listeners.push(newListener);
  433. },
  434. _off: function (type, fn, context) {
  435. var listeners,
  436. i,
  437. len;
  438. if (!this._events) { return; }
  439. listeners = this._events[type];
  440. if (!listeners) {
  441. return;
  442. }
  443. if (!fn) {
  444. // Set all removed listeners to noop so they are not called if remove happens in fire
  445. for (i = 0, len = listeners.length; i < len; i++) {
  446. listeners[i].fn = falseFn;
  447. }
  448. // clear all listeners for a type if function isn't specified
  449. delete this._events[type];
  450. return;
  451. }
  452. if (context === this) {
  453. context = undefined;
  454. }
  455. if (listeners) {
  456. // find fn and remove it
  457. for (i = 0, len = listeners.length; i < len; i++) {
  458. var l = listeners[i];
  459. if (l.ctx !== context) { continue; }
  460. if (l.fn === fn) {
  461. // set the removed listener to noop so that's not called if remove happens in fire
  462. l.fn = falseFn;
  463. if (this._firingCount) {
  464. /* copy array in case events are being fired */
  465. this._events[type] = listeners = listeners.slice();
  466. }
  467. listeners.splice(i, 1);
  468. return;
  469. }
  470. }
  471. }
  472. },
  473. // @method fire(type: String, data?: Object, propagate?: Boolean): this
  474. // Fires an event of the specified type. You can optionally provide an data
  475. // object — the first argument of the listener function will contain its
  476. // properties. The event can optionally be propagated to event parents.
  477. fire: function (type, data, propagate) {
  478. if (!this.listens(type, propagate)) { return this; }
  479. var event = extend({}, data, {
  480. type: type,
  481. target: this,
  482. sourceTarget: data && data.sourceTarget || this
  483. });
  484. if (this._events) {
  485. var listeners = this._events[type];
  486. if (listeners) {
  487. this._firingCount = (this._firingCount + 1) || 1;
  488. for (var i = 0, len = listeners.length; i < len; i++) {
  489. var l = listeners[i];
  490. l.fn.call(l.ctx || this, event);
  491. }
  492. this._firingCount--;
  493. }
  494. }
  495. if (propagate) {
  496. // propagate the event to parents (set with addEventParent)
  497. this._propagateEvent(event);
  498. }
  499. return this;
  500. },
  501. // @method listens(type: String): Boolean
  502. // Returns `true` if a particular event type has any listeners attached to it.
  503. listens: function (type, propagate) {
  504. var listeners = this._events && this._events[type];
  505. if (listeners && listeners.length) { return true; }
  506. if (propagate) {
  507. // also check parents for listeners if event propagates
  508. for (var id in this._eventParents) {
  509. if (this._eventParents[id].listens(type, propagate)) { return true; }
  510. }
  511. }
  512. return false;
  513. },
  514. // @method once(…): this
  515. // Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed.
  516. once: function (types, fn, context) {
  517. if (typeof types === 'object') {
  518. for (var type in types) {
  519. this.once(type, types[type], fn);
  520. }
  521. return this;
  522. }
  523. var handler = bind(function () {
  524. this
  525. .off(types, fn, context)
  526. .off(types, handler, context);
  527. }, this);
  528. // add a listener that's executed once and removed after that
  529. return this
  530. .on(types, fn, context)
  531. .on(types, handler, context);
  532. },
  533. // @method addEventParent(obj: Evented): this
  534. // Adds an event parent - an `Evented` that will receive propagated events
  535. addEventParent: function (obj) {
  536. this._eventParents = this._eventParents || {};
  537. this._eventParents[stamp(obj)] = obj;
  538. return this;
  539. },
  540. // @method removeEventParent(obj: Evented): this
  541. // Removes an event parent, so it will stop receiving propagated events
  542. removeEventParent: function (obj) {
  543. if (this._eventParents) {
  544. delete this._eventParents[stamp(obj)];
  545. }
  546. return this;
  547. },
  548. _propagateEvent: function (e) {
  549. for (var id in this._eventParents) {
  550. this._eventParents[id].fire(e.type, extend({
  551. layer: e.target,
  552. propagatedFrom: e.target
  553. }, e), true);
  554. }
  555. }
  556. };
  557. // aliases; we should ditch those eventually
  558. // @method addEventListener(…): this
  559. // Alias to [`on(…)`](#evented-on)
  560. Events.addEventListener = Events.on;
  561. // @method removeEventListener(…): this
  562. // Alias to [`off(…)`](#evented-off)
  563. // @method clearAllEventListeners(…): this
  564. // Alias to [`off()`](#evented-off)
  565. Events.removeEventListener = Events.clearAllEventListeners = Events.off;
  566. // @method addOneTimeEventListener(…): this
  567. // Alias to [`once(…)`](#evented-once)
  568. Events.addOneTimeEventListener = Events.once;
  569. // @method fireEvent(…): this
  570. // Alias to [`fire(…)`](#evented-fire)
  571. Events.fireEvent = Events.fire;
  572. // @method hasEventListeners(…): Boolean
  573. // Alias to [`listens(…)`](#evented-listens)
  574. Events.hasEventListeners = Events.listens;
  575. var Evented = Class.extend(Events);
  576. /*
  577. * @class Point
  578. * @aka L.Point
  579. *
  580. * Represents a point with `x` and `y` coordinates in pixels.
  581. *
  582. * @example
  583. *
  584. * ```js
  585. * var point = L.point(200, 300);
  586. * ```
  587. *
  588. * 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:
  589. *
  590. * ```js
  591. * map.panBy([200, 300]);
  592. * map.panBy(L.point(200, 300));
  593. * ```
  594. *
  595. * Note that `Point` does not inherit from Leafet's `Class` object,
  596. * which means new classes can't inherit from it, and new methods
  597. * can't be added to it with the `include` function.
  598. */
  599. function Point(x, y, round) {
  600. // @property x: Number; The `x` coordinate of the point
  601. this.x = (round ? Math.round(x) : x);
  602. // @property y: Number; The `y` coordinate of the point
  603. this.y = (round ? Math.round(y) : y);
  604. }
  605. var trunc = Math.trunc || function (v) {
  606. return v > 0 ? Math.floor(v) : Math.ceil(v);
  607. };
  608. Point.prototype = {
  609. // @method clone(): Point
  610. // Returns a copy of the current point.
  611. clone: function () {
  612. return new Point(this.x, this.y);
  613. },
  614. // @method add(otherPoint: Point): Point
  615. // Returns the result of addition of the current and the given points.
  616. add: function (point) {
  617. // non-destructive, returns a new point
  618. return this.clone()._add(toPoint(point));
  619. },
  620. _add: function (point) {
  621. // destructive, used directly for performance in situations where it's safe to modify existing point
  622. this.x += point.x;
  623. this.y += point.y;
  624. return this;
  625. },
  626. // @method subtract(otherPoint: Point): Point
  627. // Returns the result of subtraction of the given point from the current.
  628. subtract: function (point) {
  629. return this.clone()._subtract(toPoint(point));
  630. },
  631. _subtract: function (point) {
  632. this.x -= point.x;
  633. this.y -= point.y;
  634. return this;
  635. },
  636. // @method divideBy(num: Number): Point
  637. // Returns the result of division of the current point by the given number.
  638. divideBy: function (num) {
  639. return this.clone()._divideBy(num);
  640. },
  641. _divideBy: function (num) {
  642. this.x /= num;
  643. this.y /= num;
  644. return this;
  645. },
  646. // @method multiplyBy(num: Number): Point
  647. // Returns the result of multiplication of the current point by the given number.
  648. multiplyBy: function (num) {
  649. return this.clone()._multiplyBy(num);
  650. },
  651. _multiplyBy: function (num) {
  652. this.x *= num;
  653. this.y *= num;
  654. return this;
  655. },
  656. // @method scaleBy(scale: Point): Point
  657. // Multiply each coordinate of the current point by each coordinate of
  658. // `scale`. In linear algebra terms, multiply the point by the
  659. // [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation)
  660. // defined by `scale`.
  661. scaleBy: function (point) {
  662. return new Point(this.x * point.x, this.y * point.y);
  663. },
  664. // @method unscaleBy(scale: Point): Point
  665. // Inverse of `scaleBy`. Divide each coordinate of the current point by
  666. // each coordinate of `scale`.
  667. unscaleBy: function (point) {
  668. return new Point(this.x / point.x, this.y / point.y);
  669. },
  670. // @method round(): Point
  671. // Returns a copy of the current point with rounded coordinates.
  672. round: function () {
  673. return this.clone()._round();
  674. },
  675. _round: function () {
  676. this.x = Math.round(this.x);
  677. this.y = Math.round(this.y);
  678. return this;
  679. },
  680. // @method floor(): Point
  681. // Returns a copy of the current point with floored coordinates (rounded down).
  682. floor: function () {
  683. return this.clone()._floor();
  684. },
  685. _floor: function () {
  686. this.x = Math.floor(this.x);
  687. this.y = Math.floor(this.y);
  688. return this;
  689. },
  690. // @method ceil(): Point
  691. // Returns a copy of the current point with ceiled coordinates (rounded up).
  692. ceil: function () {
  693. return this.clone()._ceil();
  694. },
  695. _ceil: function () {
  696. this.x = Math.ceil(this.x);
  697. this.y = Math.ceil(this.y);
  698. return this;
  699. },
  700. // @method trunc(): Point
  701. // Returns a copy of the current point with truncated coordinates (rounded towards zero).
  702. trunc: function () {
  703. return this.clone()._trunc();
  704. },
  705. _trunc: function () {
  706. this.x = trunc(this.x);
  707. this.y = trunc(this.y);
  708. return this;
  709. },
  710. // @method distanceTo(otherPoint: Point): Number
  711. // Returns the cartesian distance between the current and the given points.
  712. distanceTo: function (point) {
  713. point = toPoint(point);
  714. var x = point.x - this.x,
  715. y = point.y - this.y;
  716. return Math.sqrt(x * x + y * y);
  717. },
  718. // @method equals(otherPoint: Point): Boolean
  719. // Returns `true` if the given point has the same coordinates.
  720. equals: function (point) {
  721. point = toPoint(point);
  722. return point.x === this.x &&
  723. point.y === this.y;
  724. },
  725. // @method contains(otherPoint: Point): Boolean
  726. // Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).
  727. contains: function (point) {
  728. point = toPoint(point);
  729. return Math.abs(point.x) <= Math.abs(this.x) &&
  730. Math.abs(point.y) <= Math.abs(this.y);
  731. },
  732. // @method toString(): String
  733. // Returns a string representation of the point for debugging purposes.
  734. toString: function () {
  735. return 'Point(' +
  736. formatNum(this.x) + ', ' +
  737. formatNum(this.y) + ')';
  738. }
  739. };
  740. // @factory L.point(x: Number, y: Number, round?: Boolean)
  741. // Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values.
  742. // @alternative
  743. // @factory L.point(coords: Number[])
  744. // Expects an array of the form `[x, y]` instead.
  745. // @alternative
  746. // @factory L.point(coords: Object)
  747. // Expects a plain object of the form `{x: Number, y: Number}` instead.
  748. function toPoint(x, y, round) {
  749. if (x instanceof Point) {
  750. return x;
  751. }
  752. if (isArray(x)) {
  753. return new Point(x[0], x[1]);
  754. }
  755. if (x === undefined || x === null) {
  756. return x;
  757. }
  758. if (typeof x === 'object' && 'x' in x && 'y' in x) {
  759. return new Point(x.x, x.y);
  760. }
  761. return new Point(x, y, round);
  762. }
  763. /*
  764. * @class Bounds
  765. * @aka L.Bounds
  766. *
  767. * Represents a rectangular area in pixel coordinates.
  768. *
  769. * @example
  770. *
  771. * ```js
  772. * var p1 = L.point(10, 10),
  773. * p2 = L.point(40, 60),
  774. * bounds = L.bounds(p1, p2);
  775. * ```
  776. *
  777. * 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:
  778. *
  779. * ```js
  780. * otherBounds.intersects([[10, 10], [40, 60]]);
  781. * ```
  782. *
  783. * Note that `Bounds` does not inherit from Leafet's `Class` object,
  784. * which means new classes can't inherit from it, and new methods
  785. * can't be added to it with the `include` function.
  786. */
  787. function Bounds(a, b) {
  788. if (!a) { return; }
  789. var points = b ? [a, b] : a;
  790. for (var i = 0, len = points.length; i < len; i++) {
  791. this.extend(points[i]);
  792. }
  793. }
  794. Bounds.prototype = {
  795. // @method extend(point: Point): this
  796. // Extends the bounds to contain the given point.
  797. extend: function (point) { // (Point)
  798. point = toPoint(point);
  799. // @property min: Point
  800. // The top left corner of the rectangle.
  801. // @property max: Point
  802. // The bottom right corner of the rectangle.
  803. if (!this.min && !this.max) {
  804. this.min = point.clone();
  805. this.max = point.clone();
  806. } else {
  807. this.min.x = Math.min(point.x, this.min.x);
  808. this.max.x = Math.max(point.x, this.max.x);
  809. this.min.y = Math.min(point.y, this.min.y);
  810. this.max.y = Math.max(point.y, this.max.y);
  811. }
  812. return this;
  813. },
  814. // @method getCenter(round?: Boolean): Point
  815. // Returns the center point of the bounds.
  816. getCenter: function (round) {
  817. return new Point(
  818. (this.min.x + this.max.x) / 2,
  819. (this.min.y + this.max.y) / 2, round);
  820. },
  821. // @method getBottomLeft(): Point
  822. // Returns the bottom-left point of the bounds.
  823. getBottomLeft: function () {
  824. return new Point(this.min.x, this.max.y);
  825. },
  826. // @method getTopRight(): Point
  827. // Returns the top-right point of the bounds.
  828. getTopRight: function () { // -> Point
  829. return new Point(this.max.x, this.min.y);
  830. },
  831. // @method getTopLeft(): Point
  832. // Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)).
  833. getTopLeft: function () {
  834. return this.min; // left, top
  835. },
  836. // @method getBottomRight(): Point
  837. // Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)).
  838. getBottomRight: function () {
  839. return this.max; // right, bottom
  840. },
  841. // @method getSize(): Point
  842. // Returns the size of the given bounds
  843. getSize: function () {
  844. return this.max.subtract(this.min);
  845. },
  846. // @method contains(otherBounds: Bounds): Boolean
  847. // Returns `true` if the rectangle contains the given one.
  848. // @alternative
  849. // @method contains(point: Point): Boolean
  850. // Returns `true` if the rectangle contains the given point.
  851. contains: function (obj) {
  852. var min, max;
  853. if (typeof obj[0] === 'number' || obj instanceof Point) {
  854. obj = toPoint(obj);
  855. } else {
  856. obj = toBounds(obj);
  857. }
  858. if (obj instanceof Bounds) {
  859. min = obj.min;
  860. max = obj.max;
  861. } else {
  862. min = max = obj;
  863. }
  864. return (min.x >= this.min.x) &&
  865. (max.x <= this.max.x) &&
  866. (min.y >= this.min.y) &&
  867. (max.y <= this.max.y);
  868. },
  869. // @method intersects(otherBounds: Bounds): Boolean
  870. // Returns `true` if the rectangle intersects the given bounds. Two bounds
  871. // intersect if they have at least one point in common.
  872. intersects: function (bounds) { // (Bounds) -> Boolean
  873. bounds = toBounds(bounds);
  874. var min = this.min,
  875. max = this.max,
  876. min2 = bounds.min,
  877. max2 = bounds.max,
  878. xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
  879. yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
  880. return xIntersects && yIntersects;
  881. },
  882. // @method overlaps(otherBounds: Bounds): Boolean
  883. // Returns `true` if the rectangle overlaps the given bounds. Two bounds
  884. // overlap if their intersection is an area.
  885. overlaps: function (bounds) { // (Bounds) -> Boolean
  886. bounds = toBounds(bounds);
  887. var min = this.min,
  888. max = this.max,
  889. min2 = bounds.min,
  890. max2 = bounds.max,
  891. xOverlaps = (max2.x > min.x) && (min2.x < max.x),
  892. yOverlaps = (max2.y > min.y) && (min2.y < max.y);
  893. return xOverlaps && yOverlaps;
  894. },
  895. isValid: function () {
  896. return !!(this.min && this.max);
  897. }
  898. };
  899. // @factory L.bounds(corner1: Point, corner2: Point)
  900. // Creates a Bounds object from two corners coordinate pairs.
  901. // @alternative
  902. // @factory L.bounds(points: Point[])
  903. // Creates a Bounds object from the given array of points.
  904. function toBounds(a, b) {
  905. if (!a || a instanceof Bounds) {
  906. return a;
  907. }
  908. return new Bounds(a, b);
  909. }
  910. /*
  911. * @class LatLngBounds
  912. * @aka L.LatLngBounds
  913. *
  914. * Represents a rectangular geographical area on a map.
  915. *
  916. * @example
  917. *
  918. * ```js
  919. * var corner1 = L.latLng(40.712, -74.227),
  920. * corner2 = L.latLng(40.774, -74.125),
  921. * bounds = L.latLngBounds(corner1, corner2);
  922. * ```
  923. *
  924. * 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:
  925. *
  926. * ```js
  927. * map.fitBounds([
  928. * [40.712, -74.227],
  929. * [40.774, -74.125]
  930. * ]);
  931. * ```
  932. *
  933. * 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.
  934. *
  935. * Note that `LatLngBounds` does not inherit from Leafet's `Class` object,
  936. * which means new classes can't inherit from it, and new methods
  937. * can't be added to it with the `include` function.
  938. */
  939. function LatLngBounds(corner1, corner2) { // (LatLng, LatLng) or (LatLng[])
  940. if (!corner1) { return; }
  941. var latlngs = corner2 ? [corner1, corner2] : corner1;
  942. for (var i = 0, len = latlngs.length; i < len; i++) {
  943. this.extend(latlngs[i]);
  944. }
  945. }
  946. LatLngBounds.prototype = {
  947. // @method extend(latlng: LatLng): this
  948. // Extend the bounds to contain the given point
  949. // @alternative
  950. // @method extend(otherBounds: LatLngBounds): this
  951. // Extend the bounds to contain the given bounds
  952. extend: function (obj) {
  953. var sw = this._southWest,
  954. ne = this._northEast,
  955. sw2, ne2;
  956. if (obj instanceof LatLng) {
  957. sw2 = obj;
  958. ne2 = obj;
  959. } else if (obj instanceof LatLngBounds) {
  960. sw2 = obj._southWest;
  961. ne2 = obj._northEast;
  962. if (!sw2 || !ne2) { return this; }
  963. } else {
  964. return obj ? this.extend(toLatLng(obj) || toLatLngBounds(obj)) : this;
  965. }
  966. if (!sw && !ne) {
  967. this._southWest = new LatLng(sw2.lat, sw2.lng);
  968. this._northEast = new LatLng(ne2.lat, ne2.lng);
  969. } else {
  970. sw.lat = Math.min(sw2.lat, sw.lat);
  971. sw.lng = Math.min(sw2.lng, sw.lng);
  972. ne.lat = Math.max(ne2.lat, ne.lat);
  973. ne.lng = Math.max(ne2.lng, ne.lng);
  974. }
  975. return this;
  976. },
  977. // @method pad(bufferRatio: Number): LatLngBounds
  978. // Returns bounds created by extending or retracting the current bounds by a given ratio in each direction.
  979. // For example, a ratio of 0.5 extends the bounds by 50% in each direction.
  980. // Negative values will retract the bounds.
  981. pad: function (bufferRatio) {
  982. var sw = this._southWest,
  983. ne = this._northEast,
  984. heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
  985. widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
  986. return new LatLngBounds(
  987. new LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
  988. new LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
  989. },
  990. // @method getCenter(): LatLng
  991. // Returns the center point of the bounds.
  992. getCenter: function () {
  993. return new LatLng(
  994. (this._southWest.lat + this._northEast.lat) / 2,
  995. (this._southWest.lng + this._northEast.lng) / 2);
  996. },
  997. // @method getSouthWest(): LatLng
  998. // Returns the south-west point of the bounds.
  999. getSouthWest: function () {
  1000. return this._southWest;
  1001. },
  1002. // @method getNorthEast(): LatLng
  1003. // Returns the north-east point of the bounds.
  1004. getNorthEast: function () {
  1005. return this._northEast;
  1006. },
  1007. // @method getNorthWest(): LatLng
  1008. // Returns the north-west point of the bounds.
  1009. getNorthWest: function () {
  1010. return new LatLng(this.getNorth(), this.getWest());
  1011. },
  1012. // @method getSouthEast(): LatLng
  1013. // Returns the south-east point of the bounds.
  1014. getSouthEast: function () {
  1015. return new LatLng(this.getSouth(), this.getEast());
  1016. },
  1017. // @method getWest(): Number
  1018. // Returns the west longitude of the bounds
  1019. getWest: function () {
  1020. return this._southWest.lng;
  1021. },
  1022. // @method getSouth(): Number
  1023. // Returns the south latitude of the bounds
  1024. getSouth: function () {
  1025. return this._southWest.lat;
  1026. },
  1027. // @method getEast(): Number
  1028. // Returns the east longitude of the bounds
  1029. getEast: function () {
  1030. return this._northEast.lng;
  1031. },
  1032. // @method getNorth(): Number
  1033. // Returns the north latitude of the bounds
  1034. getNorth: function () {
  1035. return this._northEast.lat;
  1036. },
  1037. // @method contains(otherBounds: LatLngBounds): Boolean
  1038. // Returns `true` if the rectangle contains the given one.
  1039. // @alternative
  1040. // @method contains (latlng: LatLng): Boolean
  1041. // Returns `true` if the rectangle contains the given point.
  1042. contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
  1043. if (typeof obj[0] === 'number' || obj instanceof LatLng || 'lat' in obj) {
  1044. obj = toLatLng(obj);
  1045. } else {
  1046. obj = toLatLngBounds(obj);
  1047. }
  1048. var sw = this._southWest,
  1049. ne = this._northEast,
  1050. sw2, ne2;
  1051. if (obj instanceof LatLngBounds) {
  1052. sw2 = obj.getSouthWest();
  1053. ne2 = obj.getNorthEast();
  1054. } else {
  1055. sw2 = ne2 = obj;
  1056. }
  1057. return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
  1058. (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
  1059. },
  1060. // @method intersects(otherBounds: LatLngBounds): Boolean
  1061. // Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.
  1062. intersects: function (bounds) {
  1063. bounds = toLatLngBounds(bounds);
  1064. var sw = this._southWest,
  1065. ne = this._northEast,
  1066. sw2 = bounds.getSouthWest(),
  1067. ne2 = bounds.getNorthEast(),
  1068. latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
  1069. lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
  1070. return latIntersects && lngIntersects;
  1071. },
  1072. // @method overlaps(otherBounds: Bounds): Boolean
  1073. // Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.
  1074. overlaps: function (bounds) {
  1075. bounds = toLatLngBounds(bounds);
  1076. var sw = this._southWest,
  1077. ne = this._northEast,
  1078. sw2 = bounds.getSouthWest(),
  1079. ne2 = bounds.getNorthEast(),
  1080. latOverlaps = (ne2.lat > sw.lat) && (sw2.lat < ne.lat),
  1081. lngOverlaps = (ne2.lng > sw.lng) && (sw2.lng < ne.lng);
  1082. return latOverlaps && lngOverlaps;
  1083. },
  1084. // @method toBBoxString(): String
  1085. // 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.
  1086. toBBoxString: function () {
  1087. return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
  1088. },
  1089. // @method equals(otherBounds: LatLngBounds, maxMargin?: Number): Boolean
  1090. // 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.
  1091. equals: function (bounds, maxMargin) {
  1092. if (!bounds) { return false; }
  1093. bounds = toLatLngBounds(bounds);
  1094. return this._southWest.equals(bounds.getSouthWest(), maxMargin) &&
  1095. this._northEast.equals(bounds.getNorthEast(), maxMargin);
  1096. },
  1097. // @method isValid(): Boolean
  1098. // Returns `true` if the bounds are properly initialized.
  1099. isValid: function () {
  1100. return !!(this._southWest && this._northEast);
  1101. }
  1102. };
  1103. // TODO International date line?
  1104. // @factory L.latLngBounds(corner1: LatLng, corner2: LatLng)
  1105. // Creates a `LatLngBounds` object by defining two diagonally opposite corners of the rectangle.
  1106. // @alternative
  1107. // @factory L.latLngBounds(latlngs: LatLng[])
  1108. // 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).
  1109. function toLatLngBounds(a, b) {
  1110. if (a instanceof LatLngBounds) {
  1111. return a;
  1112. }
  1113. return new LatLngBounds(a, b);
  1114. }
  1115. /* @class LatLng
  1116. * @aka L.LatLng
  1117. *
  1118. * Represents a geographical point with a certain latitude and longitude.
  1119. *
  1120. * @example
  1121. *
  1122. * ```
  1123. * var latlng = L.latLng(50.5, 30.5);
  1124. * ```
  1125. *
  1126. * 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:
  1127. *
  1128. * ```
  1129. * map.panTo([50, 30]);
  1130. * map.panTo({lon: 30, lat: 50});
  1131. * map.panTo({lat: 50, lng: 30});
  1132. * map.panTo(L.latLng(50, 30));
  1133. * ```
  1134. *
  1135. * Note that `LatLng` does not inherit from Leafet's `Class` object,
  1136. * which means new classes can't inherit from it, and new methods
  1137. * can't be added to it with the `include` function.
  1138. */
  1139. function LatLng(lat, lng, alt) {
  1140. if (isNaN(lat) || isNaN(lng)) {
  1141. throw new Error('Invalid LatLng object: (' + lat + ', ' + lng + ')');
  1142. }
  1143. // @property lat: Number
  1144. // Latitude in degrees
  1145. this.lat = +lat;
  1146. // @property lng: Number
  1147. // Longitude in degrees
  1148. this.lng = +lng;
  1149. // @property alt: Number
  1150. // Altitude in meters (optional)
  1151. if (alt !== undefined) {
  1152. this.alt = +alt;
  1153. }
  1154. }
  1155. LatLng.prototype = {
  1156. // @method equals(otherLatLng: LatLng, maxMargin?: Number): Boolean
  1157. // 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.
  1158. equals: function (obj, maxMargin) {
  1159. if (!obj) { return false; }
  1160. obj = toLatLng(obj);
  1161. var margin = Math.max(
  1162. Math.abs(this.lat - obj.lat),
  1163. Math.abs(this.lng - obj.lng));
  1164. return margin <= (maxMargin === undefined ? 1.0E-9 : maxMargin);
  1165. },
  1166. // @method toString(): String
  1167. // Returns a string representation of the point (for debugging purposes).
  1168. toString: function (precision) {
  1169. return 'LatLng(' +
  1170. formatNum(this.lat, precision) + ', ' +
  1171. formatNum(this.lng, precision) + ')';
  1172. },
  1173. // @method distanceTo(otherLatLng: LatLng): Number
  1174. // 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).
  1175. distanceTo: function (other) {
  1176. return Earth.distance(this, toLatLng(other));
  1177. },
  1178. // @method wrap(): LatLng
  1179. // Returns a new `LatLng` object with the longitude wrapped so it's always between -180 and +180 degrees.
  1180. wrap: function () {
  1181. return Earth.wrapLatLng(this);
  1182. },
  1183. // @method toBounds(sizeInMeters: Number): LatLngBounds
  1184. // Returns a new `LatLngBounds` object in which each boundary is `sizeInMeters/2` meters apart from the `LatLng`.
  1185. toBounds: function (sizeInMeters) {
  1186. var latAccuracy = 180 * sizeInMeters / 40075017,
  1187. lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);
  1188. return toLatLngBounds(
  1189. [this.lat - latAccuracy, this.lng - lngAccuracy],
  1190. [this.lat + latAccuracy, this.lng + lngAccuracy]);
  1191. },
  1192. clone: function () {
  1193. return new LatLng(this.lat, this.lng, this.alt);
  1194. }
  1195. };
  1196. // @factory L.latLng(latitude: Number, longitude: Number, altitude?: Number): LatLng
  1197. // Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude).
  1198. // @alternative
  1199. // @factory L.latLng(coords: Array): LatLng
  1200. // Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead.
  1201. // @alternative
  1202. // @factory L.latLng(coords: Object): LatLng
  1203. // Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead.
  1204. function toLatLng(a, b, c) {
  1205. if (a instanceof LatLng) {
  1206. return a;
  1207. }
  1208. if (isArray(a) && typeof a[0] !== 'object') {
  1209. if (a.length === 3) {
  1210. return new LatLng(a[0], a[1], a[2]);
  1211. }
  1212. if (a.length === 2) {
  1213. return new LatLng(a[0], a[1]);
  1214. }
  1215. return null;
  1216. }
  1217. if (a === undefined || a === null) {
  1218. return a;
  1219. }
  1220. if (typeof a === 'object' && 'lat' in a) {
  1221. return new LatLng(a.lat, 'lng' in a ? a.lng : a.lon, a.alt);
  1222. }
  1223. if (b === undefined) {
  1224. return null;
  1225. }
  1226. return new LatLng(a, b, c);
  1227. }
  1228. /*
  1229. * @namespace CRS
  1230. * @crs L.CRS.Base
  1231. * Object that defines coordinate reference systems for projecting
  1232. * geographical points into pixel (screen) coordinates and back (and to
  1233. * coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See
  1234. * [spatial reference system](http://en.wikipedia.org/wiki/Coordinate_reference_system).
  1235. *
  1236. * Leaflet defines the most usual CRSs by default. If you want to use a
  1237. * CRS not defined by default, take a look at the
  1238. * [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin.
  1239. *
  1240. * Note that the CRS instances do not inherit from Leafet's `Class` object,
  1241. * and can't be instantiated. Also, new classes can't inherit from them,
  1242. * and methods can't be added to them with the `include` function.
  1243. */
  1244. var CRS = {
  1245. // @method latLngToPoint(latlng: LatLng, zoom: Number): Point
  1246. // Projects geographical coordinates into pixel coordinates for a given zoom.
  1247. latLngToPoint: function (latlng, zoom) {
  1248. var projectedPoint = this.projection.project(latlng),
  1249. scale = this.scale(zoom);
  1250. return this.transformation._transform(projectedPoint, scale);
  1251. },
  1252. // @method pointToLatLng(point: Point, zoom: Number): LatLng
  1253. // The inverse of `latLngToPoint`. Projects pixel coordinates on a given
  1254. // zoom into geographical coordinates.
  1255. pointToLatLng: function (point, zoom) {
  1256. var scale = this.scale(zoom),
  1257. untransformedPoint = this.transformation.untransform(point, scale);
  1258. return this.projection.unproject(untransformedPoint);
  1259. },
  1260. // @method project(latlng: LatLng): Point
  1261. // Projects geographical coordinates into coordinates in units accepted for
  1262. // this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).
  1263. project: function (latlng) {
  1264. return this.projection.project(latlng);
  1265. },
  1266. // @method unproject(point: Point): LatLng
  1267. // Given a projected coordinate returns the corresponding LatLng.
  1268. // The inverse of `project`.
  1269. unproject: function (point) {
  1270. return this.projection.unproject(point);
  1271. },
  1272. // @method scale(zoom: Number): Number
  1273. // Returns the scale used when transforming projected coordinates into
  1274. // pixel coordinates for a particular zoom. For example, it returns
  1275. // `256 * 2^zoom` for Mercator-based CRS.
  1276. scale: function (zoom) {
  1277. return 256 * Math.pow(2, zoom);
  1278. },
  1279. // @method zoom(scale: Number): Number
  1280. // Inverse of `scale()`, returns the zoom level corresponding to a scale
  1281. // factor of `scale`.
  1282. zoom: function (scale) {
  1283. return Math.log(scale / 256) / Math.LN2;
  1284. },
  1285. // @method getProjectedBounds(zoom: Number): Bounds
  1286. // Returns the projection's bounds scaled and transformed for the provided `zoom`.
  1287. getProjectedBounds: function (zoom) {
  1288. if (this.infinite) { return null; }
  1289. var b = this.projection.bounds,
  1290. s = this.scale(zoom),
  1291. min = this.transformation.transform(b.min, s),
  1292. max = this.transformation.transform(b.max, s);
  1293. return new Bounds(min, max);
  1294. },
  1295. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  1296. // Returns the distance between two geographical coordinates.
  1297. // @property code: String
  1298. // Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`)
  1299. //
  1300. // @property wrapLng: Number[]
  1301. // An array of two numbers defining whether the longitude (horizontal) coordinate
  1302. // axis wraps around a given range and how. Defaults to `[-180, 180]` in most
  1303. // geographical CRSs. If `undefined`, the longitude axis does not wrap around.
  1304. //
  1305. // @property wrapLat: Number[]
  1306. // Like `wrapLng`, but for the latitude (vertical) axis.
  1307. // wrapLng: [min, max],
  1308. // wrapLat: [min, max],
  1309. // @property infinite: Boolean
  1310. // If true, the coordinate space will be unbounded (infinite in both axes)
  1311. infinite: false,
  1312. // @method wrapLatLng(latlng: LatLng): LatLng
  1313. // Returns a `LatLng` where lat and lng has been wrapped according to the
  1314. // CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds.
  1315. wrapLatLng: function (latlng) {
  1316. var lng = this.wrapLng ? wrapNum(latlng.lng, this.wrapLng, true) : latlng.lng,
  1317. lat = this.wrapLat ? wrapNum(latlng.lat, this.wrapLat, true) : latlng.lat,
  1318. alt = latlng.alt;
  1319. return new LatLng(lat, lng, alt);
  1320. },
  1321. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  1322. // Returns a `LatLngBounds` with the same size as the given one, ensuring
  1323. // that its center is within the CRS's bounds.
  1324. // Only accepts actual `L.LatLngBounds` instances, not arrays.
  1325. wrapLatLngBounds: function (bounds) {
  1326. var center = bounds.getCenter(),
  1327. newCenter = this.wrapLatLng(center),
  1328. latShift = center.lat - newCenter.lat,
  1329. lngShift = center.lng - newCenter.lng;
  1330. if (latShift === 0 && lngShift === 0) {
  1331. return bounds;
  1332. }
  1333. var sw = bounds.getSouthWest(),
  1334. ne = bounds.getNorthEast(),
  1335. newSw = new LatLng(sw.lat - latShift, sw.lng - lngShift),
  1336. newNe = new LatLng(ne.lat - latShift, ne.lng - lngShift);
  1337. return new LatLngBounds(newSw, newNe);
  1338. }
  1339. };
  1340. /*
  1341. * @namespace CRS
  1342. * @crs L.CRS.Earth
  1343. *
  1344. * Serves as the base for CRS that are global such that they cover the earth.
  1345. * Can only be used as the base for other CRS and cannot be used directly,
  1346. * since it does not have a `code`, `projection` or `transformation`. `distance()` returns
  1347. * meters.
  1348. */
  1349. var Earth = extend({}, CRS, {
  1350. wrapLng: [-180, 180],
  1351. // Mean Earth Radius, as recommended for use by
  1352. // the International Union of Geodesy and Geophysics,
  1353. // see http://rosettacode.org/wiki/Haversine_formula
  1354. R: 6371000,
  1355. // distance between two geographical points using spherical law of cosines approximation
  1356. distance: function (latlng1, latlng2) {
  1357. var rad = Math.PI / 180,
  1358. lat1 = latlng1.lat * rad,
  1359. lat2 = latlng2.lat * rad,
  1360. sinDLat = Math.sin((latlng2.lat - latlng1.lat) * rad / 2),
  1361. sinDLon = Math.sin((latlng2.lng - latlng1.lng) * rad / 2),
  1362. a = sinDLat * sinDLat + Math.cos(lat1) * Math.cos(lat2) * sinDLon * sinDLon,
  1363. c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1364. return this.R * c;
  1365. }
  1366. });
  1367. /*
  1368. * @namespace Projection
  1369. * @projection L.Projection.SphericalMercator
  1370. *
  1371. * Spherical Mercator projection — the most common projection for online maps,
  1372. * used by almost all free and commercial tile providers. Assumes that Earth is
  1373. * a sphere. Used by the `EPSG:3857` CRS.
  1374. */
  1375. var SphericalMercator = {
  1376. R: 6378137,
  1377. MAX_LATITUDE: 85.0511287798,
  1378. project: function (latlng) {
  1379. var d = Math.PI / 180,
  1380. max = this.MAX_LATITUDE,
  1381. lat = Math.max(Math.min(max, latlng.lat), -max),
  1382. sin = Math.sin(lat * d);
  1383. return new Point(
  1384. this.R * latlng.lng * d,
  1385. this.R * Math.log((1 + sin) / (1 - sin)) / 2);
  1386. },
  1387. unproject: function (point) {
  1388. var d = 180 / Math.PI;
  1389. return new LatLng(
  1390. (2 * Math.atan(Math.exp(point.y / this.R)) - (Math.PI / 2)) * d,
  1391. point.x * d / this.R);
  1392. },
  1393. bounds: (function () {
  1394. var d = 6378137 * Math.PI;
  1395. return new Bounds([-d, -d], [d, d]);
  1396. })()
  1397. };
  1398. /*
  1399. * @class Transformation
  1400. * @aka L.Transformation
  1401. *
  1402. * Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d`
  1403. * for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing
  1404. * the reverse. Used by Leaflet in its projections code.
  1405. *
  1406. * @example
  1407. *
  1408. * ```js
  1409. * var transformation = L.transformation(2, 5, -1, 10),
  1410. * p = L.point(1, 2),
  1411. * p2 = transformation.transform(p), // L.point(7, 8)
  1412. * p3 = transformation.untransform(p2); // L.point(1, 2)
  1413. * ```
  1414. */
  1415. // factory new L.Transformation(a: Number, b: Number, c: Number, d: Number)
  1416. // Creates a `Transformation` object with the given coefficients.
  1417. function Transformation(a, b, c, d) {
  1418. if (isArray(a)) {
  1419. // use array properties
  1420. this._a = a[0];
  1421. this._b = a[1];
  1422. this._c = a[2];
  1423. this._d = a[3];
  1424. return;
  1425. }
  1426. this._a = a;
  1427. this._b = b;
  1428. this._c = c;
  1429. this._d = d;
  1430. }
  1431. Transformation.prototype = {
  1432. // @method transform(point: Point, scale?: Number): Point
  1433. // Returns a transformed point, optionally multiplied by the given scale.
  1434. // Only accepts actual `L.Point` instances, not arrays.
  1435. transform: function (point, scale) { // (Point, Number) -> Point
  1436. return this._transform(point.clone(), scale);
  1437. },
  1438. // destructive transform (faster)
  1439. _transform: function (point, scale) {
  1440. scale = scale || 1;
  1441. point.x = scale * (this._a * point.x + this._b);
  1442. point.y = scale * (this._c * point.y + this._d);
  1443. return point;
  1444. },
  1445. // @method untransform(point: Point, scale?: Number): Point
  1446. // Returns the reverse transformation of the given point, optionally divided
  1447. // by the given scale. Only accepts actual `L.Point` instances, not arrays.
  1448. untransform: function (point, scale) {
  1449. scale = scale || 1;
  1450. return new Point(
  1451. (point.x / scale - this._b) / this._a,
  1452. (point.y / scale - this._d) / this._c);
  1453. }
  1454. };
  1455. // factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1456. // @factory L.transformation(a: Number, b: Number, c: Number, d: Number)
  1457. // Instantiates a Transformation object with the given coefficients.
  1458. // @alternative
  1459. // @factory L.transformation(coefficients: Array): Transformation
  1460. // Expects an coefficients array of the form
  1461. // `[a: Number, b: Number, c: Number, d: Number]`.
  1462. function toTransformation(a, b, c, d) {
  1463. return new Transformation(a, b, c, d);
  1464. }
  1465. /*
  1466. * @namespace CRS
  1467. * @crs L.CRS.EPSG3857
  1468. *
  1469. * The most common CRS for online maps, used by almost all free and commercial
  1470. * tile providers. Uses Spherical Mercator projection. Set in by default in
  1471. * Map's `crs` option.
  1472. */
  1473. var EPSG3857 = extend({}, Earth, {
  1474. code: 'EPSG:3857',
  1475. projection: SphericalMercator,
  1476. transformation: (function () {
  1477. var scale = 0.5 / (Math.PI * SphericalMercator.R);
  1478. return toTransformation(scale, 0.5, -scale, 0.5);
  1479. }())
  1480. });
  1481. var EPSG900913 = extend({}, EPSG3857, {
  1482. code: 'EPSG:900913'
  1483. });
  1484. // @namespace SVG; @section
  1485. // There are several static functions which can be called without instantiating L.SVG:
  1486. // @function create(name: String): SVGElement
  1487. // Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement),
  1488. // corresponding to the class name passed. For example, using 'line' will return
  1489. // an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement).
  1490. function svgCreate(name) {
  1491. return document.createElementNS('http://www.w3.org/2000/svg', name);
  1492. }
  1493. // @function pointsToPath(rings: Point[], closed: Boolean): String
  1494. // Generates a SVG path string for multiple rings, with each ring turning
  1495. // into "M..L..L.." instructions
  1496. function pointsToPath(rings, closed) {
  1497. var str = '',
  1498. i, j, len, len2, points, p;
  1499. for (i = 0, len = rings.length; i < len; i++) {
  1500. points = rings[i];
  1501. for (j = 0, len2 = points.length; j < len2; j++) {
  1502. p = points[j];
  1503. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  1504. }
  1505. // closes the ring for polygons; "x" is VML syntax
  1506. str += closed ? (svg ? 'z' : 'x') : '';
  1507. }
  1508. // SVG complains about empty path strings
  1509. return str || 'M0 0';
  1510. }
  1511. /*
  1512. * @namespace Browser
  1513. * @aka L.Browser
  1514. *
  1515. * A namespace with static properties for browser/feature detection used by Leaflet internally.
  1516. *
  1517. * @example
  1518. *
  1519. * ```js
  1520. * if (L.Browser.ielt9) {
  1521. * alert('Upgrade your browser, dude!');
  1522. * }
  1523. * ```
  1524. */
  1525. var style$1 = document.documentElement.style;
  1526. // @property ie: Boolean; `true` for all Internet Explorer versions (not Edge).
  1527. var ie = 'ActiveXObject' in window;
  1528. // @property ielt9: Boolean; `true` for Internet Explorer versions less than 9.
  1529. var ielt9 = ie && !document.addEventListener;
  1530. // @property edge: Boolean; `true` for the Edge web browser.
  1531. var edge = 'msLaunchUri' in navigator && !('documentMode' in document);
  1532. // @property webkit: Boolean;
  1533. // `true` for webkit-based browsers like Chrome and Safari (including mobile versions).
  1534. var webkit = userAgentContains('webkit');
  1535. // @property android: Boolean
  1536. // `true` for any browser running on an Android platform.
  1537. var android = userAgentContains('android');
  1538. // @property android23: Boolean; `true` for browsers running on Android 2 or Android 3.
  1539. var android23 = userAgentContains('android 2') || userAgentContains('android 3');
  1540. /* See https://stackoverflow.com/a/17961266 for details on detecting stock Android */
  1541. var webkitVer = parseInt(/WebKit\/([0-9]+)|$/.exec(navigator.userAgent)[1], 10); // also matches AppleWebKit
  1542. // @property androidStock: Boolean; `true` for the Android stock browser (i.e. not Chrome)
  1543. var androidStock = android && userAgentContains('Google') && webkitVer < 537 && !('AudioNode' in window);
  1544. // @property opera: Boolean; `true` for the Opera browser
  1545. var opera = !!window.opera;
  1546. // @property chrome: Boolean; `true` for the Chrome browser.
  1547. var chrome = userAgentContains('chrome');
  1548. // @property gecko: Boolean; `true` for gecko-based browsers like Firefox.
  1549. var gecko = userAgentContains('gecko') && !webkit && !opera && !ie;
  1550. // @property safari: Boolean; `true` for the Safari browser.
  1551. var safari = !chrome && userAgentContains('safari');
  1552. var phantom = userAgentContains('phantom');
  1553. // @property opera12: Boolean
  1554. // `true` for the Opera browser supporting CSS transforms (version 12 or later).
  1555. var opera12 = 'OTransition' in style$1;
  1556. // @property win: Boolean; `true` when the browser is running in a Windows platform
  1557. var win = navigator.platform.indexOf('Win') === 0;
  1558. // @property ie3d: Boolean; `true` for all Internet Explorer versions supporting CSS transforms.
  1559. var ie3d = ie && ('transition' in style$1);
  1560. // @property webkit3d: Boolean; `true` for webkit-based browsers supporting CSS transforms.
  1561. var webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23;
  1562. // @property gecko3d: Boolean; `true` for gecko-based browsers supporting CSS transforms.
  1563. var gecko3d = 'MozPerspective' in style$1;
  1564. // @property any3d: Boolean
  1565. // `true` for all browsers supporting CSS transforms.
  1566. var any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d) && !opera12 && !phantom;
  1567. // @property mobile: Boolean; `true` for all browsers running in a mobile device.
  1568. var mobile = typeof orientation !== 'undefined' || userAgentContains('mobile');
  1569. // @property mobileWebkit: Boolean; `true` for all webkit-based browsers in a mobile device.
  1570. var mobileWebkit = mobile && webkit;
  1571. // @property mobileWebkit3d: Boolean
  1572. // `true` for all webkit-based browsers in a mobile device supporting CSS transforms.
  1573. var mobileWebkit3d = mobile && webkit3d;
  1574. // @property msPointer: Boolean
  1575. // `true` for browsers implementing the Microsoft touch events model (notably IE10).
  1576. var msPointer = !window.PointerEvent && window.MSPointerEvent;
  1577. // @property pointer: Boolean
  1578. // `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx).
  1579. var pointer = !!(window.PointerEvent || msPointer);
  1580. // @property touch: Boolean
  1581. // `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events).
  1582. // This does not necessarily mean that the browser is running in a computer with
  1583. // a touchscreen, it only means that the browser is capable of understanding
  1584. // touch events.
  1585. var touch = !window.L_NO_TOUCH && (pointer || 'ontouchstart' in window ||
  1586. (window.DocumentTouch && document instanceof window.DocumentTouch));
  1587. // @property mobileOpera: Boolean; `true` for the Opera browser in a mobile device.
  1588. var mobileOpera = mobile && opera;
  1589. // @property mobileGecko: Boolean
  1590. // `true` for gecko-based browsers running in a mobile device.
  1591. var mobileGecko = mobile && gecko;
  1592. // @property retina: Boolean
  1593. // `true` for browsers on a high-resolution "retina" screen.
  1594. var retina = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
  1595. // @property canvas: Boolean
  1596. // `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  1597. var canvas = (function () {
  1598. return !!document.createElement('canvas').getContext;
  1599. }());
  1600. // @property svg: Boolean
  1601. // `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG).
  1602. var svg = !!(document.createElementNS && svgCreate('svg').createSVGRect);
  1603. // @property vml: Boolean
  1604. // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language).
  1605. var vml = !svg && (function () {
  1606. try {
  1607. var div = document.createElement('div');
  1608. div.innerHTML = '<v:shape adj="1"/>';
  1609. var shape = div.firstChild;
  1610. shape.style.behavior = 'url(#default#VML)';
  1611. return shape && (typeof shape.adj === 'object');
  1612. } catch (e) {
  1613. return false;
  1614. }
  1615. }());
  1616. function userAgentContains(str) {
  1617. return navigator.userAgent.toLowerCase().indexOf(str) >= 0;
  1618. }
  1619. var Browser = (Object.freeze || Object)({
  1620. ie: ie,
  1621. ielt9: ielt9,
  1622. edge: edge,
  1623. webkit: webkit,
  1624. android: android,
  1625. android23: android23,
  1626. androidStock: androidStock,
  1627. opera: opera,
  1628. chrome: chrome,
  1629. gecko: gecko,
  1630. safari: safari,
  1631. phantom: phantom,
  1632. opera12: opera12,
  1633. win: win,
  1634. ie3d: ie3d,
  1635. webkit3d: webkit3d,
  1636. gecko3d: gecko3d,
  1637. any3d: any3d,
  1638. mobile: mobile,
  1639. mobileWebkit: mobileWebkit,
  1640. mobileWebkit3d: mobileWebkit3d,
  1641. msPointer: msPointer,
  1642. pointer: pointer,
  1643. touch: touch,
  1644. mobileOpera: mobileOpera,
  1645. mobileGecko: mobileGecko,
  1646. retina: retina,
  1647. canvas: canvas,
  1648. svg: svg,
  1649. vml: vml
  1650. });
  1651. /*
  1652. * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
  1653. */
  1654. var POINTER_DOWN = msPointer ? 'MSPointerDown' : 'pointerdown';
  1655. var POINTER_MOVE = msPointer ? 'MSPointerMove' : 'pointermove';
  1656. var POINTER_UP = msPointer ? 'MSPointerUp' : 'pointerup';
  1657. var POINTER_CANCEL = msPointer ? 'MSPointerCancel' : 'pointercancel';
  1658. var TAG_WHITE_LIST = ['INPUT', 'SELECT', 'OPTION'];
  1659. var _pointers = {};
  1660. var _pointerDocListener = false;
  1661. // DomEvent.DoubleTap needs to know about this
  1662. var _pointersCount = 0;
  1663. // Provides a touch events wrapper for (ms)pointer events.
  1664. // ref http://www.w3.org/TR/pointerevents/ https://www.w3.org/Bugs/Public/show_bug.cgi?id=22890
  1665. function addPointerListener(obj, type, handler, id) {
  1666. if (type === 'touchstart') {
  1667. _addPointerStart(obj, handler, id);
  1668. } else if (type === 'touchmove') {
  1669. _addPointerMove(obj, handler, id);
  1670. } else if (type === 'touchend') {
  1671. _addPointerEnd(obj, handler, id);
  1672. }
  1673. return this;
  1674. }
  1675. function removePointerListener(obj, type, id) {
  1676. var handler = obj['_leaflet_' + type + id];
  1677. if (type === 'touchstart') {
  1678. obj.removeEventListener(POINTER_DOWN, handler, false);
  1679. } else if (type === 'touchmove') {
  1680. obj.removeEventListener(POINTER_MOVE, handler, false);
  1681. } else if (type === 'touchend') {
  1682. obj.removeEventListener(POINTER_UP, handler, false);
  1683. obj.removeEventListener(POINTER_CANCEL, handler, false);
  1684. }
  1685. return this;
  1686. }
  1687. function _addPointerStart(obj, handler, id) {
  1688. var onDown = bind(function (e) {
  1689. if (e.pointerType !== 'mouse' && e.MSPOINTER_TYPE_MOUSE && e.pointerType !== e.MSPOINTER_TYPE_MOUSE) {
  1690. // In IE11, some touch events needs to fire for form controls, or
  1691. // the controls will stop working. We keep a whitelist of tag names that
  1692. // need these events. For other target tags, we prevent default on the event.
  1693. if (TAG_WHITE_LIST.indexOf(e.target.tagName) < 0) {
  1694. preventDefault(e);
  1695. } else {
  1696. return;
  1697. }
  1698. }
  1699. _handlePointer(e, handler);
  1700. });
  1701. obj['_leaflet_touchstart' + id] = onDown;
  1702. obj.addEventListener(POINTER_DOWN, onDown, false);
  1703. // need to keep track of what pointers and how many are active to provide e.touches emulation
  1704. if (!_pointerDocListener) {
  1705. // we listen documentElement as any drags that end by moving the touch off the screen get fired there
  1706. document.documentElement.addEventListener(POINTER_DOWN, _globalPointerDown, true);
  1707. document.documentElement.addEventListener(POINTER_MOVE, _globalPointerMove, true);
  1708. document.documentElement.addEventListener(POINTER_UP, _globalPointerUp, true);
  1709. document.documentElement.addEventListener(POINTER_CANCEL, _globalPointerUp, true);
  1710. _pointerDocListener = true;
  1711. }
  1712. }
  1713. function _globalPointerDown(e) {
  1714. _pointers[e.pointerId] = e;
  1715. _pointersCount++;
  1716. }
  1717. function _globalPointerMove(e) {
  1718. if (_pointers[e.pointerId]) {
  1719. _pointers[e.pointerId] = e;
  1720. }
  1721. }
  1722. function _globalPointerUp(e) {
  1723. delete _pointers[e.pointerId];
  1724. _pointersCount--;
  1725. }
  1726. function _handlePointer(e, handler) {
  1727. e.touches = [];
  1728. for (var i in _pointers) {
  1729. e.touches.push(_pointers[i]);
  1730. }
  1731. e.changedTouches = [e];
  1732. handler(e);
  1733. }
  1734. function _addPointerMove(obj, handler, id) {
  1735. var onMove = function (e) {
  1736. // don't fire touch moves when mouse isn't down
  1737. if ((e.pointerType === e.MSPOINTER_TYPE_MOUSE || e.pointerType === 'mouse') && e.buttons === 0) { return; }
  1738. _handlePointer(e, handler);
  1739. };
  1740. obj['_leaflet_touchmove' + id] = onMove;
  1741. obj.addEventListener(POINTER_MOVE, onMove, false);
  1742. }
  1743. function _addPointerEnd(obj, handler, id) {
  1744. var onUp = function (e) {
  1745. _handlePointer(e, handler);
  1746. };
  1747. obj['_leaflet_touchend' + id] = onUp;
  1748. obj.addEventListener(POINTER_UP, onUp, false);
  1749. obj.addEventListener(POINTER_CANCEL, onUp, false);
  1750. }
  1751. /*
  1752. * Extends the event handling code with double tap support for mobile browsers.
  1753. */
  1754. var _touchstart = msPointer ? 'MSPointerDown' : pointer ? 'pointerdown' : 'touchstart';
  1755. var _touchend = msPointer ? 'MSPointerUp' : pointer ? 'pointerup' : 'touchend';
  1756. var _pre = '_leaflet_';
  1757. // inspired by Zepto touch code by Thomas Fuchs
  1758. function addDoubleTapListener(obj, handler, id) {
  1759. var last, touch$$1,
  1760. doubleTap = false,
  1761. delay = 250;
  1762. function onTouchStart(e) {
  1763. var count;
  1764. if (pointer) {
  1765. if ((!edge) || e.pointerType === 'mouse') { return; }
  1766. count = _pointersCount;
  1767. } else {
  1768. count = e.touches.length;
  1769. }
  1770. if (count > 1) { return; }
  1771. var now = Date.now(),
  1772. delta = now - (last || now);
  1773. touch$$1 = e.touches ? e.touches[0] : e;
  1774. doubleTap = (delta > 0 && delta <= delay);
  1775. last = now;
  1776. }
  1777. function onTouchEnd(e) {
  1778. if (doubleTap && !touch$$1.cancelBubble) {
  1779. if (pointer) {
  1780. if ((!edge) || e.pointerType === 'mouse') { return; }
  1781. // work around .type being readonly with MSPointer* events
  1782. var newTouch = {},
  1783. prop, i;
  1784. for (i in touch$$1) {
  1785. prop = touch$$1[i];
  1786. newTouch[i] = prop && prop.bind ? prop.bind(touch$$1) : prop;
  1787. }
  1788. touch$$1 = newTouch;
  1789. }
  1790. touch$$1.type = 'dblclick';
  1791. handler(touch$$1);
  1792. last = null;
  1793. }
  1794. }
  1795. obj[_pre + _touchstart + id] = onTouchStart;
  1796. obj[_pre + _touchend + id] = onTouchEnd;
  1797. obj[_pre + 'dblclick' + id] = handler;
  1798. obj.addEventListener(_touchstart, onTouchStart, false);
  1799. obj.addEventListener(_touchend, onTouchEnd, false);
  1800. // On some platforms (notably, chrome<55 on win10 + touchscreen + mouse),
  1801. // the browser doesn't fire touchend/pointerup events but does fire
  1802. // native dblclicks. See #4127.
  1803. // Edge 14 also fires native dblclicks, but only for pointerType mouse, see #5180.
  1804. obj.addEventListener('dblclick', handler, false);
  1805. return this;
  1806. }
  1807. function removeDoubleTapListener(obj, id) {
  1808. var touchstart = obj[_pre + _touchstart + id],
  1809. touchend = obj[_pre + _touchend + id],
  1810. dblclick = obj[_pre + 'dblclick' + id];
  1811. obj.removeEventListener(_touchstart, touchstart, false);
  1812. obj.removeEventListener(_touchend, touchend, false);
  1813. if (!edge) {
  1814. obj.removeEventListener('dblclick', dblclick, false);
  1815. }
  1816. return this;
  1817. }
  1818. /*
  1819. * @namespace DomEvent
  1820. * Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally.
  1821. */
  1822. // Inspired by John Resig, Dean Edwards and YUI addEvent implementations.
  1823. // @function on(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1824. // Adds a listener function (`fn`) to a particular DOM event type of the
  1825. // element `el`. You can optionally specify the context of the listener
  1826. // (object the `this` keyword will point to). You can also pass several
  1827. // space-separated types (e.g. `'click dblclick'`).
  1828. // @alternative
  1829. // @function on(el: HTMLElement, eventMap: Object, context?: Object): this
  1830. // Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1831. function on(obj, types, fn, context) {
  1832. if (typeof types === 'object') {
  1833. for (var type in types) {
  1834. addOne(obj, type, types[type], fn);
  1835. }
  1836. } else {
  1837. types = splitWords(types);
  1838. for (var i = 0, len = types.length; i < len; i++) {
  1839. addOne(obj, types[i], fn, context);
  1840. }
  1841. }
  1842. return this;
  1843. }
  1844. var eventsKey = '_leaflet_events';
  1845. // @function off(el: HTMLElement, types: String, fn: Function, context?: Object): this
  1846. // Removes a previously added listener function.
  1847. // Note that if you passed a custom context to on, you must pass the same
  1848. // context to `off` in order to remove the listener.
  1849. // @alternative
  1850. // @function off(el: HTMLElement, eventMap: Object, context?: Object): this
  1851. // Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}`
  1852. function off(obj, types, fn, context) {
  1853. if (typeof types === 'object') {
  1854. for (var type in types) {
  1855. removeOne(obj, type, types[type], fn);
  1856. }
  1857. } else if (types) {
  1858. types = splitWords(types);
  1859. for (var i = 0, len = types.length; i < len; i++) {
  1860. removeOne(obj, types[i], fn, context);
  1861. }
  1862. } else {
  1863. for (var j in obj[eventsKey]) {
  1864. removeOne(obj, j, obj[eventsKey][j]);
  1865. }
  1866. delete obj[eventsKey];
  1867. }
  1868. return this;
  1869. }
  1870. function addOne(obj, type, fn, context) {
  1871. var id = type + stamp(fn) + (context ? '_' + stamp(context) : '');
  1872. if (obj[eventsKey] && obj[eventsKey][id]) { return this; }
  1873. var handler = function (e) {
  1874. return fn.call(context || obj, e || window.event);
  1875. };
  1876. var originalHandler = handler;
  1877. if (pointer && type.indexOf('touch') === 0) {
  1878. // Needs DomEvent.Pointer.js
  1879. addPointerListener(obj, type, handler, id);
  1880. } else if (touch && (type === 'dblclick') && addDoubleTapListener &&
  1881. !(pointer && chrome)) {
  1882. // Chrome >55 does not need the synthetic dblclicks from addDoubleTapListener
  1883. // See #5180
  1884. addDoubleTapListener(obj, handler, id);
  1885. } else if ('addEventListener' in obj) {
  1886. if (type === 'mousewheel') {
  1887. obj.addEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1888. } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
  1889. handler = function (e) {
  1890. e = e || window.event;
  1891. if (isExternalTarget(obj, e)) {
  1892. originalHandler(e);
  1893. }
  1894. };
  1895. obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false);
  1896. } else {
  1897. if (type === 'click' && android) {
  1898. handler = function (e) {
  1899. filterClick(e, originalHandler);
  1900. };
  1901. }
  1902. obj.addEventListener(type, handler, false);
  1903. }
  1904. } else if ('attachEvent' in obj) {
  1905. obj.attachEvent('on' + type, handler);
  1906. }
  1907. obj[eventsKey] = obj[eventsKey] || {};
  1908. obj[eventsKey][id] = handler;
  1909. }
  1910. function removeOne(obj, type, fn, context) {
  1911. var id = type + stamp(fn) + (context ? '_' + stamp(context) : ''),
  1912. handler = obj[eventsKey] && obj[eventsKey][id];
  1913. if (!handler) { return this; }
  1914. if (pointer && type.indexOf('touch') === 0) {
  1915. removePointerListener(obj, type, id);
  1916. } else if (touch && (type === 'dblclick') && removeDoubleTapListener &&
  1917. !(pointer && chrome)) {
  1918. removeDoubleTapListener(obj, id);
  1919. } else if ('removeEventListener' in obj) {
  1920. if (type === 'mousewheel') {
  1921. obj.removeEventListener('onwheel' in obj ? 'wheel' : 'mousewheel', handler, false);
  1922. } else {
  1923. obj.removeEventListener(
  1924. type === 'mouseenter' ? 'mouseover' :
  1925. type === 'mouseleave' ? 'mouseout' : type, handler, false);
  1926. }
  1927. } else if ('detachEvent' in obj) {
  1928. obj.detachEvent('on' + type, handler);
  1929. }
  1930. obj[eventsKey][id] = null;
  1931. }
  1932. // @function stopPropagation(ev: DOMEvent): this
  1933. // Stop the given event from propagation to parent elements. Used inside the listener functions:
  1934. // ```js
  1935. // L.DomEvent.on(div, 'click', function (ev) {
  1936. // L.DomEvent.stopPropagation(ev);
  1937. // });
  1938. // ```
  1939. function stopPropagation(e) {
  1940. if (e.stopPropagation) {
  1941. e.stopPropagation();
  1942. } else if (e.originalEvent) { // In case of Leaflet event.
  1943. e.originalEvent._stopped = true;
  1944. } else {
  1945. e.cancelBubble = true;
  1946. }
  1947. skipped(e);
  1948. return this;
  1949. }
  1950. // @function disableScrollPropagation(el: HTMLElement): this
  1951. // Adds `stopPropagation` to the element's `'mousewheel'` events (plus browser variants).
  1952. function disableScrollPropagation(el) {
  1953. addOne(el, 'mousewheel', stopPropagation);
  1954. return this;
  1955. }
  1956. // @function disableClickPropagation(el: HTMLElement): this
  1957. // Adds `stopPropagation` to the element's `'click'`, `'doubleclick'`,
  1958. // `'mousedown'` and `'touchstart'` events (plus browser variants).
  1959. function disableClickPropagation(el) {
  1960. on(el, 'mousedown touchstart dblclick', stopPropagation);
  1961. addOne(el, 'click', fakeStop);
  1962. return this;
  1963. }
  1964. // @function preventDefault(ev: DOMEvent): this
  1965. // Prevents the default action of the DOM Event `ev` from happening (such as
  1966. // following a link in the href of the a element, or doing a POST request
  1967. // with page reload when a `<form>` is submitted).
  1968. // Use it inside listener functions.
  1969. function preventDefault(e) {
  1970. if (e.preventDefault) {
  1971. e.preventDefault();
  1972. } else {
  1973. e.returnValue = false;
  1974. }
  1975. return this;
  1976. }
  1977. // @function stop(ev: DOMEvent): this
  1978. // Does `stopPropagation` and `preventDefault` at the same time.
  1979. function stop(e) {
  1980. preventDefault(e);
  1981. stopPropagation(e);
  1982. return this;
  1983. }
  1984. // @function getMousePosition(ev: DOMEvent, container?: HTMLElement): Point
  1985. // Gets normalized mouse position from a DOM event relative to the
  1986. // `container` or to the whole page if not specified.
  1987. function getMousePosition(e, container) {
  1988. if (!container) {
  1989. return new Point(e.clientX, e.clientY);
  1990. }
  1991. var rect = container.getBoundingClientRect();
  1992. var scaleX = rect.width / container.offsetWidth || 1;
  1993. var scaleY = rect.height / container.offsetHeight || 1;
  1994. return new Point(
  1995. e.clientX / scaleX - rect.left - container.clientLeft,
  1996. e.clientY / scaleY - rect.top - container.clientTop);
  1997. }
  1998. // Chrome on Win scrolls double the pixels as in other platforms (see #4538),
  1999. // and Firefox scrolls device pixels, not CSS pixels
  2000. var wheelPxFactor =
  2001. (win && chrome) ? 2 * window.devicePixelRatio :
  2002. gecko ? window.devicePixelRatio : 1;
  2003. // @function getWheelDelta(ev: DOMEvent): Number
  2004. // Gets normalized wheel delta from a mousewheel DOM event, in vertical
  2005. // pixels scrolled (negative if scrolling down).
  2006. // Events from pointing devices without precise scrolling are mapped to
  2007. // a best guess of 60 pixels.
  2008. function getWheelDelta(e) {
  2009. return (edge) ? e.wheelDeltaY / 2 : // Don't trust window-geometry-based delta
  2010. (e.deltaY && e.deltaMode === 0) ? -e.deltaY / wheelPxFactor : // Pixels
  2011. (e.deltaY && e.deltaMode === 1) ? -e.deltaY * 20 : // Lines
  2012. (e.deltaY && e.deltaMode === 2) ? -e.deltaY * 60 : // Pages
  2013. (e.deltaX || e.deltaZ) ? 0 : // Skip horizontal/depth wheel events
  2014. e.wheelDelta ? (e.wheelDeltaY || e.wheelDelta) / 2 : // Legacy IE pixels
  2015. (e.detail && Math.abs(e.detail) < 32765) ? -e.detail * 20 : // Legacy Moz lines
  2016. e.detail ? e.detail / -32765 * 60 : // Legacy Moz pages
  2017. 0;
  2018. }
  2019. var skipEvents = {};
  2020. function fakeStop(e) {
  2021. // fakes stopPropagation by setting a special event flag, checked/reset with skipped(e)
  2022. skipEvents[e.type] = true;
  2023. }
  2024. function skipped(e) {
  2025. var events = skipEvents[e.type];
  2026. // reset when checking, as it's only used in map container and propagates outside of the map
  2027. skipEvents[e.type] = false;
  2028. return events;
  2029. }
  2030. // check if element really left/entered the event target (for mouseenter/mouseleave)
  2031. function isExternalTarget(el, e) {
  2032. var related = e.relatedTarget;
  2033. if (!related) { return true; }
  2034. try {
  2035. while (related && (related !== el)) {
  2036. related = related.parentNode;
  2037. }
  2038. } catch (err) {
  2039. return false;
  2040. }
  2041. return (related !== el);
  2042. }
  2043. var lastClick;
  2044. // this is a horrible workaround for a bug in Android where a single touch triggers two click events
  2045. function filterClick(e, handler) {
  2046. var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)),
  2047. elapsed = lastClick && (timeStamp - lastClick);
  2048. // are they closer together than 500ms yet more than 100ms?
  2049. // Android typically triggers them ~300ms apart while multiple listeners
  2050. // on the same event should be triggered far faster;
  2051. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2052. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2053. stop(e);
  2054. return;
  2055. }
  2056. lastClick = timeStamp;
  2057. handler(e);
  2058. }
  2059. var DomEvent = (Object.freeze || Object)({
  2060. on: on,
  2061. off: off,
  2062. stopPropagation: stopPropagation,
  2063. disableScrollPropagation: disableScrollPropagation,
  2064. disableClickPropagation: disableClickPropagation,
  2065. preventDefault: preventDefault,
  2066. stop: stop,
  2067. getMousePosition: getMousePosition,
  2068. getWheelDelta: getWheelDelta,
  2069. fakeStop: fakeStop,
  2070. skipped: skipped,
  2071. isExternalTarget: isExternalTarget,
  2072. addListener: on,
  2073. removeListener: off
  2074. });
  2075. /*
  2076. * @namespace DomUtil
  2077. *
  2078. * Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model)
  2079. * tree, used by Leaflet internally.
  2080. *
  2081. * Most functions expecting or returning a `HTMLElement` also work for
  2082. * SVG elements. The only difference is that classes refer to CSS classes
  2083. * in HTML and SVG classes in SVG.
  2084. */
  2085. // @property TRANSFORM: String
  2086. // Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit).
  2087. var TRANSFORM = testProp(
  2088. ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  2089. // webkitTransition comes first because some browser versions that drop vendor prefix don't do
  2090. // the same for the transitionend event, in particular the Android 4.1 stock browser
  2091. // @property TRANSITION: String
  2092. // Vendor-prefixed transition style name.
  2093. var TRANSITION = testProp(
  2094. ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  2095. // @property TRANSITION_END: String
  2096. // Vendor-prefixed transitionend event name.
  2097. var TRANSITION_END =
  2098. TRANSITION === 'webkitTransition' || TRANSITION === 'OTransition' ? TRANSITION + 'End' : 'transitionend';
  2099. // @function get(id: String|HTMLElement): HTMLElement
  2100. // Returns an element given its DOM id, or returns the element itself
  2101. // if it was passed directly.
  2102. function get(id) {
  2103. return typeof id === 'string' ? document.getElementById(id) : id;
  2104. }
  2105. // @function getStyle(el: HTMLElement, styleAttrib: String): String
  2106. // Returns the value for a certain style attribute on an element,
  2107. // including computed values or values set through CSS.
  2108. function getStyle(el, style) {
  2109. var value = el.style[style] || (el.currentStyle && el.currentStyle[style]);
  2110. if ((!value || value === 'auto') && document.defaultView) {
  2111. var css = document.defaultView.getComputedStyle(el, null);
  2112. value = css ? css[style] : null;
  2113. }
  2114. return value === 'auto' ? null : value;
  2115. }
  2116. // @function create(tagName: String, className?: String, container?: HTMLElement): HTMLElement
  2117. // Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element.
  2118. function create$1(tagName, className, container) {
  2119. var el = document.createElement(tagName);
  2120. el.className = className || '';
  2121. if (container) {
  2122. container.appendChild(el);
  2123. }
  2124. return el;
  2125. }
  2126. // @function remove(el: HTMLElement)
  2127. // Removes `el` from its parent element
  2128. function remove(el) {
  2129. var parent = el.parentNode;
  2130. if (parent) {
  2131. parent.removeChild(el);
  2132. }
  2133. }
  2134. // @function empty(el: HTMLElement)
  2135. // Removes all of `el`'s children elements from `el`
  2136. function empty(el) {
  2137. while (el.firstChild) {
  2138. el.removeChild(el.firstChild);
  2139. }
  2140. }
  2141. // @function toFront(el: HTMLElement)
  2142. // Makes `el` the last child of its parent, so it renders in front of the other children.
  2143. function toFront(el) {
  2144. var parent = el.parentNode;
  2145. if (parent.lastChild !== el) {
  2146. parent.appendChild(el);
  2147. }
  2148. }
  2149. // @function toBack(el: HTMLElement)
  2150. // Makes `el` the first child of its parent, so it renders behind the other children.
  2151. function toBack(el) {
  2152. var parent = el.parentNode;
  2153. if (parent.firstChild !== el) {
  2154. parent.insertBefore(el, parent.firstChild);
  2155. }
  2156. }
  2157. // @function hasClass(el: HTMLElement, name: String): Boolean
  2158. // Returns `true` if the element's class attribute contains `name`.
  2159. function hasClass(el, name) {
  2160. if (el.classList !== undefined) {
  2161. return el.classList.contains(name);
  2162. }
  2163. var className = getClass(el);
  2164. return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
  2165. }
  2166. // @function addClass(el: HTMLElement, name: String)
  2167. // Adds `name` to the element's class attribute.
  2168. function addClass(el, name) {
  2169. if (el.classList !== undefined) {
  2170. var classes = splitWords(name);
  2171. for (var i = 0, len = classes.length; i < len; i++) {
  2172. el.classList.add(classes[i]);
  2173. }
  2174. } else if (!hasClass(el, name)) {
  2175. var className = getClass(el);
  2176. setClass(el, (className ? className + ' ' : '') + name);
  2177. }
  2178. }
  2179. // @function removeClass(el: HTMLElement, name: String)
  2180. // Removes `name` from the element's class attribute.
  2181. function removeClass(el, name) {
  2182. if (el.classList !== undefined) {
  2183. el.classList.remove(name);
  2184. } else {
  2185. setClass(el, trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' ')));
  2186. }
  2187. }
  2188. // @function setClass(el: HTMLElement, name: String)
  2189. // Sets the element's class.
  2190. function setClass(el, name) {
  2191. if (el.className.baseVal === undefined) {
  2192. el.className = name;
  2193. } else {
  2194. // in case of SVG element
  2195. el.className.baseVal = name;
  2196. }
  2197. }
  2198. // @function getClass(el: HTMLElement): String
  2199. // Returns the element's class.
  2200. function getClass(el) {
  2201. return el.className.baseVal === undefined ? el.className : el.className.baseVal;
  2202. }
  2203. // @function setOpacity(el: HTMLElement, opacity: Number)
  2204. // Set the opacity of an element (including old IE support).
  2205. // `opacity` must be a number from `0` to `1`.
  2206. function setOpacity(el, value) {
  2207. if ('opacity' in el.style) {
  2208. el.style.opacity = value;
  2209. } else if ('filter' in el.style) {
  2210. _setOpacityIE(el, value);
  2211. }
  2212. }
  2213. function _setOpacityIE(el, value) {
  2214. var filter = false,
  2215. filterName = 'DXImageTransform.Microsoft.Alpha';
  2216. // filters collection throws an error if we try to retrieve a filter that doesn't exist
  2217. try {
  2218. filter = el.filters.item(filterName);
  2219. } catch (e) {
  2220. // don't set opacity to 1 if we haven't already set an opacity,
  2221. // it isn't needed and breaks transparent pngs.
  2222. if (value === 1) { return; }
  2223. }
  2224. value = Math.round(value * 100);
  2225. if (filter) {
  2226. filter.Enabled = (value !== 100);
  2227. filter.Opacity = value;
  2228. } else {
  2229. el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
  2230. }
  2231. }
  2232. // @function testProp(props: String[]): String|false
  2233. // Goes through the array of style names and returns the first name
  2234. // that is a valid style name for an element. If no such name is found,
  2235. // it returns false. Useful for vendor-prefixed styles like `transform`.
  2236. function testProp(props) {
  2237. var style = document.documentElement.style;
  2238. for (var i = 0; i < props.length; i++) {
  2239. if (props[i] in style) {
  2240. return props[i];
  2241. }
  2242. }
  2243. return false;
  2244. }
  2245. // @function setTransform(el: HTMLElement, offset: Point, scale?: Number)
  2246. // Resets the 3D CSS transform of `el` so it is translated by `offset` pixels
  2247. // and optionally scaled by `scale`. Does not have an effect if the
  2248. // browser doesn't support 3D CSS transforms.
  2249. function setTransform(el, offset, scale) {
  2250. var pos = offset || new Point(0, 0);
  2251. el.style[TRANSFORM] =
  2252. (ie3d ?
  2253. 'translate(' + pos.x + 'px,' + pos.y + 'px)' :
  2254. 'translate3d(' + pos.x + 'px,' + pos.y + 'px,0)') +
  2255. (scale ? ' scale(' + scale + ')' : '');
  2256. }
  2257. // @function setPosition(el: HTMLElement, position: Point)
  2258. // Sets the position of `el` to coordinates specified by `position`,
  2259. // using CSS translate or top/left positioning depending on the browser
  2260. // (used by Leaflet internally to position its layers).
  2261. function setPosition(el, point) {
  2262. /*eslint-disable */
  2263. el._leaflet_pos = point;
  2264. /* eslint-enable */
  2265. if (any3d) {
  2266. setTransform(el, point);
  2267. } else {
  2268. el.style.left = point.x + 'px';
  2269. el.style.top = point.y + 'px';
  2270. }
  2271. }
  2272. // @function getPosition(el: HTMLElement): Point
  2273. // Returns the coordinates of an element previously positioned with setPosition.
  2274. function getPosition(el) {
  2275. // this method is only used for elements previously positioned using setPosition,
  2276. // so it's safe to cache the position for performance
  2277. return el._leaflet_pos || new Point(0, 0);
  2278. }
  2279. // @function disableTextSelection()
  2280. // Prevents the user from generating `selectstart` DOM events, usually generated
  2281. // when the user drags the mouse through a page with text. Used internally
  2282. // by Leaflet to override the behaviour of any click-and-drag interaction on
  2283. // the map. Affects drag interactions on the whole document.
  2284. // @function enableTextSelection()
  2285. // Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection).
  2286. var disableTextSelection;
  2287. var enableTextSelection;
  2288. var _userSelect;
  2289. if ('onselectstart' in document) {
  2290. disableTextSelection = function () {
  2291. on(window, 'selectstart', preventDefault);
  2292. };
  2293. enableTextSelection = function () {
  2294. off(window, 'selectstart', preventDefault);
  2295. };
  2296. } else {
  2297. var userSelectProperty = testProp(
  2298. ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
  2299. disableTextSelection = function () {
  2300. if (userSelectProperty) {
  2301. var style = document.documentElement.style;
  2302. _userSelect = style[userSelectProperty];
  2303. style[userSelectProperty] = 'none';
  2304. }
  2305. };
  2306. enableTextSelection = function () {
  2307. if (userSelectProperty) {
  2308. document.documentElement.style[userSelectProperty] = _userSelect;
  2309. _userSelect = undefined;
  2310. }
  2311. };
  2312. }
  2313. // @function disableImageDrag()
  2314. // As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but
  2315. // for `dragstart` DOM events, usually generated when the user drags an image.
  2316. function disableImageDrag() {
  2317. on(window, 'dragstart', preventDefault);
  2318. }
  2319. // @function enableImageDrag()
  2320. // Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection).
  2321. function enableImageDrag() {
  2322. off(window, 'dragstart', preventDefault);
  2323. }
  2324. var _outlineElement;
  2325. var _outlineStyle;
  2326. // @function preventOutline(el: HTMLElement)
  2327. // Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline)
  2328. // of the element `el` invisible. Used internally by Leaflet to prevent
  2329. // focusable elements from displaying an outline when the user performs a
  2330. // drag interaction on them.
  2331. function preventOutline(element) {
  2332. while (element.tabIndex === -1) {
  2333. element = element.parentNode;
  2334. }
  2335. if (!element.style) { return; }
  2336. restoreOutline();
  2337. _outlineElement = element;
  2338. _outlineStyle = element.style.outline;
  2339. element.style.outline = 'none';
  2340. on(window, 'keydown', restoreOutline);
  2341. }
  2342. // @function restoreOutline()
  2343. // Cancels the effects of a previous [`L.DomUtil.preventOutline`]().
  2344. function restoreOutline() {
  2345. if (!_outlineElement) { return; }
  2346. _outlineElement.style.outline = _outlineStyle;
  2347. _outlineElement = undefined;
  2348. _outlineStyle = undefined;
  2349. off(window, 'keydown', restoreOutline);
  2350. }
  2351. var DomUtil = (Object.freeze || Object)({
  2352. TRANSFORM: TRANSFORM,
  2353. TRANSITION: TRANSITION,
  2354. TRANSITION_END: TRANSITION_END,
  2355. get: get,
  2356. getStyle: getStyle,
  2357. create: create$1,
  2358. remove: remove,
  2359. empty: empty,
  2360. toFront: toFront,
  2361. toBack: toBack,
  2362. hasClass: hasClass,
  2363. addClass: addClass,
  2364. removeClass: removeClass,
  2365. setClass: setClass,
  2366. getClass: getClass,
  2367. setOpacity: setOpacity,
  2368. testProp: testProp,
  2369. setTransform: setTransform,
  2370. setPosition: setPosition,
  2371. getPosition: getPosition,
  2372. disableTextSelection: disableTextSelection,
  2373. enableTextSelection: enableTextSelection,
  2374. disableImageDrag: disableImageDrag,
  2375. enableImageDrag: enableImageDrag,
  2376. preventOutline: preventOutline,
  2377. restoreOutline: restoreOutline
  2378. });
  2379. /*
  2380. * @class PosAnimation
  2381. * @aka L.PosAnimation
  2382. * @inherits Evented
  2383. * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
  2384. *
  2385. * @example
  2386. * ```js
  2387. * var fx = new L.PosAnimation();
  2388. * fx.run(el, [300, 500], 0.5);
  2389. * ```
  2390. *
  2391. * @constructor L.PosAnimation()
  2392. * Creates a `PosAnimation` object.
  2393. *
  2394. */
  2395. var PosAnimation = Evented.extend({
  2396. // @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
  2397. // Run an animation of a given element to a new position, optionally setting
  2398. // duration in seconds (`0.25` by default) and easing linearity factor (3rd
  2399. // argument of the [cubic bezier curve](http://cubic-bezier.com/#0,0,.5,1),
  2400. // `0.5` by default).
  2401. run: function (el, newPos, duration, easeLinearity) {
  2402. this.stop();
  2403. this._el = el;
  2404. this._inProgress = true;
  2405. this._duration = duration || 0.25;
  2406. this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
  2407. this._startPos = getPosition(el);
  2408. this._offset = newPos.subtract(this._startPos);
  2409. this._startTime = +new Date();
  2410. // @event start: Event
  2411. // Fired when the animation starts
  2412. this.fire('start');
  2413. this._animate();
  2414. },
  2415. // @method stop()
  2416. // Stops the animation (if currently running).
  2417. stop: function () {
  2418. if (!this._inProgress) { return; }
  2419. this._step(true);
  2420. this._complete();
  2421. },
  2422. _animate: function () {
  2423. // animation loop
  2424. this._animId = requestAnimFrame(this._animate, this);
  2425. this._step();
  2426. },
  2427. _step: function (round) {
  2428. var elapsed = (+new Date()) - this._startTime,
  2429. duration = this._duration * 1000;
  2430. if (elapsed < duration) {
  2431. this._runFrame(this._easeOut(elapsed / duration), round);
  2432. } else {
  2433. this._runFrame(1);
  2434. this._complete();
  2435. }
  2436. },
  2437. _runFrame: function (progress, round) {
  2438. var pos = this._startPos.add(this._offset.multiplyBy(progress));
  2439. if (round) {
  2440. pos._round();
  2441. }
  2442. setPosition(this._el, pos);
  2443. // @event step: Event
  2444. // Fired continuously during the animation.
  2445. this.fire('step');
  2446. },
  2447. _complete: function () {
  2448. cancelAnimFrame(this._animId);
  2449. this._inProgress = false;
  2450. // @event end: Event
  2451. // Fired when the animation ends.
  2452. this.fire('end');
  2453. },
  2454. _easeOut: function (t) {
  2455. return 1 - Math.pow(1 - t, this._easeOutPower);
  2456. }
  2457. });
  2458. /*
  2459. * @class Map
  2460. * @aka L.Map
  2461. * @inherits Evented
  2462. *
  2463. * The central class of the API — it is used to create a map on a page and manipulate it.
  2464. *
  2465. * @example
  2466. *
  2467. * ```js
  2468. * // initialize the map on the "map" div with a given center and zoom
  2469. * var map = L.map('map', {
  2470. * center: [51.505, -0.09],
  2471. * zoom: 13
  2472. * });
  2473. * ```
  2474. *
  2475. */
  2476. var Map = Evented.extend({
  2477. options: {
  2478. // @section Map State Options
  2479. // @option crs: CRS = L.CRS.EPSG3857
  2480. // The [Coordinate Reference System](#crs) to use. Don't change this if you're not
  2481. // sure what it means.
  2482. crs: EPSG3857,
  2483. // @option center: LatLng = undefined
  2484. // Initial geographic center of the map
  2485. center: undefined,
  2486. // @option zoom: Number = undefined
  2487. // Initial map zoom level
  2488. zoom: undefined,
  2489. // @option minZoom: Number = *
  2490. // Minimum zoom level of the map.
  2491. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2492. // the lowest of their `minZoom` options will be used instead.
  2493. minZoom: undefined,
  2494. // @option maxZoom: Number = *
  2495. // Maximum zoom level of the map.
  2496. // If not specified and at least one `GridLayer` or `TileLayer` is in the map,
  2497. // the highest of their `maxZoom` options will be used instead.
  2498. maxZoom: undefined,
  2499. // @option layers: Layer[] = []
  2500. // Array of layers that will be added to the map initially
  2501. layers: [],
  2502. // @option maxBounds: LatLngBounds = null
  2503. // When this option is set, the map restricts the view to the given
  2504. // geographical bounds, bouncing the user back if the user tries to pan
  2505. // outside the view. To set the restriction dynamically, use
  2506. // [`setMaxBounds`](#map-setmaxbounds) method.
  2507. maxBounds: undefined,
  2508. // @option renderer: Renderer = *
  2509. // The default method for drawing vector layers on the map. `L.SVG`
  2510. // or `L.Canvas` by default depending on browser support.
  2511. renderer: undefined,
  2512. // @section Animation Options
  2513. // @option zoomAnimation: Boolean = true
  2514. // Whether the map zoom animation is enabled. By default it's enabled
  2515. // in all browsers that support CSS3 Transitions except Android.
  2516. zoomAnimation: true,
  2517. // @option zoomAnimationThreshold: Number = 4
  2518. // Won't animate zoom if the zoom difference exceeds this value.
  2519. zoomAnimationThreshold: 4,
  2520. // @option fadeAnimation: Boolean = true
  2521. // Whether the tile fade animation is enabled. By default it's enabled
  2522. // in all browsers that support CSS3 Transitions except Android.
  2523. fadeAnimation: true,
  2524. // @option markerZoomAnimation: Boolean = true
  2525. // Whether markers animate their zoom with the zoom animation, if disabled
  2526. // they will disappear for the length of the animation. By default it's
  2527. // enabled in all browsers that support CSS3 Transitions except Android.
  2528. markerZoomAnimation: true,
  2529. // @option transform3DLimit: Number = 2^23
  2530. // Defines the maximum size of a CSS translation transform. The default
  2531. // value should not be changed unless a web browser positions layers in
  2532. // the wrong place after doing a large `panBy`.
  2533. transform3DLimit: 8388608, // Precision limit of a 32-bit float
  2534. // @section Interaction Options
  2535. // @option zoomSnap: Number = 1
  2536. // Forces the map's zoom level to always be a multiple of this, particularly
  2537. // right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom.
  2538. // By default, the zoom level snaps to the nearest integer; lower values
  2539. // (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0`
  2540. // means the zoom level will not be snapped after `fitBounds` or a pinch-zoom.
  2541. zoomSnap: 1,
  2542. // @option zoomDelta: Number = 1
  2543. // Controls how much the map's zoom level will change after a
  2544. // [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+`
  2545. // or `-` on the keyboard, or using the [zoom controls](#control-zoom).
  2546. // Values smaller than `1` (e.g. `0.5`) allow for greater granularity.
  2547. zoomDelta: 1,
  2548. // @option trackResize: Boolean = true
  2549. // Whether the map automatically handles browser window resize to update itself.
  2550. trackResize: true
  2551. },
  2552. initialize: function (id, options) { // (HTMLElement or String, Object)
  2553. options = setOptions(this, options);
  2554. this._initContainer(id);
  2555. this._initLayout();
  2556. // hack for https://github.com/Leaflet/Leaflet/issues/1980
  2557. this._onResize = bind(this._onResize, this);
  2558. this._initEvents();
  2559. if (options.maxBounds) {
  2560. this.setMaxBounds(options.maxBounds);
  2561. }
  2562. if (options.zoom !== undefined) {
  2563. this._zoom = this._limitZoom(options.zoom);
  2564. }
  2565. if (options.center && options.zoom !== undefined) {
  2566. this.setView(toLatLng(options.center), options.zoom, {reset: true});
  2567. }
  2568. this._handlers = [];
  2569. this._layers = {};
  2570. this._zoomBoundLayers = {};
  2571. this._sizeChanged = true;
  2572. this.callInitHooks();
  2573. // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
  2574. this._zoomAnimated = TRANSITION && any3d && !mobileOpera &&
  2575. this.options.zoomAnimation;
  2576. // zoom transitions run with the same duration for all layers, so if one of transitionend events
  2577. // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
  2578. if (this._zoomAnimated) {
  2579. this._createAnimProxy();
  2580. on(this._proxy, TRANSITION_END, this._catchTransitionEnd, this);
  2581. }
  2582. this._addLayers(this.options.layers);
  2583. },
  2584. // @section Methods for modifying map state
  2585. // @method setView(center: LatLng, zoom: Number, options?: Zoom/pan options): this
  2586. // Sets the view of the map (geographical center and zoom) with the given
  2587. // animation options.
  2588. setView: function (center, zoom, options) {
  2589. zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);
  2590. center = this._limitCenter(toLatLng(center), zoom, this.options.maxBounds);
  2591. options = options || {};
  2592. this._stop();
  2593. if (this._loaded && !options.reset && options !== true) {
  2594. if (options.animate !== undefined) {
  2595. options.zoom = extend({animate: options.animate}, options.zoom);
  2596. options.pan = extend({animate: options.animate, duration: options.duration}, options.pan);
  2597. }
  2598. // try animating pan or zoom
  2599. var moved = (this._zoom !== zoom) ?
  2600. this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
  2601. this._tryAnimatedPan(center, options.pan);
  2602. if (moved) {
  2603. // prevent resize handler call, the view will refresh after animation anyway
  2604. clearTimeout(this._sizeTimer);
  2605. return this;
  2606. }
  2607. }
  2608. // animation didn't start, just reset the map view
  2609. this._resetView(center, zoom);
  2610. return this;
  2611. },
  2612. // @method setZoom(zoom: Number, options?: Zoom/pan options): this
  2613. // Sets the zoom of the map.
  2614. setZoom: function (zoom, options) {
  2615. if (!this._loaded) {
  2616. this._zoom = zoom;
  2617. return this;
  2618. }
  2619. return this.setView(this.getCenter(), zoom, {zoom: options});
  2620. },
  2621. // @method zoomIn(delta?: Number, options?: Zoom options): this
  2622. // Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2623. zoomIn: function (delta, options) {
  2624. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2625. return this.setZoom(this._zoom + delta, options);
  2626. },
  2627. // @method zoomOut(delta?: Number, options?: Zoom options): this
  2628. // Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default).
  2629. zoomOut: function (delta, options) {
  2630. delta = delta || (any3d ? this.options.zoomDelta : 1);
  2631. return this.setZoom(this._zoom - delta, options);
  2632. },
  2633. // @method setZoomAround(latlng: LatLng, zoom: Number, options: Zoom options): this
  2634. // Zooms the map while keeping a specified geographical point on the map
  2635. // stationary (e.g. used internally for scroll zoom and double-click zoom).
  2636. // @alternative
  2637. // @method setZoomAround(offset: Point, zoom: Number, options: Zoom options): this
  2638. // Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
  2639. setZoomAround: function (latlng, zoom, options) {
  2640. var scale = this.getZoomScale(zoom),
  2641. viewHalf = this.getSize().divideBy(2),
  2642. containerPoint = latlng instanceof Point ? latlng : this.latLngToContainerPoint(latlng),
  2643. centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
  2644. newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
  2645. return this.setView(newCenter, zoom, {zoom: options});
  2646. },
  2647. _getBoundsCenterZoom: function (bounds, options) {
  2648. options = options || {};
  2649. bounds = bounds.getBounds ? bounds.getBounds() : toLatLngBounds(bounds);
  2650. var paddingTL = toPoint(options.paddingTopLeft || options.padding || [0, 0]),
  2651. paddingBR = toPoint(options.paddingBottomRight || options.padding || [0, 0]),
  2652. zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR));
  2653. zoom = (typeof options.maxZoom === 'number') ? Math.min(options.maxZoom, zoom) : zoom;
  2654. if (zoom === Infinity) {
  2655. return {
  2656. center: bounds.getCenter(),
  2657. zoom: zoom
  2658. };
  2659. }
  2660. var paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
  2661. swPoint = this.project(bounds.getSouthWest(), zoom),
  2662. nePoint = this.project(bounds.getNorthEast(), zoom),
  2663. center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
  2664. return {
  2665. center: center,
  2666. zoom: zoom
  2667. };
  2668. },
  2669. // @method fitBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2670. // Sets a map view that contains the given geographical bounds with the
  2671. // maximum zoom level possible.
  2672. fitBounds: function (bounds, options) {
  2673. bounds = toLatLngBounds(bounds);
  2674. if (!bounds.isValid()) {
  2675. throw new Error('Bounds are not valid.');
  2676. }
  2677. var target = this._getBoundsCenterZoom(bounds, options);
  2678. return this.setView(target.center, target.zoom, options);
  2679. },
  2680. // @method fitWorld(options?: fitBounds options): this
  2681. // Sets a map view that mostly contains the whole world with the maximum
  2682. // zoom level possible.
  2683. fitWorld: function (options) {
  2684. return this.fitBounds([[-90, -180], [90, 180]], options);
  2685. },
  2686. // @method panTo(latlng: LatLng, options?: Pan options): this
  2687. // Pans the map to a given center.
  2688. panTo: function (center, options) { // (LatLng)
  2689. return this.setView(center, this._zoom, {pan: options});
  2690. },
  2691. // @method panBy(offset: Point, options?: Pan options): this
  2692. // Pans the map by a given number of pixels (animated).
  2693. panBy: function (offset, options) {
  2694. offset = toPoint(offset).round();
  2695. options = options || {};
  2696. if (!offset.x && !offset.y) {
  2697. return this.fire('moveend');
  2698. }
  2699. // If we pan too far, Chrome gets issues with tiles
  2700. // and makes them disappear or appear in the wrong place (slightly offset) #2602
  2701. if (options.animate !== true && !this.getSize().contains(offset)) {
  2702. this._resetView(this.unproject(this.project(this.getCenter()).add(offset)), this.getZoom());
  2703. return this;
  2704. }
  2705. if (!this._panAnim) {
  2706. this._panAnim = new PosAnimation();
  2707. this._panAnim.on({
  2708. 'step': this._onPanTransitionStep,
  2709. 'end': this._onPanTransitionEnd
  2710. }, this);
  2711. }
  2712. // don't fire movestart if animating inertia
  2713. if (!options.noMoveStart) {
  2714. this.fire('movestart');
  2715. }
  2716. // animate pan unless animate: false specified
  2717. if (options.animate !== false) {
  2718. addClass(this._mapPane, 'leaflet-pan-anim');
  2719. var newPos = this._getMapPanePos().subtract(offset).round();
  2720. this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
  2721. } else {
  2722. this._rawPanBy(offset);
  2723. this.fire('move').fire('moveend');
  2724. }
  2725. return this;
  2726. },
  2727. // @method flyTo(latlng: LatLng, zoom?: Number, options?: Zoom/pan options): this
  2728. // Sets the view of the map (geographical center and zoom) performing a smooth
  2729. // pan-zoom animation.
  2730. flyTo: function (targetCenter, targetZoom, options) {
  2731. options = options || {};
  2732. if (options.animate === false || !any3d) {
  2733. return this.setView(targetCenter, targetZoom, options);
  2734. }
  2735. this._stop();
  2736. var from = this.project(this.getCenter()),
  2737. to = this.project(targetCenter),
  2738. size = this.getSize(),
  2739. startZoom = this._zoom;
  2740. targetCenter = toLatLng(targetCenter);
  2741. targetZoom = targetZoom === undefined ? startZoom : targetZoom;
  2742. var w0 = Math.max(size.x, size.y),
  2743. w1 = w0 * this.getZoomScale(startZoom, targetZoom),
  2744. u1 = (to.distanceTo(from)) || 1,
  2745. rho = 1.42,
  2746. rho2 = rho * rho;
  2747. function r(i) {
  2748. var s1 = i ? -1 : 1,
  2749. s2 = i ? w1 : w0,
  2750. t1 = w1 * w1 - w0 * w0 + s1 * rho2 * rho2 * u1 * u1,
  2751. b1 = 2 * s2 * rho2 * u1,
  2752. b = t1 / b1,
  2753. sq = Math.sqrt(b * b + 1) - b;
  2754. // workaround for floating point precision bug when sq = 0, log = -Infinite,
  2755. // thus triggering an infinite loop in flyTo
  2756. var log = sq < 0.000000001 ? -18 : Math.log(sq);
  2757. return log;
  2758. }
  2759. function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }
  2760. function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }
  2761. function tanh(n) { return sinh(n) / cosh(n); }
  2762. var r0 = r(0);
  2763. function w(s) { return w0 * (cosh(r0) / cosh(r0 + rho * s)); }
  2764. function u(s) { return w0 * (cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2; }
  2765. function easeOut(t) { return 1 - Math.pow(1 - t, 1.5); }
  2766. var start = Date.now(),
  2767. S = (r(1) - r0) / rho,
  2768. duration = options.duration ? 1000 * options.duration : 1000 * S * 0.8;
  2769. function frame() {
  2770. var t = (Date.now() - start) / duration,
  2771. s = easeOut(t) * S;
  2772. if (t <= 1) {
  2773. this._flyToFrame = requestAnimFrame(frame, this);
  2774. this._move(
  2775. this.unproject(from.add(to.subtract(from).multiplyBy(u(s) / u1)), startZoom),
  2776. this.getScaleZoom(w0 / w(s), startZoom),
  2777. {flyTo: true});
  2778. } else {
  2779. this
  2780. ._move(targetCenter, targetZoom)
  2781. ._moveEnd(true);
  2782. }
  2783. }
  2784. this._moveStart(true, options.noMoveStart);
  2785. frame.call(this);
  2786. return this;
  2787. },
  2788. // @method flyToBounds(bounds: LatLngBounds, options?: fitBounds options): this
  2789. // Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto),
  2790. // but takes a bounds parameter like [`fitBounds`](#map-fitbounds).
  2791. flyToBounds: function (bounds, options) {
  2792. var target = this._getBoundsCenterZoom(bounds, options);
  2793. return this.flyTo(target.center, target.zoom, options);
  2794. },
  2795. // @method setMaxBounds(bounds: Bounds): this
  2796. // Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option).
  2797. setMaxBounds: function (bounds) {
  2798. bounds = toLatLngBounds(bounds);
  2799. if (!bounds.isValid()) {
  2800. this.options.maxBounds = null;
  2801. return this.off('moveend', this._panInsideMaxBounds);
  2802. } else if (this.options.maxBounds) {
  2803. this.off('moveend', this._panInsideMaxBounds);
  2804. }
  2805. this.options.maxBounds = bounds;
  2806. if (this._loaded) {
  2807. this._panInsideMaxBounds();
  2808. }
  2809. return this.on('moveend', this._panInsideMaxBounds);
  2810. },
  2811. // @method setMinZoom(zoom: Number): this
  2812. // Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option).
  2813. setMinZoom: function (zoom) {
  2814. var oldZoom = this.options.minZoom;
  2815. this.options.minZoom = zoom;
  2816. if (this._loaded && oldZoom !== zoom) {
  2817. this.fire('zoomlevelschange');
  2818. if (this.getZoom() < this.options.minZoom) {
  2819. return this.setZoom(zoom);
  2820. }
  2821. }
  2822. return this;
  2823. },
  2824. // @method setMaxZoom(zoom: Number): this
  2825. // Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option).
  2826. setMaxZoom: function (zoom) {
  2827. var oldZoom = this.options.maxZoom;
  2828. this.options.maxZoom = zoom;
  2829. if (this._loaded && oldZoom !== zoom) {
  2830. this.fire('zoomlevelschange');
  2831. if (this.getZoom() > this.options.maxZoom) {
  2832. return this.setZoom(zoom);
  2833. }
  2834. }
  2835. return this;
  2836. },
  2837. // @method panInsideBounds(bounds: LatLngBounds, options?: Pan options): this
  2838. // 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.
  2839. panInsideBounds: function (bounds, options) {
  2840. this._enforcingBounds = true;
  2841. var center = this.getCenter(),
  2842. newCenter = this._limitCenter(center, this._zoom, toLatLngBounds(bounds));
  2843. if (!center.equals(newCenter)) {
  2844. this.panTo(newCenter, options);
  2845. }
  2846. this._enforcingBounds = false;
  2847. return this;
  2848. },
  2849. // @method invalidateSize(options: Zoom/pan options): this
  2850. // Checks if the map container size changed and updates the map if so —
  2851. // call it after you've changed the map size dynamically, also animating
  2852. // pan by default. If `options.pan` is `false`, panning will not occur.
  2853. // If `options.debounceMoveend` is `true`, it will delay `moveend` event so
  2854. // that it doesn't happen often even if the method is called many
  2855. // times in a row.
  2856. // @alternative
  2857. // @method invalidateSize(animate: Boolean): this
  2858. // Checks if the map container size changed and updates the map if so —
  2859. // call it after you've changed the map size dynamically, also animating
  2860. // pan by default.
  2861. invalidateSize: function (options) {
  2862. if (!this._loaded) { return this; }
  2863. options = extend({
  2864. animate: false,
  2865. pan: true
  2866. }, options === true ? {animate: true} : options);
  2867. var oldSize = this.getSize();
  2868. this._sizeChanged = true;
  2869. this._lastCenter = null;
  2870. var newSize = this.getSize(),
  2871. oldCenter = oldSize.divideBy(2).round(),
  2872. newCenter = newSize.divideBy(2).round(),
  2873. offset = oldCenter.subtract(newCenter);
  2874. if (!offset.x && !offset.y) { return this; }
  2875. if (options.animate && options.pan) {
  2876. this.panBy(offset);
  2877. } else {
  2878. if (options.pan) {
  2879. this._rawPanBy(offset);
  2880. }
  2881. this.fire('move');
  2882. if (options.debounceMoveend) {
  2883. clearTimeout(this._sizeTimer);
  2884. this._sizeTimer = setTimeout(bind(this.fire, this, 'moveend'), 200);
  2885. } else {
  2886. this.fire('moveend');
  2887. }
  2888. }
  2889. // @section Map state change events
  2890. // @event resize: ResizeEvent
  2891. // Fired when the map is resized.
  2892. return this.fire('resize', {
  2893. oldSize: oldSize,
  2894. newSize: newSize
  2895. });
  2896. },
  2897. // @section Methods for modifying map state
  2898. // @method stop(): this
  2899. // Stops the currently running `panTo` or `flyTo` animation, if any.
  2900. stop: function () {
  2901. this.setZoom(this._limitZoom(this._zoom));
  2902. if (!this.options.zoomSnap) {
  2903. this.fire('viewreset');
  2904. }
  2905. return this._stop();
  2906. },
  2907. // @section Geolocation methods
  2908. // @method locate(options?: Locate options): this
  2909. // Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound)
  2910. // event with location data on success or a [`locationerror`](#map-locationerror) event on failure,
  2911. // and optionally sets the map view to the user's location with respect to
  2912. // detection accuracy (or to the world view if geolocation failed).
  2913. // Note that, if your page doesn't use HTTPS, this method will fail in
  2914. // modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins))
  2915. // See `Locate options` for more details.
  2916. locate: function (options) {
  2917. options = this._locateOptions = extend({
  2918. timeout: 10000,
  2919. watch: false
  2920. // setView: false
  2921. // maxZoom: <Number>
  2922. // maximumAge: 0
  2923. // enableHighAccuracy: false
  2924. }, options);
  2925. if (!('geolocation' in navigator)) {
  2926. this._handleGeolocationError({
  2927. code: 0,
  2928. message: 'Geolocation not supported.'
  2929. });
  2930. return this;
  2931. }
  2932. var onResponse = bind(this._handleGeolocationResponse, this),
  2933. onError = bind(this._handleGeolocationError, this);
  2934. if (options.watch) {
  2935. this._locationWatchId =
  2936. navigator.geolocation.watchPosition(onResponse, onError, options);
  2937. } else {
  2938. navigator.geolocation.getCurrentPosition(onResponse, onError, options);
  2939. }
  2940. return this;
  2941. },
  2942. // @method stopLocate(): this
  2943. // Stops watching location previously initiated by `map.locate({watch: true})`
  2944. // and aborts resetting the map view if map.locate was called with
  2945. // `{setView: true}`.
  2946. stopLocate: function () {
  2947. if (navigator.geolocation && navigator.geolocation.clearWatch) {
  2948. navigator.geolocation.clearWatch(this._locationWatchId);
  2949. }
  2950. if (this._locateOptions) {
  2951. this._locateOptions.setView = false;
  2952. }
  2953. return this;
  2954. },
  2955. _handleGeolocationError: function (error) {
  2956. var c = error.code,
  2957. message = error.message ||
  2958. (c === 1 ? 'permission denied' :
  2959. (c === 2 ? 'position unavailable' : 'timeout'));
  2960. if (this._locateOptions.setView && !this._loaded) {
  2961. this.fitWorld();
  2962. }
  2963. // @section Location events
  2964. // @event locationerror: ErrorEvent
  2965. // Fired when geolocation (using the [`locate`](#map-locate) method) failed.
  2966. this.fire('locationerror', {
  2967. code: c,
  2968. message: 'Geolocation error: ' + message + '.'
  2969. });
  2970. },
  2971. _handleGeolocationResponse: function (pos) {
  2972. var lat = pos.coords.latitude,
  2973. lng = pos.coords.longitude,
  2974. latlng = new LatLng(lat, lng),
  2975. bounds = latlng.toBounds(pos.coords.accuracy),
  2976. options = this._locateOptions;
  2977. if (options.setView) {
  2978. var zoom = this.getBoundsZoom(bounds);
  2979. this.setView(latlng, options.maxZoom ? Math.min(zoom, options.maxZoom) : zoom);
  2980. }
  2981. var data = {
  2982. latlng: latlng,
  2983. bounds: bounds,
  2984. timestamp: pos.timestamp
  2985. };
  2986. for (var i in pos.coords) {
  2987. if (typeof pos.coords[i] === 'number') {
  2988. data[i] = pos.coords[i];
  2989. }
  2990. }
  2991. // @event locationfound: LocationEvent
  2992. // Fired when geolocation (using the [`locate`](#map-locate) method)
  2993. // went successfully.
  2994. this.fire('locationfound', data);
  2995. },
  2996. // TODO Appropriate docs section?
  2997. // @section Other Methods
  2998. // @method addHandler(name: String, HandlerClass: Function): this
  2999. // Adds a new `Handler` to the map, given its name and constructor function.
  3000. addHandler: function (name, HandlerClass) {
  3001. if (!HandlerClass) { return this; }
  3002. var handler = this[name] = new HandlerClass(this);
  3003. this._handlers.push(handler);
  3004. if (this.options[name]) {
  3005. handler.enable();
  3006. }
  3007. return this;
  3008. },
  3009. // @method remove(): this
  3010. // Destroys the map and clears all related event listeners.
  3011. remove: function () {
  3012. this._initEvents(true);
  3013. if (this._containerId !== this._container._leaflet_id) {
  3014. throw new Error('Map container is being reused by another instance');
  3015. }
  3016. try {
  3017. // throws error in IE6-8
  3018. delete this._container._leaflet_id;
  3019. delete this._containerId;
  3020. } catch (e) {
  3021. /*eslint-disable */
  3022. this._container._leaflet_id = undefined;
  3023. /* eslint-enable */
  3024. this._containerId = undefined;
  3025. }
  3026. if (this._locationWatchId !== undefined) {
  3027. this.stopLocate();
  3028. }
  3029. this._stop();
  3030. remove(this._mapPane);
  3031. if (this._clearControlPos) {
  3032. this._clearControlPos();
  3033. }
  3034. this._clearHandlers();
  3035. if (this._loaded) {
  3036. // @section Map state change events
  3037. // @event unload: Event
  3038. // Fired when the map is destroyed with [remove](#map-remove) method.
  3039. this.fire('unload');
  3040. }
  3041. var i;
  3042. for (i in this._layers) {
  3043. this._layers[i].remove();
  3044. }
  3045. for (i in this._panes) {
  3046. remove(this._panes[i]);
  3047. }
  3048. this._layers = [];
  3049. this._panes = [];
  3050. delete this._mapPane;
  3051. delete this._renderer;
  3052. return this;
  3053. },
  3054. // @section Other Methods
  3055. // @method createPane(name: String, container?: HTMLElement): HTMLElement
  3056. // Creates a new [map pane](#map-pane) with the given name if it doesn't exist already,
  3057. // then returns it. The pane is created as a child of `container`, or
  3058. // as a child of the main map pane if not set.
  3059. createPane: function (name, container) {
  3060. var className = 'leaflet-pane' + (name ? ' leaflet-' + name.replace('Pane', '') + '-pane' : ''),
  3061. pane = create$1('div', className, container || this._mapPane);
  3062. if (name) {
  3063. this._panes[name] = pane;
  3064. }
  3065. return pane;
  3066. },
  3067. // @section Methods for Getting Map State
  3068. // @method getCenter(): LatLng
  3069. // Returns the geographical center of the map view
  3070. getCenter: function () {
  3071. this._checkIfLoaded();
  3072. if (this._lastCenter && !this._moved()) {
  3073. return this._lastCenter;
  3074. }
  3075. return this.layerPointToLatLng(this._getCenterLayerPoint());
  3076. },
  3077. // @method getZoom(): Number
  3078. // Returns the current zoom level of the map view
  3079. getZoom: function () {
  3080. return this._zoom;
  3081. },
  3082. // @method getBounds(): LatLngBounds
  3083. // Returns the geographical bounds visible in the current map view
  3084. getBounds: function () {
  3085. var bounds = this.getPixelBounds(),
  3086. sw = this.unproject(bounds.getBottomLeft()),
  3087. ne = this.unproject(bounds.getTopRight());
  3088. return new LatLngBounds(sw, ne);
  3089. },
  3090. // @method getMinZoom(): Number
  3091. // 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.
  3092. getMinZoom: function () {
  3093. return this.options.minZoom === undefined ? this._layersMinZoom || 0 : this.options.minZoom;
  3094. },
  3095. // @method getMaxZoom(): Number
  3096. // Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers).
  3097. getMaxZoom: function () {
  3098. return this.options.maxZoom === undefined ?
  3099. (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
  3100. this.options.maxZoom;
  3101. },
  3102. // @method getBoundsZoom(bounds: LatLngBounds, inside?: Boolean): Number
  3103. // Returns the maximum zoom level on which the given bounds fit to the map
  3104. // view in its entirety. If `inside` (optional) is set to `true`, the method
  3105. // instead returns the minimum zoom level on which the map view fits into
  3106. // the given bounds in its entirety.
  3107. getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
  3108. bounds = toLatLngBounds(bounds);
  3109. padding = toPoint(padding || [0, 0]);
  3110. var zoom = this.getZoom() || 0,
  3111. min = this.getMinZoom(),
  3112. max = this.getMaxZoom(),
  3113. nw = bounds.getNorthWest(),
  3114. se = bounds.getSouthEast(),
  3115. size = this.getSize().subtract(padding),
  3116. boundsSize = toBounds(this.project(se, zoom), this.project(nw, zoom)).getSize(),
  3117. snap = any3d ? this.options.zoomSnap : 1,
  3118. scalex = size.x / boundsSize.x,
  3119. scaley = size.y / boundsSize.y,
  3120. scale = inside ? Math.max(scalex, scaley) : Math.min(scalex, scaley);
  3121. zoom = this.getScaleZoom(scale, zoom);
  3122. if (snap) {
  3123. zoom = Math.round(zoom / (snap / 100)) * (snap / 100); // don't jump if within 1% of a snap level
  3124. zoom = inside ? Math.ceil(zoom / snap) * snap : Math.floor(zoom / snap) * snap;
  3125. }
  3126. return Math.max(min, Math.min(max, zoom));
  3127. },
  3128. // @method getSize(): Point
  3129. // Returns the current size of the map container (in pixels).
  3130. getSize: function () {
  3131. if (!this._size || this._sizeChanged) {
  3132. this._size = new Point(
  3133. this._container.clientWidth || 0,
  3134. this._container.clientHeight || 0);
  3135. this._sizeChanged = false;
  3136. }
  3137. return this._size.clone();
  3138. },
  3139. // @method getPixelBounds(): Bounds
  3140. // Returns the bounds of the current map view in projected pixel
  3141. // coordinates (sometimes useful in layer and overlay implementations).
  3142. getPixelBounds: function (center, zoom) {
  3143. var topLeftPoint = this._getTopLeftPoint(center, zoom);
  3144. return new Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
  3145. },
  3146. // TODO: Check semantics - isn't the pixel origin the 0,0 coord relative to
  3147. // the map pane? "left point of the map layer" can be confusing, specially
  3148. // since there can be negative offsets.
  3149. // @method getPixelOrigin(): Point
  3150. // Returns the projected pixel coordinates of the top left point of
  3151. // the map layer (useful in custom layer and overlay implementations).
  3152. getPixelOrigin: function () {
  3153. this._checkIfLoaded();
  3154. return this._pixelOrigin;
  3155. },
  3156. // @method getPixelWorldBounds(zoom?: Number): Bounds
  3157. // Returns the world's bounds in pixel coordinates for zoom level `zoom`.
  3158. // If `zoom` is omitted, the map's current zoom level is used.
  3159. getPixelWorldBounds: function (zoom) {
  3160. return this.options.crs.getProjectedBounds(zoom === undefined ? this.getZoom() : zoom);
  3161. },
  3162. // @section Other Methods
  3163. // @method getPane(pane: String|HTMLElement): HTMLElement
  3164. // Returns a [map pane](#map-pane), given its name or its HTML element (its identity).
  3165. getPane: function (pane) {
  3166. return typeof pane === 'string' ? this._panes[pane] : pane;
  3167. },
  3168. // @method getPanes(): Object
  3169. // Returns a plain object containing the names of all [panes](#map-pane) as keys and
  3170. // the panes as values.
  3171. getPanes: function () {
  3172. return this._panes;
  3173. },
  3174. // @method getContainer: HTMLElement
  3175. // Returns the HTML element that contains the map.
  3176. getContainer: function () {
  3177. return this._container;
  3178. },
  3179. // @section Conversion Methods
  3180. // @method getZoomScale(toZoom: Number, fromZoom: Number): Number
  3181. // Returns the scale factor to be applied to a map transition from zoom level
  3182. // `fromZoom` to `toZoom`. Used internally to help with zoom animations.
  3183. getZoomScale: function (toZoom, fromZoom) {
  3184. // TODO replace with universal implementation after refactoring projections
  3185. var crs = this.options.crs;
  3186. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3187. return crs.scale(toZoom) / crs.scale(fromZoom);
  3188. },
  3189. // @method getScaleZoom(scale: Number, fromZoom: Number): Number
  3190. // Returns the zoom level that the map would end up at, if it is at `fromZoom`
  3191. // level and everything is scaled by a factor of `scale`. Inverse of
  3192. // [`getZoomScale`](#map-getZoomScale).
  3193. getScaleZoom: function (scale, fromZoom) {
  3194. var crs = this.options.crs;
  3195. fromZoom = fromZoom === undefined ? this._zoom : fromZoom;
  3196. var zoom = crs.zoom(scale * crs.scale(fromZoom));
  3197. return isNaN(zoom) ? Infinity : zoom;
  3198. },
  3199. // @method project(latlng: LatLng, zoom: Number): Point
  3200. // Projects a geographical coordinate `LatLng` according to the projection
  3201. // of the map's CRS, then scales it according to `zoom` and the CRS's
  3202. // `Transformation`. The result is pixel coordinate relative to
  3203. // the CRS origin.
  3204. project: function (latlng, zoom) {
  3205. zoom = zoom === undefined ? this._zoom : zoom;
  3206. return this.options.crs.latLngToPoint(toLatLng(latlng), zoom);
  3207. },
  3208. // @method unproject(point: Point, zoom: Number): LatLng
  3209. // Inverse of [`project`](#map-project).
  3210. unproject: function (point, zoom) {
  3211. zoom = zoom === undefined ? this._zoom : zoom;
  3212. return this.options.crs.pointToLatLng(toPoint(point), zoom);
  3213. },
  3214. // @method layerPointToLatLng(point: Point): LatLng
  3215. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3216. // returns the corresponding geographical coordinate (for the current zoom level).
  3217. layerPointToLatLng: function (point) {
  3218. var projectedPoint = toPoint(point).add(this.getPixelOrigin());
  3219. return this.unproject(projectedPoint);
  3220. },
  3221. // @method latLngToLayerPoint(latlng: LatLng): Point
  3222. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3223. // relative to the [origin pixel](#map-getpixelorigin).
  3224. latLngToLayerPoint: function (latlng) {
  3225. var projectedPoint = this.project(toLatLng(latlng))._round();
  3226. return projectedPoint._subtract(this.getPixelOrigin());
  3227. },
  3228. // @method wrapLatLng(latlng: LatLng): LatLng
  3229. // Returns a `LatLng` where `lat` and `lng` has been wrapped according to the
  3230. // map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the
  3231. // CRS's bounds.
  3232. // By default this means longitude is wrapped around the dateline so its
  3233. // value is between -180 and +180 degrees.
  3234. wrapLatLng: function (latlng) {
  3235. return this.options.crs.wrapLatLng(toLatLng(latlng));
  3236. },
  3237. // @method wrapLatLngBounds(bounds: LatLngBounds): LatLngBounds
  3238. // Returns a `LatLngBounds` with the same size as the given one, ensuring that
  3239. // its center is within the CRS's bounds.
  3240. // By default this means the center longitude is wrapped around the dateline so its
  3241. // value is between -180 and +180 degrees, and the majority of the bounds
  3242. // overlaps the CRS's bounds.
  3243. wrapLatLngBounds: function (latlng) {
  3244. return this.options.crs.wrapLatLngBounds(toLatLngBounds(latlng));
  3245. },
  3246. // @method distance(latlng1: LatLng, latlng2: LatLng): Number
  3247. // Returns the distance between two geographical coordinates according to
  3248. // the map's CRS. By default this measures distance in meters.
  3249. distance: function (latlng1, latlng2) {
  3250. return this.options.crs.distance(toLatLng(latlng1), toLatLng(latlng2));
  3251. },
  3252. // @method containerPointToLayerPoint(point: Point): Point
  3253. // Given a pixel coordinate relative to the map container, returns the corresponding
  3254. // pixel coordinate relative to the [origin pixel](#map-getpixelorigin).
  3255. containerPointToLayerPoint: function (point) { // (Point)
  3256. return toPoint(point).subtract(this._getMapPanePos());
  3257. },
  3258. // @method layerPointToContainerPoint(point: Point): Point
  3259. // Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin),
  3260. // returns the corresponding pixel coordinate relative to the map container.
  3261. layerPointToContainerPoint: function (point) { // (Point)
  3262. return toPoint(point).add(this._getMapPanePos());
  3263. },
  3264. // @method containerPointToLatLng(point: Point): LatLng
  3265. // Given a pixel coordinate relative to the map container, returns
  3266. // the corresponding geographical coordinate (for the current zoom level).
  3267. containerPointToLatLng: function (point) {
  3268. var layerPoint = this.containerPointToLayerPoint(toPoint(point));
  3269. return this.layerPointToLatLng(layerPoint);
  3270. },
  3271. // @method latLngToContainerPoint(latlng: LatLng): Point
  3272. // Given a geographical coordinate, returns the corresponding pixel coordinate
  3273. // relative to the map container.
  3274. latLngToContainerPoint: function (latlng) {
  3275. return this.layerPointToContainerPoint(this.latLngToLayerPoint(toLatLng(latlng)));
  3276. },
  3277. // @method mouseEventToContainerPoint(ev: MouseEvent): Point
  3278. // Given a MouseEvent object, returns the pixel coordinate relative to the
  3279. // map container where the event took place.
  3280. mouseEventToContainerPoint: function (e) {
  3281. return getMousePosition(e, this._container);
  3282. },
  3283. // @method mouseEventToLayerPoint(ev: MouseEvent): Point
  3284. // Given a MouseEvent object, returns the pixel coordinate relative to
  3285. // the [origin pixel](#map-getpixelorigin) where the event took place.
  3286. mouseEventToLayerPoint: function (e) {
  3287. return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
  3288. },
  3289. // @method mouseEventToLatLng(ev: MouseEvent): LatLng
  3290. // Given a MouseEvent object, returns geographical coordinate where the
  3291. // event took place.
  3292. mouseEventToLatLng: function (e) { // (MouseEvent)
  3293. return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
  3294. },
  3295. // map initialization methods
  3296. _initContainer: function (id) {
  3297. var container = this._container = get(id);
  3298. if (!container) {
  3299. throw new Error('Map container not found.');
  3300. } else if (container._leaflet_id) {
  3301. throw new Error('Map container is already initialized.');
  3302. }
  3303. on(container, 'scroll', this._onScroll, this);
  3304. this._containerId = stamp(container);
  3305. },
  3306. _initLayout: function () {
  3307. var container = this._container;
  3308. this._fadeAnimated = this.options.fadeAnimation && any3d;
  3309. addClass(container, 'leaflet-container' +
  3310. (touch ? ' leaflet-touch' : '') +
  3311. (retina ? ' leaflet-retina' : '') +
  3312. (ielt9 ? ' leaflet-oldie' : '') +
  3313. (safari ? ' leaflet-safari' : '') +
  3314. (this._fadeAnimated ? ' leaflet-fade-anim' : ''));
  3315. var position = getStyle(container, 'position');
  3316. if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
  3317. container.style.position = 'relative';
  3318. }
  3319. this._initPanes();
  3320. if (this._initControlPos) {
  3321. this._initControlPos();
  3322. }
  3323. },
  3324. _initPanes: function () {
  3325. var panes = this._panes = {};
  3326. this._paneRenderers = {};
  3327. // @section
  3328. //
  3329. // Panes are DOM elements used to control the ordering of layers on the map. You
  3330. // can access panes with [`map.getPane`](#map-getpane) or
  3331. // [`map.getPanes`](#map-getpanes) methods. New panes can be created with the
  3332. // [`map.createPane`](#map-createpane) method.
  3333. //
  3334. // Every map has the following default panes that differ only in zIndex.
  3335. //
  3336. // @pane mapPane: HTMLElement = 'auto'
  3337. // Pane that contains all other map panes
  3338. this._mapPane = this.createPane('mapPane', this._container);
  3339. setPosition(this._mapPane, new Point(0, 0));
  3340. // @pane tilePane: HTMLElement = 200
  3341. // Pane for `GridLayer`s and `TileLayer`s
  3342. this.createPane('tilePane');
  3343. // @pane overlayPane: HTMLElement = 400
  3344. // Pane for vectors (`Path`s, like `Polyline`s and `Polygon`s), `ImageOverlay`s and `VideoOverlay`s
  3345. this.createPane('shadowPane');
  3346. // @pane shadowPane: HTMLElement = 500
  3347. // Pane for overlay shadows (e.g. `Marker` shadows)
  3348. this.createPane('overlayPane');
  3349. // @pane markerPane: HTMLElement = 600
  3350. // Pane for `Icon`s of `Marker`s
  3351. this.createPane('markerPane');
  3352. // @pane tooltipPane: HTMLElement = 650
  3353. // Pane for `Tooltip`s.
  3354. this.createPane('tooltipPane');
  3355. // @pane popupPane: HTMLElement = 700
  3356. // Pane for `Popup`s.
  3357. this.createPane('popupPane');
  3358. if (!this.options.markerZoomAnimation) {
  3359. addClass(panes.markerPane, 'leaflet-zoom-hide');
  3360. addClass(panes.shadowPane, 'leaflet-zoom-hide');
  3361. }
  3362. },
  3363. // private methods that modify map state
  3364. // @section Map state change events
  3365. _resetView: function (center, zoom) {
  3366. setPosition(this._mapPane, new Point(0, 0));
  3367. var loading = !this._loaded;
  3368. this._loaded = true;
  3369. zoom = this._limitZoom(zoom);
  3370. this.fire('viewprereset');
  3371. var zoomChanged = this._zoom !== zoom;
  3372. this
  3373. ._moveStart(zoomChanged, false)
  3374. ._move(center, zoom)
  3375. ._moveEnd(zoomChanged);
  3376. // @event viewreset: Event
  3377. // Fired when the map needs to redraw its content (this usually happens
  3378. // on map zoom or load). Very useful for creating custom overlays.
  3379. this.fire('viewreset');
  3380. // @event load: Event
  3381. // Fired when the map is initialized (when its center and zoom are set
  3382. // for the first time).
  3383. if (loading) {
  3384. this.fire('load');
  3385. }
  3386. },
  3387. _moveStart: function (zoomChanged, noMoveStart) {
  3388. // @event zoomstart: Event
  3389. // Fired when the map zoom is about to change (e.g. before zoom animation).
  3390. // @event movestart: Event
  3391. // Fired when the view of the map starts changing (e.g. user starts dragging the map).
  3392. if (zoomChanged) {
  3393. this.fire('zoomstart');
  3394. }
  3395. if (!noMoveStart) {
  3396. this.fire('movestart');
  3397. }
  3398. return this;
  3399. },
  3400. _move: function (center, zoom, data) {
  3401. if (zoom === undefined) {
  3402. zoom = this._zoom;
  3403. }
  3404. var zoomChanged = this._zoom !== zoom;
  3405. this._zoom = zoom;
  3406. this._lastCenter = center;
  3407. this._pixelOrigin = this._getNewPixelOrigin(center);
  3408. // @event zoom: Event
  3409. // Fired repeatedly during any change in zoom level, including zoom
  3410. // and fly animations.
  3411. if (zoomChanged || (data && data.pinch)) { // Always fire 'zoom' if pinching because #3530
  3412. this.fire('zoom', data);
  3413. }
  3414. // @event move: Event
  3415. // Fired repeatedly during any movement of the map, including pan and
  3416. // fly animations.
  3417. return this.fire('move', data);
  3418. },
  3419. _moveEnd: function (zoomChanged) {
  3420. // @event zoomend: Event
  3421. // Fired when the map has changed, after any animations.
  3422. if (zoomChanged) {
  3423. this.fire('zoomend');
  3424. }
  3425. // @event moveend: Event
  3426. // Fired when the center of the map stops changing (e.g. user stopped
  3427. // dragging the map).
  3428. return this.fire('moveend');
  3429. },
  3430. _stop: function () {
  3431. cancelAnimFrame(this._flyToFrame);
  3432. if (this._panAnim) {
  3433. this._panAnim.stop();
  3434. }
  3435. return this;
  3436. },
  3437. _rawPanBy: function (offset) {
  3438. setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
  3439. },
  3440. _getZoomSpan: function () {
  3441. return this.getMaxZoom() - this.getMinZoom();
  3442. },
  3443. _panInsideMaxBounds: function () {
  3444. if (!this._enforcingBounds) {
  3445. this.panInsideBounds(this.options.maxBounds);
  3446. }
  3447. },
  3448. _checkIfLoaded: function () {
  3449. if (!this._loaded) {
  3450. throw new Error('Set map center and zoom first.');
  3451. }
  3452. },
  3453. // DOM event handling
  3454. // @section Interaction events
  3455. _initEvents: function (remove$$1) {
  3456. this._targets = {};
  3457. this._targets[stamp(this._container)] = this;
  3458. var onOff = remove$$1 ? off : on;
  3459. // @event click: MouseEvent
  3460. // Fired when the user clicks (or taps) the map.
  3461. // @event dblclick: MouseEvent
  3462. // Fired when the user double-clicks (or double-taps) the map.
  3463. // @event mousedown: MouseEvent
  3464. // Fired when the user pushes the mouse button on the map.
  3465. // @event mouseup: MouseEvent
  3466. // Fired when the user releases the mouse button on the map.
  3467. // @event mouseover: MouseEvent
  3468. // Fired when the mouse enters the map.
  3469. // @event mouseout: MouseEvent
  3470. // Fired when the mouse leaves the map.
  3471. // @event mousemove: MouseEvent
  3472. // Fired while the mouse moves over the map.
  3473. // @event contextmenu: MouseEvent
  3474. // Fired when the user pushes the right mouse button on the map, prevents
  3475. // default browser context menu from showing if there are listeners on
  3476. // this event. Also fired on mobile when the user holds a single touch
  3477. // for a second (also called long press).
  3478. // @event keypress: KeyboardEvent
  3479. // Fired when the user presses a key from the keyboard while the map is focused.
  3480. onOff(this._container, 'click dblclick mousedown mouseup ' +
  3481. 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this);
  3482. if (this.options.trackResize) {
  3483. onOff(window, 'resize', this._onResize, this);
  3484. }
  3485. if (any3d && this.options.transform3DLimit) {
  3486. (remove$$1 ? this.off : this.on).call(this, 'moveend', this._onMoveEnd);
  3487. }
  3488. },
  3489. _onResize: function () {
  3490. cancelAnimFrame(this._resizeRequest);
  3491. this._resizeRequest = requestAnimFrame(
  3492. function () { this.invalidateSize({debounceMoveend: true}); }, this);
  3493. },
  3494. _onScroll: function () {
  3495. this._container.scrollTop = 0;
  3496. this._container.scrollLeft = 0;
  3497. },
  3498. _onMoveEnd: function () {
  3499. var pos = this._getMapPanePos();
  3500. if (Math.max(Math.abs(pos.x), Math.abs(pos.y)) >= this.options.transform3DLimit) {
  3501. // https://bugzilla.mozilla.org/show_bug.cgi?id=1203873 but Webkit also have
  3502. // a pixel offset on very high values, see: http://jsfiddle.net/dg6r5hhb/
  3503. this._resetView(this.getCenter(), this.getZoom());
  3504. }
  3505. },
  3506. _findEventTargets: function (e, type) {
  3507. var targets = [],
  3508. target,
  3509. isHover = type === 'mouseout' || type === 'mouseover',
  3510. src = e.target || e.srcElement,
  3511. dragging = false;
  3512. while (src) {
  3513. target = this._targets[stamp(src)];
  3514. if (target && (type === 'click' || type === 'preclick') && !e._simulated && this._draggableMoved(target)) {
  3515. // Prevent firing click after you just dragged an object.
  3516. dragging = true;
  3517. break;
  3518. }
  3519. if (target && target.listens(type, true)) {
  3520. if (isHover && !isExternalTarget(src, e)) { break; }
  3521. targets.push(target);
  3522. if (isHover) { break; }
  3523. }
  3524. if (src === this._container) { break; }
  3525. src = src.parentNode;
  3526. }
  3527. if (!targets.length && !dragging && !isHover && isExternalTarget(src, e)) {
  3528. targets = [this];
  3529. }
  3530. return targets;
  3531. },
  3532. _handleDOMEvent: function (e) {
  3533. if (!this._loaded || skipped(e)) { return; }
  3534. var type = e.type;
  3535. if (type === 'mousedown' || type === 'keypress') {
  3536. // prevents outline when clicking on keyboard-focusable element
  3537. preventOutline(e.target || e.srcElement);
  3538. }
  3539. this._fireDOMEvent(e, type);
  3540. },
  3541. _mouseEvents: ['click', 'dblclick', 'mouseover', 'mouseout', 'contextmenu'],
  3542. _fireDOMEvent: function (e, type, targets) {
  3543. if (e.type === 'click') {
  3544. // Fire a synthetic 'preclick' event which propagates up (mainly for closing popups).
  3545. // @event preclick: MouseEvent
  3546. // Fired before mouse click on the map (sometimes useful when you
  3547. // want something to happen on click before any existing click
  3548. // handlers start running).
  3549. var synth = extend({}, e);
  3550. synth.type = 'preclick';
  3551. this._fireDOMEvent(synth, synth.type, targets);
  3552. }
  3553. if (e._stopped) { return; }
  3554. // Find the layer the event is propagating from and its parents.
  3555. targets = (targets || []).concat(this._findEventTargets(e, type));
  3556. if (!targets.length) { return; }
  3557. var target = targets[0];
  3558. if (type === 'contextmenu' && target.listens(type, true)) {
  3559. preventDefault(e);
  3560. }
  3561. var data = {
  3562. originalEvent: e
  3563. };
  3564. if (e.type !== 'keypress') {
  3565. var isMarker = target.getLatLng && (!target._radius || target._radius <= 10);
  3566. data.containerPoint = isMarker ?
  3567. this.latLngToContainerPoint(target.getLatLng()) : this.mouseEventToContainerPoint(e);
  3568. data.layerPoint = this.containerPointToLayerPoint(data.containerPoint);
  3569. data.latlng = isMarker ? target.getLatLng() : this.layerPointToLatLng(data.layerPoint);
  3570. }
  3571. for (var i = 0; i < targets.length; i++) {
  3572. targets[i].fire(type, data, true);
  3573. if (data.originalEvent._stopped ||
  3574. (targets[i].options.bubblingMouseEvents === false && indexOf(this._mouseEvents, type) !== -1)) { return; }
  3575. }
  3576. },
  3577. _draggableMoved: function (obj) {
  3578. obj = obj.dragging && obj.dragging.enabled() ? obj : this;
  3579. return (obj.dragging && obj.dragging.moved()) || (this.boxZoom && this.boxZoom.moved());
  3580. },
  3581. _clearHandlers: function () {
  3582. for (var i = 0, len = this._handlers.length; i < len; i++) {
  3583. this._handlers[i].disable();
  3584. }
  3585. },
  3586. // @section Other Methods
  3587. // @method whenReady(fn: Function, context?: Object): this
  3588. // Runs the given function `fn` when the map gets initialized with
  3589. // a view (center and zoom) and at least one layer, or immediately
  3590. // if it's already initialized, optionally passing a function context.
  3591. whenReady: function (callback, context) {
  3592. if (this._loaded) {
  3593. callback.call(context || this, {target: this});
  3594. } else {
  3595. this.on('load', callback, context);
  3596. }
  3597. return this;
  3598. },
  3599. // private methods for getting map state
  3600. _getMapPanePos: function () {
  3601. return getPosition(this._mapPane) || new Point(0, 0);
  3602. },
  3603. _moved: function () {
  3604. var pos = this._getMapPanePos();
  3605. return pos && !pos.equals([0, 0]);
  3606. },
  3607. _getTopLeftPoint: function (center, zoom) {
  3608. var pixelOrigin = center && zoom !== undefined ?
  3609. this._getNewPixelOrigin(center, zoom) :
  3610. this.getPixelOrigin();
  3611. return pixelOrigin.subtract(this._getMapPanePos());
  3612. },
  3613. _getNewPixelOrigin: function (center, zoom) {
  3614. var viewHalf = this.getSize()._divideBy(2);
  3615. return this.project(center, zoom)._subtract(viewHalf)._add(this._getMapPanePos())._round();
  3616. },
  3617. _latLngToNewLayerPoint: function (latlng, zoom, center) {
  3618. var topLeft = this._getNewPixelOrigin(center, zoom);
  3619. return this.project(latlng, zoom)._subtract(topLeft);
  3620. },
  3621. _latLngBoundsToNewLayerBounds: function (latLngBounds, zoom, center) {
  3622. var topLeft = this._getNewPixelOrigin(center, zoom);
  3623. return toBounds([
  3624. this.project(latLngBounds.getSouthWest(), zoom)._subtract(topLeft),
  3625. this.project(latLngBounds.getNorthWest(), zoom)._subtract(topLeft),
  3626. this.project(latLngBounds.getSouthEast(), zoom)._subtract(topLeft),
  3627. this.project(latLngBounds.getNorthEast(), zoom)._subtract(topLeft)
  3628. ]);
  3629. },
  3630. // layer point of the current center
  3631. _getCenterLayerPoint: function () {
  3632. return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
  3633. },
  3634. // offset of the specified place to the current center in pixels
  3635. _getCenterOffset: function (latlng) {
  3636. return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
  3637. },
  3638. // adjust center for view to get inside bounds
  3639. _limitCenter: function (center, zoom, bounds) {
  3640. if (!bounds) { return center; }
  3641. var centerPoint = this.project(center, zoom),
  3642. viewHalf = this.getSize().divideBy(2),
  3643. viewBounds = new Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)),
  3644. offset = this._getBoundsOffset(viewBounds, bounds, zoom);
  3645. // If offset is less than a pixel, ignore.
  3646. // This prevents unstable projections from getting into
  3647. // an infinite loop of tiny offsets.
  3648. if (offset.round().equals([0, 0])) {
  3649. return center;
  3650. }
  3651. return this.unproject(centerPoint.add(offset), zoom);
  3652. },
  3653. // adjust offset for view to get inside bounds
  3654. _limitOffset: function (offset, bounds) {
  3655. if (!bounds) { return offset; }
  3656. var viewBounds = this.getPixelBounds(),
  3657. newBounds = new Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));
  3658. return offset.add(this._getBoundsOffset(newBounds, bounds));
  3659. },
  3660. // returns offset needed for pxBounds to get inside maxBounds at a specified zoom
  3661. _getBoundsOffset: function (pxBounds, maxBounds, zoom) {
  3662. var projectedMaxBounds = toBounds(
  3663. this.project(maxBounds.getNorthEast(), zoom),
  3664. this.project(maxBounds.getSouthWest(), zoom)
  3665. ),
  3666. minOffset = projectedMaxBounds.min.subtract(pxBounds.min),
  3667. maxOffset = projectedMaxBounds.max.subtract(pxBounds.max),
  3668. dx = this._rebound(minOffset.x, -maxOffset.x),
  3669. dy = this._rebound(minOffset.y, -maxOffset.y);
  3670. return new Point(dx, dy);
  3671. },
  3672. _rebound: function (left, right) {
  3673. return left + right > 0 ?
  3674. Math.round(left - right) / 2 :
  3675. Math.max(0, Math.ceil(left)) - Math.max(0, Math.floor(right));
  3676. },
  3677. _limitZoom: function (zoom) {
  3678. var min = this.getMinZoom(),
  3679. max = this.getMaxZoom(),
  3680. snap = any3d ? this.options.zoomSnap : 1;
  3681. if (snap) {
  3682. zoom = Math.round(zoom / snap) * snap;
  3683. }
  3684. return Math.max(min, Math.min(max, zoom));
  3685. },
  3686. _onPanTransitionStep: function () {
  3687. this.fire('move');
  3688. },
  3689. _onPanTransitionEnd: function () {
  3690. removeClass(this._mapPane, 'leaflet-pan-anim');
  3691. this.fire('moveend');
  3692. },
  3693. _tryAnimatedPan: function (center, options) {
  3694. // difference between the new and current centers in pixels
  3695. var offset = this._getCenterOffset(center)._trunc();
  3696. // don't animate too far unless animate: true specified in options
  3697. if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
  3698. this.panBy(offset, options);
  3699. return true;
  3700. },
  3701. _createAnimProxy: function () {
  3702. var proxy = this._proxy = create$1('div', 'leaflet-proxy leaflet-zoom-animated');
  3703. this._panes.mapPane.appendChild(proxy);
  3704. this.on('zoomanim', function (e) {
  3705. var prop = TRANSFORM,
  3706. transform = this._proxy.style[prop];
  3707. setTransform(this._proxy, this.project(e.center, e.zoom), this.getZoomScale(e.zoom, 1));
  3708. // workaround for case when transform is the same and so transitionend event is not fired
  3709. if (transform === this._proxy.style[prop] && this._animatingZoom) {
  3710. this._onZoomTransitionEnd();
  3711. }
  3712. }, this);
  3713. this.on('load moveend', function () {
  3714. var c = this.getCenter(),
  3715. z = this.getZoom();
  3716. setTransform(this._proxy, this.project(c, z), this.getZoomScale(z, 1));
  3717. }, this);
  3718. this._on('unload', this._destroyAnimProxy, this);
  3719. },
  3720. _destroyAnimProxy: function () {
  3721. remove(this._proxy);
  3722. delete this._proxy;
  3723. },
  3724. _catchTransitionEnd: function (e) {
  3725. if (this._animatingZoom && e.propertyName.indexOf('transform') >= 0) {
  3726. this._onZoomTransitionEnd();
  3727. }
  3728. },
  3729. _nothingToAnimate: function () {
  3730. return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
  3731. },
  3732. _tryAnimatedZoom: function (center, zoom, options) {
  3733. if (this._animatingZoom) { return true; }
  3734. options = options || {};
  3735. // don't animate if disabled, not supported or zoom difference is too large
  3736. if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
  3737. Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
  3738. // offset is the pixel coords of the zoom origin relative to the current center
  3739. var scale = this.getZoomScale(zoom),
  3740. offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale);
  3741. // don't animate if the zoom origin isn't within one screen from the current center, unless forced
  3742. if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
  3743. requestAnimFrame(function () {
  3744. this
  3745. ._moveStart(true, false)
  3746. ._animateZoom(center, zoom, true);
  3747. }, this);
  3748. return true;
  3749. },
  3750. _animateZoom: function (center, zoom, startAnim, noUpdate) {
  3751. if (!this._mapPane) { return; }
  3752. if (startAnim) {
  3753. this._animatingZoom = true;
  3754. // remember what center/zoom to set after animation
  3755. this._animateToCenter = center;
  3756. this._animateToZoom = zoom;
  3757. addClass(this._mapPane, 'leaflet-zoom-anim');
  3758. }
  3759. // @event zoomanim: ZoomAnimEvent
  3760. // Fired on every frame of a zoom animation
  3761. this.fire('zoomanim', {
  3762. center: center,
  3763. zoom: zoom,
  3764. noUpdate: noUpdate
  3765. });
  3766. // Work around webkit not firing 'transitionend', see https://github.com/Leaflet/Leaflet/issues/3689, 2693
  3767. setTimeout(bind(this._onZoomTransitionEnd, this), 250);
  3768. },
  3769. _onZoomTransitionEnd: function () {
  3770. if (!this._animatingZoom) { return; }
  3771. if (this._mapPane) {
  3772. removeClass(this._mapPane, 'leaflet-zoom-anim');
  3773. }
  3774. this._animatingZoom = false;
  3775. this._move(this._animateToCenter, this._animateToZoom);
  3776. // This anim frame should prevent an obscure iOS webkit tile loading race condition.
  3777. requestAnimFrame(function () {
  3778. this._moveEnd(true);
  3779. }, this);
  3780. }
  3781. });
  3782. // @section
  3783. // @factory L.map(id: String, options?: Map options)
  3784. // Instantiates a map object given the DOM ID of a `<div>` element
  3785. // and optionally an object literal with `Map options`.
  3786. //
  3787. // @alternative
  3788. // @factory L.map(el: HTMLElement, options?: Map options)
  3789. // Instantiates a map object given an instance of a `<div>` HTML element
  3790. // and optionally an object literal with `Map options`.
  3791. function createMap(id, options) {
  3792. return new Map(id, options);
  3793. }
  3794. /*
  3795. * @class Control
  3796. * @aka L.Control
  3797. * @inherits Class
  3798. *
  3799. * L.Control is a base class for implementing map controls. Handles positioning.
  3800. * All other controls extend from this class.
  3801. */
  3802. var Control = Class.extend({
  3803. // @section
  3804. // @aka Control options
  3805. options: {
  3806. // @option position: String = 'topright'
  3807. // The position of the control (one of the map corners). Possible values are `'topleft'`,
  3808. // `'topright'`, `'bottomleft'` or `'bottomright'`
  3809. position: 'topright'
  3810. },
  3811. initialize: function (options) {
  3812. setOptions(this, options);
  3813. },
  3814. /* @section
  3815. * Classes extending L.Control will inherit the following methods:
  3816. *
  3817. * @method getPosition: string
  3818. * Returns the position of the control.
  3819. */
  3820. getPosition: function () {
  3821. return this.options.position;
  3822. },
  3823. // @method setPosition(position: string): this
  3824. // Sets the position of the control.
  3825. setPosition: function (position) {
  3826. var map = this._map;
  3827. if (map) {
  3828. map.removeControl(this);
  3829. }
  3830. this.options.position = position;
  3831. if (map) {
  3832. map.addControl(this);
  3833. }
  3834. return this;
  3835. },
  3836. // @method getContainer: HTMLElement
  3837. // Returns the HTMLElement that contains the control.
  3838. getContainer: function () {
  3839. return this._container;
  3840. },
  3841. // @method addTo(map: Map): this
  3842. // Adds the control to the given map.
  3843. addTo: function (map) {
  3844. this.remove();
  3845. this._map = map;
  3846. var container = this._container = this.onAdd(map),
  3847. pos = this.getPosition(),
  3848. corner = map._controlCorners[pos];
  3849. addClass(container, 'leaflet-control');
  3850. if (pos.indexOf('bottom') !== -1) {
  3851. corner.insertBefore(container, corner.firstChild);
  3852. } else {
  3853. corner.appendChild(container);
  3854. }
  3855. return this;
  3856. },
  3857. // @method remove: this
  3858. // Removes the control from the map it is currently active on.
  3859. remove: function () {
  3860. if (!this._map) {
  3861. return this;
  3862. }
  3863. remove(this._container);
  3864. if (this.onRemove) {
  3865. this.onRemove(this._map);
  3866. }
  3867. this._map = null;
  3868. return this;
  3869. },
  3870. _refocusOnMap: function (e) {
  3871. // if map exists and event is not a keyboard event
  3872. if (this._map && e && e.screenX > 0 && e.screenY > 0) {
  3873. this._map.getContainer().focus();
  3874. }
  3875. }
  3876. });
  3877. var control = function (options) {
  3878. return new Control(options);
  3879. };
  3880. /* @section Extension methods
  3881. * @uninheritable
  3882. *
  3883. * Every control should extend from `L.Control` and (re-)implement the following methods.
  3884. *
  3885. * @method onAdd(map: Map): HTMLElement
  3886. * Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo).
  3887. *
  3888. * @method onRemove(map: Map)
  3889. * Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove).
  3890. */
  3891. /* @namespace Map
  3892. * @section Methods for Layers and Controls
  3893. */
  3894. Map.include({
  3895. // @method addControl(control: Control): this
  3896. // Adds the given control to the map
  3897. addControl: function (control) {
  3898. control.addTo(this);
  3899. return this;
  3900. },
  3901. // @method removeControl(control: Control): this
  3902. // Removes the given control from the map
  3903. removeControl: function (control) {
  3904. control.remove();
  3905. return this;
  3906. },
  3907. _initControlPos: function () {
  3908. var corners = this._controlCorners = {},
  3909. l = 'leaflet-',
  3910. container = this._controlContainer =
  3911. create$1('div', l + 'control-container', this._container);
  3912. function createCorner(vSide, hSide) {
  3913. var className = l + vSide + ' ' + l + hSide;
  3914. corners[vSide + hSide] = create$1('div', className, container);
  3915. }
  3916. createCorner('top', 'left');
  3917. createCorner('top', 'right');
  3918. createCorner('bottom', 'left');
  3919. createCorner('bottom', 'right');
  3920. },
  3921. _clearControlPos: function () {
  3922. for (var i in this._controlCorners) {
  3923. remove(this._controlCorners[i]);
  3924. }
  3925. remove(this._controlContainer);
  3926. delete this._controlCorners;
  3927. delete this._controlContainer;
  3928. }
  3929. });
  3930. /*
  3931. * @class Control.Layers
  3932. * @aka L.Control.Layers
  3933. * @inherits Control
  3934. *
  3935. * 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`.
  3936. *
  3937. * @example
  3938. *
  3939. * ```js
  3940. * var baseLayers = {
  3941. * "Mapbox": mapbox,
  3942. * "OpenStreetMap": osm
  3943. * };
  3944. *
  3945. * var overlays = {
  3946. * "Marker": marker,
  3947. * "Roads": roadsLayer
  3948. * };
  3949. *
  3950. * L.control.layers(baseLayers, overlays).addTo(map);
  3951. * ```
  3952. *
  3953. * The `baseLayers` and `overlays` parameters are object literals with layer names as keys and `Layer` objects as values:
  3954. *
  3955. * ```js
  3956. * {
  3957. * "<someName1>": layer1,
  3958. * "<someName2>": layer2
  3959. * }
  3960. * ```
  3961. *
  3962. * The layer names can contain HTML, which allows you to add additional styling to the items:
  3963. *
  3964. * ```js
  3965. * {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}
  3966. * ```
  3967. */
  3968. var Layers = Control.extend({
  3969. // @section
  3970. // @aka Control.Layers options
  3971. options: {
  3972. // @option collapsed: Boolean = true
  3973. // If `true`, the control will be collapsed into an icon and expanded on mouse hover or touch.
  3974. collapsed: true,
  3975. position: 'topright',
  3976. // @option autoZIndex: Boolean = true
  3977. // 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.
  3978. autoZIndex: true,
  3979. // @option hideSingleBase: Boolean = false
  3980. // If `true`, the base layers in the control will be hidden when there is only one.
  3981. hideSingleBase: false,
  3982. // @option sortLayers: Boolean = false
  3983. // Whether to sort the layers. When `false`, layers will keep the order
  3984. // in which they were added to the control.
  3985. sortLayers: false,
  3986. // @option sortFunction: Function = *
  3987. // A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
  3988. // that will be used for sorting the layers, when `sortLayers` is `true`.
  3989. // The function receives both the `L.Layer` instances and their names, as in
  3990. // `sortFunction(layerA, layerB, nameA, nameB)`.
  3991. // By default, it sorts layers alphabetically by their name.
  3992. sortFunction: function (layerA, layerB, nameA, nameB) {
  3993. return nameA < nameB ? -1 : (nameB < nameA ? 1 : 0);
  3994. }
  3995. },
  3996. initialize: function (baseLayers, overlays, options) {
  3997. setOptions(this, options);
  3998. this._layerControlInputs = [];
  3999. this._layers = [];
  4000. this._lastZIndex = 0;
  4001. this._handlingClick = false;
  4002. for (var i in baseLayers) {
  4003. this._addLayer(baseLayers[i], i);
  4004. }
  4005. for (i in overlays) {
  4006. this._addLayer(overlays[i], i, true);
  4007. }
  4008. },
  4009. onAdd: function (map) {
  4010. this._initLayout();
  4011. this._update();
  4012. this._map = map;
  4013. map.on('zoomend', this._checkDisabledLayers, this);
  4014. for (var i = 0; i < this._layers.length; i++) {
  4015. this._layers[i].layer.on('add remove', this._onLayerChange, this);
  4016. }
  4017. return this._container;
  4018. },
  4019. addTo: function (map) {
  4020. Control.prototype.addTo.call(this, map);
  4021. // Trigger expand after Layers Control has been inserted into DOM so that is now has an actual height.
  4022. return this._expandIfNotCollapsed();
  4023. },
  4024. onRemove: function () {
  4025. this._map.off('zoomend', this._checkDisabledLayers, this);
  4026. for (var i = 0; i < this._layers.length; i++) {
  4027. this._layers[i].layer.off('add remove', this._onLayerChange, this);
  4028. }
  4029. },
  4030. // @method addBaseLayer(layer: Layer, name: String): this
  4031. // Adds a base layer (radio button entry) with the given name to the control.
  4032. addBaseLayer: function (layer, name) {
  4033. this._addLayer(layer, name);
  4034. return (this._map) ? this._update() : this;
  4035. },
  4036. // @method addOverlay(layer: Layer, name: String): this
  4037. // Adds an overlay (checkbox entry) with the given name to the control.
  4038. addOverlay: function (layer, name) {
  4039. this._addLayer(layer, name, true);
  4040. return (this._map) ? this._update() : this;
  4041. },
  4042. // @method removeLayer(layer: Layer): this
  4043. // Remove the given layer from the control.
  4044. removeLayer: function (layer) {
  4045. layer.off('add remove', this._onLayerChange, this);
  4046. var obj = this._getLayer(stamp(layer));
  4047. if (obj) {
  4048. this._layers.splice(this._layers.indexOf(obj), 1);
  4049. }
  4050. return (this._map) ? this._update() : this;
  4051. },
  4052. // @method expand(): this
  4053. // Expand the control container if collapsed.
  4054. expand: function () {
  4055. addClass(this._container, 'leaflet-control-layers-expanded');
  4056. this._form.style.height = null;
  4057. var acceptableHeight = this._map.getSize().y - (this._container.offsetTop + 50);
  4058. if (acceptableHeight < this._form.clientHeight) {
  4059. addClass(this._form, 'leaflet-control-layers-scrollbar');
  4060. this._form.style.height = acceptableHeight + 'px';
  4061. } else {
  4062. removeClass(this._form, 'leaflet-control-layers-scrollbar');
  4063. }
  4064. this._checkDisabledLayers();
  4065. return this;
  4066. },
  4067. // @method collapse(): this
  4068. // Collapse the control container if expanded.
  4069. collapse: function () {
  4070. removeClass(this._container, 'leaflet-control-layers-expanded');
  4071. return this;
  4072. },
  4073. _initLayout: function () {
  4074. var className = 'leaflet-control-layers',
  4075. container = this._container = create$1('div', className),
  4076. collapsed = this.options.collapsed;
  4077. // makes this work on IE touch devices by stopping it from firing a mouseout event when the touch is released
  4078. container.setAttribute('aria-haspopup', true);
  4079. disableClickPropagation(container);
  4080. disableScrollPropagation(container);
  4081. var form = this._form = create$1('form', className + '-list');
  4082. if (collapsed) {
  4083. this._map.on('click', this.collapse, this);
  4084. if (!android) {
  4085. on(container, {
  4086. mouseenter: this.expand,
  4087. mouseleave: this.collapse
  4088. }, this);
  4089. }
  4090. }
  4091. var link = this._layersLink = create$1('a', className + '-toggle', container);
  4092. link.href = '#';
  4093. link.title = 'Layers';
  4094. if (touch) {
  4095. on(link, 'click', stop);
  4096. on(link, 'click', this.expand, this);
  4097. } else {
  4098. on(link, 'focus', this.expand, this);
  4099. }
  4100. if (!collapsed) {
  4101. this.expand();
  4102. }
  4103. this._baseLayersList = create$1('div', className + '-base', form);
  4104. this._separator = create$1('div', className + '-separator', form);
  4105. this._overlaysList = create$1('div', className + '-overlays', form);
  4106. container.appendChild(form);
  4107. },
  4108. _getLayer: function (id) {
  4109. for (var i = 0; i < this._layers.length; i++) {
  4110. if (this._layers[i] && stamp(this._layers[i].layer) === id) {
  4111. return this._layers[i];
  4112. }
  4113. }
  4114. },
  4115. _addLayer: function (layer, name, overlay) {
  4116. if (this._map) {
  4117. layer.on('add remove', this._onLayerChange, this);
  4118. }
  4119. this._layers.push({
  4120. layer: layer,
  4121. name: name,
  4122. overlay: overlay
  4123. });
  4124. if (this.options.sortLayers) {
  4125. this._layers.sort(bind(function (a, b) {
  4126. return this.options.sortFunction(a.layer, b.layer, a.name, b.name);
  4127. }, this));
  4128. }
  4129. if (this.options.autoZIndex && layer.setZIndex) {
  4130. this._lastZIndex++;
  4131. layer.setZIndex(this._lastZIndex);
  4132. }
  4133. this._expandIfNotCollapsed();
  4134. },
  4135. _update: function () {
  4136. if (!this._container) { return this; }
  4137. empty(this._baseLayersList);
  4138. empty(this._overlaysList);
  4139. this._layerControlInputs = [];
  4140. var baseLayersPresent, overlaysPresent, i, obj, baseLayersCount = 0;
  4141. for (i = 0; i < this._layers.length; i++) {
  4142. obj = this._layers[i];
  4143. this._addItem(obj);
  4144. overlaysPresent = overlaysPresent || obj.overlay;
  4145. baseLayersPresent = baseLayersPresent || !obj.overlay;
  4146. baseLayersCount += !obj.overlay ? 1 : 0;
  4147. }
  4148. // Hide base layers section if there's only one layer.
  4149. if (this.options.hideSingleBase) {
  4150. baseLayersPresent = baseLayersPresent && baseLayersCount > 1;
  4151. this._baseLayersList.style.display = baseLayersPresent ? '' : 'none';
  4152. }
  4153. this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
  4154. return this;
  4155. },
  4156. _onLayerChange: function (e) {
  4157. if (!this._handlingClick) {
  4158. this._update();
  4159. }
  4160. var obj = this._getLayer(stamp(e.target));
  4161. // @namespace Map
  4162. // @section Layer events
  4163. // @event baselayerchange: LayersControlEvent
  4164. // Fired when the base layer is changed through the [layer control](#control-layers).
  4165. // @event overlayadd: LayersControlEvent
  4166. // Fired when an overlay is selected through the [layer control](#control-layers).
  4167. // @event overlayremove: LayersControlEvent
  4168. // Fired when an overlay is deselected through the [layer control](#control-layers).
  4169. // @namespace Control.Layers
  4170. var type = obj.overlay ?
  4171. (e.type === 'add' ? 'overlayadd' : 'overlayremove') :
  4172. (e.type === 'add' ? 'baselayerchange' : null);
  4173. if (type) {
  4174. this._map.fire(type, obj);
  4175. }
  4176. },
  4177. // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
  4178. _createRadioElement: function (name, checked) {
  4179. var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' +
  4180. name + '"' + (checked ? ' checked="checked"' : '') + '/>';
  4181. var radioFragment = document.createElement('div');
  4182. radioFragment.innerHTML = radioHtml;
  4183. return radioFragment.firstChild;
  4184. },
  4185. _addItem: function (obj) {
  4186. var label = document.createElement('label'),
  4187. checked = this._map.hasLayer(obj.layer),
  4188. input;
  4189. if (obj.overlay) {
  4190. input = document.createElement('input');
  4191. input.type = 'checkbox';
  4192. input.className = 'leaflet-control-layers-selector';
  4193. input.defaultChecked = checked;
  4194. } else {
  4195. input = this._createRadioElement('leaflet-base-layers', checked);
  4196. }
  4197. this._layerControlInputs.push(input);
  4198. input.layerId = stamp(obj.layer);
  4199. on(input, 'click', this._onInputClick, this);
  4200. var name = document.createElement('span');
  4201. name.innerHTML = ' ' + obj.name;
  4202. // Helps from preventing layer control flicker when checkboxes are disabled
  4203. // https://github.com/Leaflet/Leaflet/issues/2771
  4204. var holder = document.createElement('div');
  4205. label.appendChild(holder);
  4206. holder.appendChild(input);
  4207. holder.appendChild(name);
  4208. var container = obj.overlay ? this._overlaysList : this._baseLayersList;
  4209. container.appendChild(label);
  4210. this._checkDisabledLayers();
  4211. return label;
  4212. },
  4213. _onInputClick: function () {
  4214. var inputs = this._layerControlInputs,
  4215. input, layer;
  4216. var addedLayers = [],
  4217. removedLayers = [];
  4218. this._handlingClick = true;
  4219. for (var i = inputs.length - 1; i >= 0; i--) {
  4220. input = inputs[i];
  4221. layer = this._getLayer(input.layerId).layer;
  4222. if (input.checked) {
  4223. addedLayers.push(layer);
  4224. } else if (!input.checked) {
  4225. removedLayers.push(layer);
  4226. }
  4227. }
  4228. // Bugfix issue 2318: Should remove all old layers before readding new ones
  4229. for (i = 0; i < removedLayers.length; i++) {
  4230. if (this._map.hasLayer(removedLayers[i])) {
  4231. this._map.removeLayer(removedLayers[i]);
  4232. }
  4233. }
  4234. for (i = 0; i < addedLayers.length; i++) {
  4235. if (!this._map.hasLayer(addedLayers[i])) {
  4236. this._map.addLayer(addedLayers[i]);
  4237. }
  4238. }
  4239. this._handlingClick = false;
  4240. this._refocusOnMap();
  4241. },
  4242. _checkDisabledLayers: function () {
  4243. var inputs = this._layerControlInputs,
  4244. input,
  4245. layer,
  4246. zoom = this._map.getZoom();
  4247. for (var i = inputs.length - 1; i >= 0; i--) {
  4248. input = inputs[i];
  4249. layer = this._getLayer(input.layerId).layer;
  4250. input.disabled = (layer.options.minZoom !== undefined && zoom < layer.options.minZoom) ||
  4251. (layer.options.maxZoom !== undefined && zoom > layer.options.maxZoom);
  4252. }
  4253. },
  4254. _expandIfNotCollapsed: function () {
  4255. if (this._map && !this.options.collapsed) {
  4256. this.expand();
  4257. }
  4258. return this;
  4259. },
  4260. _expand: function () {
  4261. // Backward compatibility, remove me in 1.1.
  4262. return this.expand();
  4263. },
  4264. _collapse: function () {
  4265. // Backward compatibility, remove me in 1.1.
  4266. return this.collapse();
  4267. }
  4268. });
  4269. // @factory L.control.layers(baselayers?: Object, overlays?: Object, options?: Control.Layers options)
  4270. // 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.
  4271. var layers = function (baseLayers, overlays, options) {
  4272. return new Layers(baseLayers, overlays, options);
  4273. };
  4274. /*
  4275. * @class Control.Zoom
  4276. * @aka L.Control.Zoom
  4277. * @inherits Control
  4278. *
  4279. * 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`.
  4280. */
  4281. var Zoom = Control.extend({
  4282. // @section
  4283. // @aka Control.Zoom options
  4284. options: {
  4285. position: 'topleft',
  4286. // @option zoomInText: String = '+'
  4287. // The text set on the 'zoom in' button.
  4288. zoomInText: '+',
  4289. // @option zoomInTitle: String = 'Zoom in'
  4290. // The title set on the 'zoom in' button.
  4291. zoomInTitle: 'Zoom in',
  4292. // @option zoomOutText: String = '&#x2212;'
  4293. // The text set on the 'zoom out' button.
  4294. zoomOutText: '&#x2212;',
  4295. // @option zoomOutTitle: String = 'Zoom out'
  4296. // The title set on the 'zoom out' button.
  4297. zoomOutTitle: 'Zoom out'
  4298. },
  4299. onAdd: function (map) {
  4300. var zoomName = 'leaflet-control-zoom',
  4301. container = create$1('div', zoomName + ' leaflet-bar'),
  4302. options = this.options;
  4303. this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
  4304. zoomName + '-in', container, this._zoomIn);
  4305. this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
  4306. zoomName + '-out', container, this._zoomOut);
  4307. this._updateDisabled();
  4308. map.on('zoomend zoomlevelschange', this._updateDisabled, this);
  4309. return container;
  4310. },
  4311. onRemove: function (map) {
  4312. map.off('zoomend zoomlevelschange', this._updateDisabled, this);
  4313. },
  4314. disable: function () {
  4315. this._disabled = true;
  4316. this._updateDisabled();
  4317. return this;
  4318. },
  4319. enable: function () {
  4320. this._disabled = false;
  4321. this._updateDisabled();
  4322. return this;
  4323. },
  4324. _zoomIn: function (e) {
  4325. if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
  4326. this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4327. }
  4328. },
  4329. _zoomOut: function (e) {
  4330. if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
  4331. this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
  4332. }
  4333. },
  4334. _createButton: function (html, title, className, container, fn) {
  4335. var link = create$1('a', className, container);
  4336. link.innerHTML = html;
  4337. link.href = '#';
  4338. link.title = title;
  4339. /*
  4340. * Will force screen readers like VoiceOver to read this as "Zoom in - button"
  4341. */
  4342. link.setAttribute('role', 'button');
  4343. link.setAttribute('aria-label', title);
  4344. disableClickPropagation(link);
  4345. on(link, 'click', stop);
  4346. on(link, 'click', fn, this);
  4347. on(link, 'click', this._refocusOnMap, this);
  4348. return link;
  4349. },
  4350. _updateDisabled: function () {
  4351. var map = this._map,
  4352. className = 'leaflet-disabled';
  4353. removeClass(this._zoomInButton, className);
  4354. removeClass(this._zoomOutButton, className);
  4355. if (this._disabled || map._zoom === map.getMinZoom()) {
  4356. addClass(this._zoomOutButton, className);
  4357. }
  4358. if (this._disabled || map._zoom === map.getMaxZoom()) {
  4359. addClass(this._zoomInButton, className);
  4360. }
  4361. }
  4362. });
  4363. // @namespace Map
  4364. // @section Control options
  4365. // @option zoomControl: Boolean = true
  4366. // Whether a [zoom control](#control-zoom) is added to the map by default.
  4367. Map.mergeOptions({
  4368. zoomControl: true
  4369. });
  4370. Map.addInitHook(function () {
  4371. if (this.options.zoomControl) {
  4372. this.zoomControl = new Zoom();
  4373. this.addControl(this.zoomControl);
  4374. }
  4375. });
  4376. // @namespace Control.Zoom
  4377. // @factory L.control.zoom(options: Control.Zoom options)
  4378. // Creates a zoom control
  4379. var zoom = function (options) {
  4380. return new Zoom(options);
  4381. };
  4382. /*
  4383. * @class Control.Scale
  4384. * @aka L.Control.Scale
  4385. * @inherits Control
  4386. *
  4387. * 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`.
  4388. *
  4389. * @example
  4390. *
  4391. * ```js
  4392. * L.control.scale().addTo(map);
  4393. * ```
  4394. */
  4395. var Scale = Control.extend({
  4396. // @section
  4397. // @aka Control.Scale options
  4398. options: {
  4399. position: 'bottomleft',
  4400. // @option maxWidth: Number = 100
  4401. // Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).
  4402. maxWidth: 100,
  4403. // @option metric: Boolean = True
  4404. // Whether to show the metric scale line (m/km).
  4405. metric: true,
  4406. // @option imperial: Boolean = True
  4407. // Whether to show the imperial scale line (mi/ft).
  4408. imperial: true
  4409. // @option updateWhenIdle: Boolean = false
  4410. // If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)).
  4411. },
  4412. onAdd: function (map) {
  4413. var className = 'leaflet-control-scale',
  4414. container = create$1('div', className),
  4415. options = this.options;
  4416. this._addScales(options, className + '-line', container);
  4417. map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4418. map.whenReady(this._update, this);
  4419. return container;
  4420. },
  4421. onRemove: function (map) {
  4422. map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
  4423. },
  4424. _addScales: function (options, className, container) {
  4425. if (options.metric) {
  4426. this._mScale = create$1('div', className, container);
  4427. }
  4428. if (options.imperial) {
  4429. this._iScale = create$1('div', className, container);
  4430. }
  4431. },
  4432. _update: function () {
  4433. var map = this._map,
  4434. y = map.getSize().y / 2;
  4435. var maxMeters = map.distance(
  4436. map.containerPointToLatLng([0, y]),
  4437. map.containerPointToLatLng([this.options.maxWidth, y]));
  4438. this._updateScales(maxMeters);
  4439. },
  4440. _updateScales: function (maxMeters) {
  4441. if (this.options.metric && maxMeters) {
  4442. this._updateMetric(maxMeters);
  4443. }
  4444. if (this.options.imperial && maxMeters) {
  4445. this._updateImperial(maxMeters);
  4446. }
  4447. },
  4448. _updateMetric: function (maxMeters) {
  4449. var meters = this._getRoundNum(maxMeters),
  4450. label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
  4451. this._updateScale(this._mScale, label, meters / maxMeters);
  4452. },
  4453. _updateImperial: function (maxMeters) {
  4454. var maxFeet = maxMeters * 3.2808399,
  4455. maxMiles, miles, feet;
  4456. if (maxFeet > 5280) {
  4457. maxMiles = maxFeet / 5280;
  4458. miles = this._getRoundNum(maxMiles);
  4459. this._updateScale(this._iScale, miles + ' mi', miles / maxMiles);
  4460. } else {
  4461. feet = this._getRoundNum(maxFeet);
  4462. this._updateScale(this._iScale, feet + ' ft', feet / maxFeet);
  4463. }
  4464. },
  4465. _updateScale: function (scale, text, ratio) {
  4466. scale.style.width = Math.round(this.options.maxWidth * ratio) + 'px';
  4467. scale.innerHTML = text;
  4468. },
  4469. _getRoundNum: function (num) {
  4470. var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
  4471. d = num / pow10;
  4472. d = d >= 10 ? 10 :
  4473. d >= 5 ? 5 :
  4474. d >= 3 ? 3 :
  4475. d >= 2 ? 2 : 1;
  4476. return pow10 * d;
  4477. }
  4478. });
  4479. // @factory L.control.scale(options?: Control.Scale options)
  4480. // Creates an scale control with the given options.
  4481. var scale = function (options) {
  4482. return new Scale(options);
  4483. };
  4484. /*
  4485. * @class Control.Attribution
  4486. * @aka L.Control.Attribution
  4487. * @inherits Control
  4488. *
  4489. * 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.
  4490. */
  4491. var Attribution = Control.extend({
  4492. // @section
  4493. // @aka Control.Attribution options
  4494. options: {
  4495. position: 'bottomright',
  4496. // @option prefix: String = 'Leaflet'
  4497. // The HTML text shown before the attributions. Pass `false` to disable.
  4498. prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
  4499. },
  4500. initialize: function (options) {
  4501. setOptions(this, options);
  4502. this._attributions = {};
  4503. },
  4504. onAdd: function (map) {
  4505. map.attributionControl = this;
  4506. this._container = create$1('div', 'leaflet-control-attribution');
  4507. disableClickPropagation(this._container);
  4508. // TODO ugly, refactor
  4509. for (var i in map._layers) {
  4510. if (map._layers[i].getAttribution) {
  4511. this.addAttribution(map._layers[i].getAttribution());
  4512. }
  4513. }
  4514. this._update();
  4515. return this._container;
  4516. },
  4517. // @method setPrefix(prefix: String): this
  4518. // Sets the text before the attributions.
  4519. setPrefix: function (prefix) {
  4520. this.options.prefix = prefix;
  4521. this._update();
  4522. return this;
  4523. },
  4524. // @method addAttribution(text: String): this
  4525. // Adds an attribution text (e.g. `'Vector data &copy; Mapbox'`).
  4526. addAttribution: function (text) {
  4527. if (!text) { return this; }
  4528. if (!this._attributions[text]) {
  4529. this._attributions[text] = 0;
  4530. }
  4531. this._attributions[text]++;
  4532. this._update();
  4533. return this;
  4534. },
  4535. // @method removeAttribution(text: String): this
  4536. // Removes an attribution text.
  4537. removeAttribution: function (text) {
  4538. if (!text) { return this; }
  4539. if (this._attributions[text]) {
  4540. this._attributions[text]--;
  4541. this._update();
  4542. }
  4543. return this;
  4544. },
  4545. _update: function () {
  4546. if (!this._map) { return; }
  4547. var attribs = [];
  4548. for (var i in this._attributions) {
  4549. if (this._attributions[i]) {
  4550. attribs.push(i);
  4551. }
  4552. }
  4553. var prefixAndAttribs = [];
  4554. if (this.options.prefix) {
  4555. prefixAndAttribs.push(this.options.prefix);
  4556. }
  4557. if (attribs.length) {
  4558. prefixAndAttribs.push(attribs.join(', '));
  4559. }
  4560. this._container.innerHTML = prefixAndAttribs.join(' | ');
  4561. }
  4562. });
  4563. // @namespace Map
  4564. // @section Control options
  4565. // @option attributionControl: Boolean = true
  4566. // Whether a [attribution control](#control-attribution) is added to the map by default.
  4567. Map.mergeOptions({
  4568. attributionControl: true
  4569. });
  4570. Map.addInitHook(function () {
  4571. if (this.options.attributionControl) {
  4572. new Attribution().addTo(this);
  4573. }
  4574. });
  4575. // @namespace Control.Attribution
  4576. // @factory L.control.attribution(options: Control.Attribution options)
  4577. // Creates an attribution control.
  4578. var attribution = function (options) {
  4579. return new Attribution(options);
  4580. };
  4581. Control.Layers = Layers;
  4582. Control.Zoom = Zoom;
  4583. Control.Scale = Scale;
  4584. Control.Attribution = Attribution;
  4585. control.layers = layers;
  4586. control.zoom = zoom;
  4587. control.scale = scale;
  4588. control.attribution = attribution;
  4589. /*
  4590. L.Handler is a base class for handler classes that are used internally to inject
  4591. interaction features like dragging to classes like Map and Marker.
  4592. */
  4593. // @class Handler
  4594. // @aka L.Handler
  4595. // Abstract class for map interaction handlers
  4596. var Handler = Class.extend({
  4597. initialize: function (map) {
  4598. this._map = map;
  4599. },
  4600. // @method enable(): this
  4601. // Enables the handler
  4602. enable: function () {
  4603. if (this._enabled) { return this; }
  4604. this._enabled = true;
  4605. this.addHooks();
  4606. return this;
  4607. },
  4608. // @method disable(): this
  4609. // Disables the handler
  4610. disable: function () {
  4611. if (!this._enabled) { return this; }
  4612. this._enabled = false;
  4613. this.removeHooks();
  4614. return this;
  4615. },
  4616. // @method enabled(): Boolean
  4617. // Returns `true` if the handler is enabled
  4618. enabled: function () {
  4619. return !!this._enabled;
  4620. }
  4621. // @section Extension methods
  4622. // Classes inheriting from `Handler` must implement the two following methods:
  4623. // @method addHooks()
  4624. // Called when the handler is enabled, should add event hooks.
  4625. // @method removeHooks()
  4626. // Called when the handler is disabled, should remove the event hooks added previously.
  4627. });
  4628. // @section There is static function which can be called without instantiating L.Handler:
  4629. // @function addTo(map: Map, name: String): this
  4630. // Adds a new Handler to the given map with the given name.
  4631. Handler.addTo = function (map, name) {
  4632. map.addHandler(name, this);
  4633. return this;
  4634. };
  4635. var Mixin = {Events: Events};
  4636. /*
  4637. * @class Draggable
  4638. * @aka L.Draggable
  4639. * @inherits Evented
  4640. *
  4641. * A class for making DOM elements draggable (including touch support).
  4642. * Used internally for map and marker dragging. Only works for elements
  4643. * that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition).
  4644. *
  4645. * @example
  4646. * ```js
  4647. * var draggable = new L.Draggable(elementToDrag);
  4648. * draggable.enable();
  4649. * ```
  4650. */
  4651. var START = touch ? 'touchstart mousedown' : 'mousedown';
  4652. var END = {
  4653. mousedown: 'mouseup',
  4654. touchstart: 'touchend',
  4655. pointerdown: 'touchend',
  4656. MSPointerDown: 'touchend'
  4657. };
  4658. var MOVE = {
  4659. mousedown: 'mousemove',
  4660. touchstart: 'touchmove',
  4661. pointerdown: 'touchmove',
  4662. MSPointerDown: 'touchmove'
  4663. };
  4664. var Draggable = Evented.extend({
  4665. options: {
  4666. // @section
  4667. // @aka Draggable options
  4668. // @option clickTolerance: Number = 3
  4669. // The max number of pixels a user can shift the mouse pointer during a click
  4670. // for it to be considered a valid click (as opposed to a mouse drag).
  4671. clickTolerance: 3
  4672. },
  4673. // @constructor L.Draggable(el: HTMLElement, dragHandle?: HTMLElement, preventOutline?: Boolean, options?: Draggable options)
  4674. // Creates a `Draggable` object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default).
  4675. initialize: function (element, dragStartTarget, preventOutline$$1, options) {
  4676. setOptions(this, options);
  4677. this._element = element;
  4678. this._dragStartTarget = dragStartTarget || element;
  4679. this._preventOutline = preventOutline$$1;
  4680. },
  4681. // @method enable()
  4682. // Enables the dragging ability
  4683. enable: function () {
  4684. if (this._enabled) { return; }
  4685. on(this._dragStartTarget, START, this._onDown, this);
  4686. this._enabled = true;
  4687. },
  4688. // @method disable()
  4689. // Disables the dragging ability
  4690. disable: function () {
  4691. if (!this._enabled) { return; }
  4692. // If we're currently dragging this draggable,
  4693. // disabling it counts as first ending the drag.
  4694. if (Draggable._dragging === this) {
  4695. this.finishDrag();
  4696. }
  4697. off(this._dragStartTarget, START, this._onDown, this);
  4698. this._enabled = false;
  4699. this._moved = false;
  4700. },
  4701. _onDown: function (e) {
  4702. // Ignore simulated events, since we handle both touch and
  4703. // mouse explicitly; otherwise we risk getting duplicates of
  4704. // touch events, see #4315.
  4705. // Also ignore the event if disabled; this happens in IE11
  4706. // under some circumstances, see #3666.
  4707. if (e._simulated || !this._enabled) { return; }
  4708. this._moved = false;
  4709. if (hasClass(this._element, 'leaflet-zoom-anim')) { return; }
  4710. if (Draggable._dragging || e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
  4711. Draggable._dragging = this; // Prevent dragging multiple objects at once.
  4712. if (this._preventOutline) {
  4713. preventOutline(this._element);
  4714. }
  4715. disableImageDrag();
  4716. disableTextSelection();
  4717. if (this._moving) { return; }
  4718. // @event down: Event
  4719. // Fired when a drag is about to start.
  4720. this.fire('down');
  4721. var first = e.touches ? e.touches[0] : e;
  4722. this._startPoint = new Point(first.clientX, first.clientY);
  4723. on(document, MOVE[e.type], this._onMove, this);
  4724. on(document, END[e.type], this._onUp, this);
  4725. },
  4726. _onMove: function (e) {
  4727. // Ignore simulated events, since we handle both touch and
  4728. // mouse explicitly; otherwise we risk getting duplicates of
  4729. // touch events, see #4315.
  4730. // Also ignore the event if disabled; this happens in IE11
  4731. // under some circumstances, see #3666.
  4732. if (e._simulated || !this._enabled) { return; }
  4733. if (e.touches && e.touches.length > 1) {
  4734. this._moved = true;
  4735. return;
  4736. }
  4737. var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
  4738. newPoint = new Point(first.clientX, first.clientY),
  4739. offset = newPoint.subtract(this._startPoint);
  4740. if (!offset.x && !offset.y) { return; }
  4741. if (Math.abs(offset.x) + Math.abs(offset.y) < this.options.clickTolerance) { return; }
  4742. preventDefault(e);
  4743. if (!this._moved) {
  4744. // @event dragstart: Event
  4745. // Fired when a drag starts
  4746. this.fire('dragstart');
  4747. this._moved = true;
  4748. this._startPos = getPosition(this._element).subtract(offset);
  4749. addClass(document.body, 'leaflet-dragging');
  4750. this._lastTarget = e.target || e.srcElement;
  4751. // IE and Edge do not give the <use> element, so fetch it
  4752. // if necessary
  4753. if ((window.SVGElementInstance) && (this._lastTarget instanceof SVGElementInstance)) {
  4754. this._lastTarget = this._lastTarget.correspondingUseElement;
  4755. }
  4756. addClass(this._lastTarget, 'leaflet-drag-target');
  4757. }
  4758. this._newPos = this._startPos.add(offset);
  4759. this._moving = true;
  4760. cancelAnimFrame(this._animRequest);
  4761. this._lastEvent = e;
  4762. this._animRequest = requestAnimFrame(this._updatePosition, this, true);
  4763. },
  4764. _updatePosition: function () {
  4765. var e = {originalEvent: this._lastEvent};
  4766. // @event predrag: Event
  4767. // Fired continuously during dragging *before* each corresponding
  4768. // update of the element's position.
  4769. this.fire('predrag', e);
  4770. setPosition(this._element, this._newPos);
  4771. // @event drag: Event
  4772. // Fired continuously during dragging.
  4773. this.fire('drag', e);
  4774. },
  4775. _onUp: function (e) {
  4776. // Ignore simulated events, since we handle both touch and
  4777. // mouse explicitly; otherwise we risk getting duplicates of
  4778. // touch events, see #4315.
  4779. // Also ignore the event if disabled; this happens in IE11
  4780. // under some circumstances, see #3666.
  4781. if (e._simulated || !this._enabled) { return; }
  4782. this.finishDrag();
  4783. },
  4784. finishDrag: function () {
  4785. removeClass(document.body, 'leaflet-dragging');
  4786. if (this._lastTarget) {
  4787. removeClass(this._lastTarget, 'leaflet-drag-target');
  4788. this._lastTarget = null;
  4789. }
  4790. for (var i in MOVE) {
  4791. off(document, MOVE[i], this._onMove, this);
  4792. off(document, END[i], this._onUp, this);
  4793. }
  4794. enableImageDrag();
  4795. enableTextSelection();
  4796. if (this._moved && this._moving) {
  4797. // ensure drag is not fired after dragend
  4798. cancelAnimFrame(this._animRequest);
  4799. // @event dragend: DragEndEvent
  4800. // Fired when the drag ends.
  4801. this.fire('dragend', {
  4802. distance: this._newPos.distanceTo(this._startPos)
  4803. });
  4804. }
  4805. this._moving = false;
  4806. Draggable._dragging = false;
  4807. }
  4808. });
  4809. /*
  4810. * @namespace LineUtil
  4811. *
  4812. * Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast.
  4813. */
  4814. // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
  4815. // Improves rendering performance dramatically by lessening the number of points to draw.
  4816. // @function simplify(points: Point[], tolerance: Number): Point[]
  4817. // Dramatically reduces the number of points in a polyline while retaining
  4818. // its shape and returns a new array of simplified points, using the
  4819. // [Douglas-Peucker algorithm](http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm).
  4820. // Used for a huge performance boost when processing/displaying Leaflet polylines for
  4821. // each zoom level and also reducing visual noise. tolerance affects the amount of
  4822. // simplification (lesser value means higher quality but slower and with more points).
  4823. // Also released as a separated micro-library [Simplify.js](http://mourner.github.com/simplify-js/).
  4824. function simplify(points, tolerance) {
  4825. if (!tolerance || !points.length) {
  4826. return points.slice();
  4827. }
  4828. var sqTolerance = tolerance * tolerance;
  4829. // stage 1: vertex reduction
  4830. points = _reducePoints(points, sqTolerance);
  4831. // stage 2: Douglas-Peucker simplification
  4832. points = _simplifyDP(points, sqTolerance);
  4833. return points;
  4834. }
  4835. // @function pointToSegmentDistance(p: Point, p1: Point, p2: Point): Number
  4836. // Returns the distance between point `p` and segment `p1` to `p2`.
  4837. function pointToSegmentDistance(p, p1, p2) {
  4838. return Math.sqrt(_sqClosestPointOnSegment(p, p1, p2, true));
  4839. }
  4840. // @function closestPointOnSegment(p: Point, p1: Point, p2: Point): Number
  4841. // Returns the closest point from a point `p` on a segment `p1` to `p2`.
  4842. function closestPointOnSegment(p, p1, p2) {
  4843. return _sqClosestPointOnSegment(p, p1, p2);
  4844. }
  4845. // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
  4846. function _simplifyDP(points, sqTolerance) {
  4847. var len = points.length,
  4848. ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
  4849. markers = new ArrayConstructor(len);
  4850. markers[0] = markers[len - 1] = 1;
  4851. _simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
  4852. var i,
  4853. newPoints = [];
  4854. for (i = 0; i < len; i++) {
  4855. if (markers[i]) {
  4856. newPoints.push(points[i]);
  4857. }
  4858. }
  4859. return newPoints;
  4860. }
  4861. function _simplifyDPStep(points, markers, sqTolerance, first, last) {
  4862. var maxSqDist = 0,
  4863. index, i, sqDist;
  4864. for (i = first + 1; i <= last - 1; i++) {
  4865. sqDist = _sqClosestPointOnSegment(points[i], points[first], points[last], true);
  4866. if (sqDist > maxSqDist) {
  4867. index = i;
  4868. maxSqDist = sqDist;
  4869. }
  4870. }
  4871. if (maxSqDist > sqTolerance) {
  4872. markers[index] = 1;
  4873. _simplifyDPStep(points, markers, sqTolerance, first, index);
  4874. _simplifyDPStep(points, markers, sqTolerance, index, last);
  4875. }
  4876. }
  4877. // reduce points that are too close to each other to a single point
  4878. function _reducePoints(points, sqTolerance) {
  4879. var reducedPoints = [points[0]];
  4880. for (var i = 1, prev = 0, len = points.length; i < len; i++) {
  4881. if (_sqDist(points[i], points[prev]) > sqTolerance) {
  4882. reducedPoints.push(points[i]);
  4883. prev = i;
  4884. }
  4885. }
  4886. if (prev < len - 1) {
  4887. reducedPoints.push(points[len - 1]);
  4888. }
  4889. return reducedPoints;
  4890. }
  4891. var _lastCode;
  4892. // @function clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: Boolean, round?: Boolean): Point[]|Boolean
  4893. // Clips the segment a to b by rectangular bounds with the
  4894. // [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm)
  4895. // (modifying the segment points directly!). Used by Leaflet to only show polyline
  4896. // points that are on the screen or near, increasing performance.
  4897. function clipSegment(a, b, bounds, useLastCode, round) {
  4898. var codeA = useLastCode ? _lastCode : _getBitCode(a, bounds),
  4899. codeB = _getBitCode(b, bounds),
  4900. codeOut, p, newCode;
  4901. // save 2nd code to avoid calculating it on the next segment
  4902. _lastCode = codeB;
  4903. while (true) {
  4904. // if a,b is inside the clip window (trivial accept)
  4905. if (!(codeA | codeB)) {
  4906. return [a, b];
  4907. }
  4908. // if a,b is outside the clip window (trivial reject)
  4909. if (codeA & codeB) {
  4910. return false;
  4911. }
  4912. // other cases
  4913. codeOut = codeA || codeB;
  4914. p = _getEdgeIntersection(a, b, codeOut, bounds, round);
  4915. newCode = _getBitCode(p, bounds);
  4916. if (codeOut === codeA) {
  4917. a = p;
  4918. codeA = newCode;
  4919. } else {
  4920. b = p;
  4921. codeB = newCode;
  4922. }
  4923. }
  4924. }
  4925. function _getEdgeIntersection(a, b, code, bounds, round) {
  4926. var dx = b.x - a.x,
  4927. dy = b.y - a.y,
  4928. min = bounds.min,
  4929. max = bounds.max,
  4930. x, y;
  4931. if (code & 8) { // top
  4932. x = a.x + dx * (max.y - a.y) / dy;
  4933. y = max.y;
  4934. } else if (code & 4) { // bottom
  4935. x = a.x + dx * (min.y - a.y) / dy;
  4936. y = min.y;
  4937. } else if (code & 2) { // right
  4938. x = max.x;
  4939. y = a.y + dy * (max.x - a.x) / dx;
  4940. } else if (code & 1) { // left
  4941. x = min.x;
  4942. y = a.y + dy * (min.x - a.x) / dx;
  4943. }
  4944. return new Point(x, y, round);
  4945. }
  4946. function _getBitCode(p, bounds) {
  4947. var code = 0;
  4948. if (p.x < bounds.min.x) { // left
  4949. code |= 1;
  4950. } else if (p.x > bounds.max.x) { // right
  4951. code |= 2;
  4952. }
  4953. if (p.y < bounds.min.y) { // bottom
  4954. code |= 4;
  4955. } else if (p.y > bounds.max.y) { // top
  4956. code |= 8;
  4957. }
  4958. return code;
  4959. }
  4960. // square distance (to avoid unnecessary Math.sqrt calls)
  4961. function _sqDist(p1, p2) {
  4962. var dx = p2.x - p1.x,
  4963. dy = p2.y - p1.y;
  4964. return dx * dx + dy * dy;
  4965. }
  4966. // return closest point on segment or distance to that point
  4967. function _sqClosestPointOnSegment(p, p1, p2, sqDist) {
  4968. var x = p1.x,
  4969. y = p1.y,
  4970. dx = p2.x - x,
  4971. dy = p2.y - y,
  4972. dot = dx * dx + dy * dy,
  4973. t;
  4974. if (dot > 0) {
  4975. t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
  4976. if (t > 1) {
  4977. x = p2.x;
  4978. y = p2.y;
  4979. } else if (t > 0) {
  4980. x += dx * t;
  4981. y += dy * t;
  4982. }
  4983. }
  4984. dx = p.x - x;
  4985. dy = p.y - y;
  4986. return sqDist ? dx * dx + dy * dy : new Point(x, y);
  4987. }
  4988. // @function isFlat(latlngs: LatLng[]): Boolean
  4989. // Returns true if `latlngs` is a flat array, false is nested.
  4990. function isFlat(latlngs) {
  4991. return !isArray(latlngs[0]) || (typeof latlngs[0][0] !== 'object' && typeof latlngs[0][0] !== 'undefined');
  4992. }
  4993. function _flat(latlngs) {
  4994. console.warn('Deprecated use of _flat, please use L.LineUtil.isFlat instead.');
  4995. return isFlat(latlngs);
  4996. }
  4997. var LineUtil = (Object.freeze || Object)({
  4998. simplify: simplify,
  4999. pointToSegmentDistance: pointToSegmentDistance,
  5000. closestPointOnSegment: closestPointOnSegment,
  5001. clipSegment: clipSegment,
  5002. _getEdgeIntersection: _getEdgeIntersection,
  5003. _getBitCode: _getBitCode,
  5004. _sqClosestPointOnSegment: _sqClosestPointOnSegment,
  5005. isFlat: isFlat,
  5006. _flat: _flat
  5007. });
  5008. /*
  5009. * @namespace PolyUtil
  5010. * Various utility functions for polygon geometries.
  5011. */
  5012. /* @function clipPolygon(points: Point[], bounds: Bounds, round?: Boolean): Point[]
  5013. * 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)).
  5014. * Used by Leaflet to only show polygon points that are on the screen or near, increasing
  5015. * performance. Note that polygon points needs different algorithm for clipping
  5016. * than polyline, so there's a separate method for it.
  5017. */
  5018. function clipPolygon(points, bounds, round) {
  5019. var clippedPoints,
  5020. edges = [1, 4, 2, 8],
  5021. i, j, k,
  5022. a, b,
  5023. len, edge, p;
  5024. for (i = 0, len = points.length; i < len; i++) {
  5025. points[i]._code = _getBitCode(points[i], bounds);
  5026. }
  5027. // for each edge (left, bottom, right, top)
  5028. for (k = 0; k < 4; k++) {
  5029. edge = edges[k];
  5030. clippedPoints = [];
  5031. for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
  5032. a = points[i];
  5033. b = points[j];
  5034. // if a is inside the clip window
  5035. if (!(a._code & edge)) {
  5036. // if b is outside the clip window (a->b goes out of screen)
  5037. if (b._code & edge) {
  5038. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5039. p._code = _getBitCode(p, bounds);
  5040. clippedPoints.push(p);
  5041. }
  5042. clippedPoints.push(a);
  5043. // else if b is inside the clip window (a->b enters the screen)
  5044. } else if (!(b._code & edge)) {
  5045. p = _getEdgeIntersection(b, a, edge, bounds, round);
  5046. p._code = _getBitCode(p, bounds);
  5047. clippedPoints.push(p);
  5048. }
  5049. }
  5050. points = clippedPoints;
  5051. }
  5052. return points;
  5053. }
  5054. var PolyUtil = (Object.freeze || Object)({
  5055. clipPolygon: clipPolygon
  5056. });
  5057. /*
  5058. * @namespace Projection
  5059. * @section
  5060. * Leaflet comes with a set of already defined Projections out of the box:
  5061. *
  5062. * @projection L.Projection.LonLat
  5063. *
  5064. * Equirectangular, or Plate Carree projection — the most simple projection,
  5065. * mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as
  5066. * latitude. Also suitable for flat worlds, e.g. game maps. Used by the
  5067. * `EPSG:4326` and `Simple` CRS.
  5068. */
  5069. var LonLat = {
  5070. project: function (latlng) {
  5071. return new Point(latlng.lng, latlng.lat);
  5072. },
  5073. unproject: function (point) {
  5074. return new LatLng(point.y, point.x);
  5075. },
  5076. bounds: new Bounds([-180, -90], [180, 90])
  5077. };
  5078. /*
  5079. * @namespace Projection
  5080. * @projection L.Projection.Mercator
  5081. *
  5082. * 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.
  5083. */
  5084. var Mercator = {
  5085. R: 6378137,
  5086. R_MINOR: 6356752.314245179,
  5087. bounds: new Bounds([-20037508.34279, -15496570.73972], [20037508.34279, 18764656.23138]),
  5088. project: function (latlng) {
  5089. var d = Math.PI / 180,
  5090. r = this.R,
  5091. y = latlng.lat * d,
  5092. tmp = this.R_MINOR / r,
  5093. e = Math.sqrt(1 - tmp * tmp),
  5094. con = e * Math.sin(y);
  5095. var ts = Math.tan(Math.PI / 4 - y / 2) / Math.pow((1 - con) / (1 + con), e / 2);
  5096. y = -r * Math.log(Math.max(ts, 1E-10));
  5097. return new Point(latlng.lng * d * r, y);
  5098. },
  5099. unproject: function (point) {
  5100. var d = 180 / Math.PI,
  5101. r = this.R,
  5102. tmp = this.R_MINOR / r,
  5103. e = Math.sqrt(1 - tmp * tmp),
  5104. ts = Math.exp(-point.y / r),
  5105. phi = Math.PI / 2 - 2 * Math.atan(ts);
  5106. for (var i = 0, dphi = 0.1, con; i < 15 && Math.abs(dphi) > 1e-7; i++) {
  5107. con = e * Math.sin(phi);
  5108. con = Math.pow((1 - con) / (1 + con), e / 2);
  5109. dphi = Math.PI / 2 - 2 * Math.atan(ts * con) - phi;
  5110. phi += dphi;
  5111. }
  5112. return new LatLng(phi * d, point.x * d / r);
  5113. }
  5114. };
  5115. /*
  5116. * @class Projection
  5117. * An object with methods for projecting geographical coordinates of the world onto
  5118. * a flat surface (and back). See [Map projection](http://en.wikipedia.org/wiki/Map_projection).
  5119. * @property bounds: Bounds
  5120. * The bounds (specified in CRS units) where the projection is valid
  5121. * @method project(latlng: LatLng): Point
  5122. * Projects geographical coordinates into a 2D point.
  5123. * Only accepts actual `L.LatLng` instances, not arrays.
  5124. * @method unproject(point: Point): LatLng
  5125. * The inverse of `project`. Projects a 2D point into a geographical location.
  5126. * Only accepts actual `L.Point` instances, not arrays.
  5127. * Note that the projection instances do not inherit from Leafet's `Class` object,
  5128. * and can't be instantiated. Also, new classes can't inherit from them,
  5129. * and methods can't be added to them with the `include` function.
  5130. */
  5131. var index = (Object.freeze || Object)({
  5132. LonLat: LonLat,
  5133. Mercator: Mercator,
  5134. SphericalMercator: SphericalMercator
  5135. });
  5136. /*
  5137. * @namespace CRS
  5138. * @crs L.CRS.EPSG3395
  5139. *
  5140. * Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.
  5141. */
  5142. var EPSG3395 = extend({}, Earth, {
  5143. code: 'EPSG:3395',
  5144. projection: Mercator,
  5145. transformation: (function () {
  5146. var scale = 0.5 / (Math.PI * Mercator.R);
  5147. return toTransformation(scale, 0.5, -scale, 0.5);
  5148. }())
  5149. });
  5150. /*
  5151. * @namespace CRS
  5152. * @crs L.CRS.EPSG4326
  5153. *
  5154. * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.
  5155. *
  5156. * Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic),
  5157. * which is a breaking change from 0.7.x behaviour. If you are using a `TileLayer`
  5158. * with this CRS, ensure that there are two 256x256 pixel tiles covering the
  5159. * whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90),
  5160. * or (-180,-90) for `TileLayer`s with [the `tms` option](#tilelayer-tms) set.
  5161. */
  5162. var EPSG4326 = extend({}, Earth, {
  5163. code: 'EPSG:4326',
  5164. projection: LonLat,
  5165. transformation: toTransformation(1 / 180, 1, -1 / 180, 0.5)
  5166. });
  5167. /*
  5168. * @namespace CRS
  5169. * @crs L.CRS.Simple
  5170. *
  5171. * A simple CRS that maps longitude and latitude into `x` and `y` directly.
  5172. * May be used for maps of flat surfaces (e.g. game maps). Note that the `y`
  5173. * axis should still be inverted (going from bottom to top). `distance()` returns
  5174. * simple euclidean distance.
  5175. */
  5176. var Simple = extend({}, CRS, {
  5177. projection: LonLat,
  5178. transformation: toTransformation(1, 0, -1, 0),
  5179. scale: function (zoom) {
  5180. return Math.pow(2, zoom);
  5181. },
  5182. zoom: function (scale) {
  5183. return Math.log(scale) / Math.LN2;
  5184. },
  5185. distance: function (latlng1, latlng2) {
  5186. var dx = latlng2.lng - latlng1.lng,
  5187. dy = latlng2.lat - latlng1.lat;
  5188. return Math.sqrt(dx * dx + dy * dy);
  5189. },
  5190. infinite: true
  5191. });
  5192. CRS.Earth = Earth;
  5193. CRS.EPSG3395 = EPSG3395;
  5194. CRS.EPSG3857 = EPSG3857;
  5195. CRS.EPSG900913 = EPSG900913;
  5196. CRS.EPSG4326 = EPSG4326;
  5197. CRS.Simple = Simple;
  5198. /*
  5199. * @class Layer
  5200. * @inherits Evented
  5201. * @aka L.Layer
  5202. * @aka ILayer
  5203. *
  5204. * A set of methods from the Layer base class that all Leaflet layers use.
  5205. * Inherits all methods, options and events from `L.Evented`.
  5206. *
  5207. * @example
  5208. *
  5209. * ```js
  5210. * var layer = L.Marker(latlng).addTo(map);
  5211. * layer.addTo(map);
  5212. * layer.remove();
  5213. * ```
  5214. *
  5215. * @event add: Event
  5216. * Fired after the layer is added to a map
  5217. *
  5218. * @event remove: Event
  5219. * Fired after the layer is removed from a map
  5220. */
  5221. var Layer = Evented.extend({
  5222. // Classes extending `L.Layer` will inherit the following options:
  5223. options: {
  5224. // @option pane: String = 'overlayPane'
  5225. // 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.
  5226. pane: 'overlayPane',
  5227. // @option attribution: String = null
  5228. // String to be shown in the attribution control, describes the layer data, e.g. "© Mapbox".
  5229. attribution: null,
  5230. bubblingMouseEvents: true
  5231. },
  5232. /* @section
  5233. * Classes extending `L.Layer` will inherit the following methods:
  5234. *
  5235. * @method addTo(map: Map|LayerGroup): this
  5236. * Adds the layer to the given map or layer group.
  5237. */
  5238. addTo: function (map) {
  5239. map.addLayer(this);
  5240. return this;
  5241. },
  5242. // @method remove: this
  5243. // Removes the layer from the map it is currently active on.
  5244. remove: function () {
  5245. return this.removeFrom(this._map || this._mapToAdd);
  5246. },
  5247. // @method removeFrom(map: Map): this
  5248. // Removes the layer from the given map
  5249. removeFrom: function (obj) {
  5250. if (obj) {
  5251. obj.removeLayer(this);
  5252. }
  5253. return this;
  5254. },
  5255. // @method getPane(name? : String): HTMLElement
  5256. // Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer.
  5257. getPane: function (name) {
  5258. return this._map.getPane(name ? (this.options[name] || name) : this.options.pane);
  5259. },
  5260. addInteractiveTarget: function (targetEl) {
  5261. this._map._targets[stamp(targetEl)] = this;
  5262. return this;
  5263. },
  5264. removeInteractiveTarget: function (targetEl) {
  5265. delete this._map._targets[stamp(targetEl)];
  5266. return this;
  5267. },
  5268. // @method getAttribution: String
  5269. // Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution).
  5270. getAttribution: function () {
  5271. return this.options.attribution;
  5272. },
  5273. _layerAdd: function (e) {
  5274. var map = e.target;
  5275. // check in case layer gets added and then removed before the map is ready
  5276. if (!map.hasLayer(this)) { return; }
  5277. this._map = map;
  5278. this._zoomAnimated = map._zoomAnimated;
  5279. if (this.getEvents) {
  5280. var events = this.getEvents();
  5281. map.on(events, this);
  5282. this.once('remove', function () {
  5283. map.off(events, this);
  5284. }, this);
  5285. }
  5286. this.onAdd(map);
  5287. if (this.getAttribution && map.attributionControl) {
  5288. map.attributionControl.addAttribution(this.getAttribution());
  5289. }
  5290. this.fire('add');
  5291. map.fire('layeradd', {layer: this});
  5292. }
  5293. });
  5294. /* @section Extension methods
  5295. * @uninheritable
  5296. *
  5297. * Every layer should extend from `L.Layer` and (re-)implement the following methods.
  5298. *
  5299. * @method onAdd(map: Map): this
  5300. * 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).
  5301. *
  5302. * @method onRemove(map: Map): this
  5303. * 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).
  5304. *
  5305. * @method getEvents(): Object
  5306. * 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.
  5307. *
  5308. * @method getAttribution(): String
  5309. * This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible.
  5310. *
  5311. * @method beforeAdd(map: Map): this
  5312. * 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.
  5313. */
  5314. /* @namespace Map
  5315. * @section Layer events
  5316. *
  5317. * @event layeradd: LayerEvent
  5318. * Fired when a new layer is added to the map.
  5319. *
  5320. * @event layerremove: LayerEvent
  5321. * Fired when some layer is removed from the map
  5322. *
  5323. * @section Methods for Layers and Controls
  5324. */
  5325. Map.include({
  5326. // @method addLayer(layer: Layer): this
  5327. // Adds the given layer to the map
  5328. addLayer: function (layer) {
  5329. if (!layer._layerAdd) {
  5330. throw new Error('The provided object is not a Layer.');
  5331. }
  5332. var id = stamp(layer);
  5333. if (this._layers[id]) { return this; }
  5334. this._layers[id] = layer;
  5335. layer._mapToAdd = this;
  5336. if (layer.beforeAdd) {
  5337. layer.beforeAdd(this);
  5338. }
  5339. this.whenReady(layer._layerAdd, layer);
  5340. return this;
  5341. },
  5342. // @method removeLayer(layer: Layer): this
  5343. // Removes the given layer from the map.
  5344. removeLayer: function (layer) {
  5345. var id = stamp(layer);
  5346. if (!this._layers[id]) { return this; }
  5347. if (this._loaded) {
  5348. layer.onRemove(this);
  5349. }
  5350. if (layer.getAttribution && this.attributionControl) {
  5351. this.attributionControl.removeAttribution(layer.getAttribution());
  5352. }
  5353. delete this._layers[id];
  5354. if (this._loaded) {
  5355. this.fire('layerremove', {layer: layer});
  5356. layer.fire('remove');
  5357. }
  5358. layer._map = layer._mapToAdd = null;
  5359. return this;
  5360. },
  5361. // @method hasLayer(layer: Layer): Boolean
  5362. // Returns `true` if the given layer is currently added to the map
  5363. hasLayer: function (layer) {
  5364. return !!layer && (stamp(layer) in this._layers);
  5365. },
  5366. /* @method eachLayer(fn: Function, context?: Object): this
  5367. * Iterates over the layers of the map, optionally specifying context of the iterator function.
  5368. * ```
  5369. * map.eachLayer(function(layer){
  5370. * layer.bindPopup('Hello');
  5371. * });
  5372. * ```
  5373. */
  5374. eachLayer: function (method, context) {
  5375. for (var i in this._layers) {
  5376. method.call(context, this._layers[i]);
  5377. }
  5378. return this;
  5379. },
  5380. _addLayers: function (layers) {
  5381. layers = layers ? (isArray(layers) ? layers : [layers]) : [];
  5382. for (var i = 0, len = layers.length; i < len; i++) {
  5383. this.addLayer(layers[i]);
  5384. }
  5385. },
  5386. _addZoomLimit: function (layer) {
  5387. if (isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom)) {
  5388. this._zoomBoundLayers[stamp(layer)] = layer;
  5389. this._updateZoomLevels();
  5390. }
  5391. },
  5392. _removeZoomLimit: function (layer) {
  5393. var id = stamp(layer);
  5394. if (this._zoomBoundLayers[id]) {
  5395. delete this._zoomBoundLayers[id];
  5396. this._updateZoomLevels();
  5397. }
  5398. },
  5399. _updateZoomLevels: function () {
  5400. var minZoom = Infinity,
  5401. maxZoom = -Infinity,
  5402. oldZoomSpan = this._getZoomSpan();
  5403. for (var i in this._zoomBoundLayers) {
  5404. var options = this._zoomBoundLayers[i].options;
  5405. minZoom = options.minZoom === undefined ? minZoom : Math.min(minZoom, options.minZoom);
  5406. maxZoom = options.maxZoom === undefined ? maxZoom : Math.max(maxZoom, options.maxZoom);
  5407. }
  5408. this._layersMaxZoom = maxZoom === -Infinity ? undefined : maxZoom;
  5409. this._layersMinZoom = minZoom === Infinity ? undefined : minZoom;
  5410. // @section Map state change events
  5411. // @event zoomlevelschange: Event
  5412. // Fired when the number of zoomlevels on the map is changed due
  5413. // to adding or removing a layer.
  5414. if (oldZoomSpan !== this._getZoomSpan()) {
  5415. this.fire('zoomlevelschange');
  5416. }
  5417. if (this.options.maxZoom === undefined && this._layersMaxZoom && this.getZoom() > this._layersMaxZoom) {
  5418. this.setZoom(this._layersMaxZoom);
  5419. }
  5420. if (this.options.minZoom === undefined && this._layersMinZoom && this.getZoom() < this._layersMinZoom) {
  5421. this.setZoom(this._layersMinZoom);
  5422. }
  5423. }
  5424. });
  5425. /*
  5426. * @class LayerGroup
  5427. * @aka L.LayerGroup
  5428. * @inherits Layer
  5429. *
  5430. * Used to group several layers and handle them as one. If you add it to the map,
  5431. * any layers added or removed from the group will be added/removed on the map as
  5432. * well. Extends `Layer`.
  5433. *
  5434. * @example
  5435. *
  5436. * ```js
  5437. * L.layerGroup([marker1, marker2])
  5438. * .addLayer(polyline)
  5439. * .addTo(map);
  5440. * ```
  5441. */
  5442. var LayerGroup = Layer.extend({
  5443. initialize: function (layers, options) {
  5444. setOptions(this, options);
  5445. this._layers = {};
  5446. var i, len;
  5447. if (layers) {
  5448. for (i = 0, len = layers.length; i < len; i++) {
  5449. this.addLayer(layers[i]);
  5450. }
  5451. }
  5452. },
  5453. // @method addLayer(layer: Layer): this
  5454. // Adds the given layer to the group.
  5455. addLayer: function (layer) {
  5456. var id = this.getLayerId(layer);
  5457. this._layers[id] = layer;
  5458. if (this._map) {
  5459. this._map.addLayer(layer);
  5460. }
  5461. return this;
  5462. },
  5463. // @method removeLayer(layer: Layer): this
  5464. // Removes the given layer from the group.
  5465. // @alternative
  5466. // @method removeLayer(id: Number): this
  5467. // Removes the layer with the given internal ID from the group.
  5468. removeLayer: function (layer) {
  5469. var id = layer in this._layers ? layer : this.getLayerId(layer);
  5470. if (this._map && this._layers[id]) {
  5471. this._map.removeLayer(this._layers[id]);
  5472. }
  5473. delete this._layers[id];
  5474. return this;
  5475. },
  5476. // @method hasLayer(layer: Layer): Boolean
  5477. // Returns `true` if the given layer is currently added to the group.
  5478. // @alternative
  5479. // @method hasLayer(id: Number): Boolean
  5480. // Returns `true` if the given internal ID is currently added to the group.
  5481. hasLayer: function (layer) {
  5482. return !!layer && (layer in this._layers || this.getLayerId(layer) in this._layers);
  5483. },
  5484. // @method clearLayers(): this
  5485. // Removes all the layers from the group.
  5486. clearLayers: function () {
  5487. return this.eachLayer(this.removeLayer, this);
  5488. },
  5489. // @method invoke(methodName: String, …): this
  5490. // Calls `methodName` on every layer contained in this group, passing any
  5491. // additional parameters. Has no effect if the layers contained do not
  5492. // implement `methodName`.
  5493. invoke: function (methodName) {
  5494. var args = Array.prototype.slice.call(arguments, 1),
  5495. i, layer;
  5496. for (i in this._layers) {
  5497. layer = this._layers[i];
  5498. if (layer[methodName]) {
  5499. layer[methodName].apply(layer, args);
  5500. }
  5501. }
  5502. return this;
  5503. },
  5504. onAdd: function (map) {
  5505. this.eachLayer(map.addLayer, map);
  5506. },
  5507. onRemove: function (map) {
  5508. this.eachLayer(map.removeLayer, map);
  5509. },
  5510. // @method eachLayer(fn: Function, context?: Object): this
  5511. // Iterates over the layers of the group, optionally specifying context of the iterator function.
  5512. // ```js
  5513. // group.eachLayer(function (layer) {
  5514. // layer.bindPopup('Hello');
  5515. // });
  5516. // ```
  5517. eachLayer: function (method, context) {
  5518. for (var i in this._layers) {
  5519. method.call(context, this._layers[i]);
  5520. }
  5521. return this;
  5522. },
  5523. // @method getLayer(id: Number): Layer
  5524. // Returns the layer with the given internal ID.
  5525. getLayer: function (id) {
  5526. return this._layers[id];
  5527. },
  5528. // @method getLayers(): Layer[]
  5529. // Returns an array of all the layers added to the group.
  5530. getLayers: function () {
  5531. var layers = [];
  5532. this.eachLayer(layers.push, layers);
  5533. return layers;
  5534. },
  5535. // @method setZIndex(zIndex: Number): this
  5536. // Calls `setZIndex` on every layer contained in this group, passing the z-index.
  5537. setZIndex: function (zIndex) {
  5538. return this.invoke('setZIndex', zIndex);
  5539. },
  5540. // @method getLayerId(layer: Layer): Number
  5541. // Returns the internal ID for a layer
  5542. getLayerId: function (layer) {
  5543. return stamp(layer);
  5544. }
  5545. });
  5546. // @factory L.layerGroup(layers?: Layer[], options?: Object)
  5547. // Create a layer group, optionally given an initial set of layers and an `options` object.
  5548. var layerGroup = function (layers, options) {
  5549. return new LayerGroup(layers, options);
  5550. };
  5551. /*
  5552. * @class FeatureGroup
  5553. * @aka L.FeatureGroup
  5554. * @inherits LayerGroup
  5555. *
  5556. * Extended `LayerGroup` that makes it easier to do the same thing to all its member layers:
  5557. * * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip))
  5558. * * Events are propagated to the `FeatureGroup`, so if the group has an event
  5559. * handler, it will handle events from any of the layers. This includes mouse events
  5560. * and custom events.
  5561. * * Has `layeradd` and `layerremove` events
  5562. *
  5563. * @example
  5564. *
  5565. * ```js
  5566. * L.featureGroup([marker1, marker2, polyline])
  5567. * .bindPopup('Hello world!')
  5568. * .on('click', function() { alert('Clicked on a member of the group!'); })
  5569. * .addTo(map);
  5570. * ```
  5571. */
  5572. var FeatureGroup = LayerGroup.extend({
  5573. addLayer: function (layer) {
  5574. if (this.hasLayer(layer)) {
  5575. return this;
  5576. }
  5577. layer.addEventParent(this);
  5578. LayerGroup.prototype.addLayer.call(this, layer);
  5579. // @event layeradd: LayerEvent
  5580. // Fired when a layer is added to this `FeatureGroup`
  5581. return this.fire('layeradd', {layer: layer});
  5582. },
  5583. removeLayer: function (layer) {
  5584. if (!this.hasLayer(layer)) {
  5585. return this;
  5586. }
  5587. if (layer in this._layers) {
  5588. layer = this._layers[layer];
  5589. }
  5590. layer.removeEventParent(this);
  5591. LayerGroup.prototype.removeLayer.call(this, layer);
  5592. // @event layerremove: LayerEvent
  5593. // Fired when a layer is removed from this `FeatureGroup`
  5594. return this.fire('layerremove', {layer: layer});
  5595. },
  5596. // @method setStyle(style: Path options): this
  5597. // Sets the given path options to each layer of the group that has a `setStyle` method.
  5598. setStyle: function (style) {
  5599. return this.invoke('setStyle', style);
  5600. },
  5601. // @method bringToFront(): this
  5602. // Brings the layer group to the top of all other layers
  5603. bringToFront: function () {
  5604. return this.invoke('bringToFront');
  5605. },
  5606. // @method bringToBack(): this
  5607. // Brings the layer group to the back of all other layers
  5608. bringToBack: function () {
  5609. return this.invoke('bringToBack');
  5610. },
  5611. // @method getBounds(): LatLngBounds
  5612. // Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).
  5613. getBounds: function () {
  5614. var bounds = new LatLngBounds();
  5615. for (var id in this._layers) {
  5616. var layer = this._layers[id];
  5617. bounds.extend(layer.getBounds ? layer.getBounds() : layer.getLatLng());
  5618. }
  5619. return bounds;
  5620. }
  5621. });
  5622. // @factory L.featureGroup(layers: Layer[])
  5623. // Create a feature group, optionally given an initial set of layers.
  5624. var featureGroup = function (layers) {
  5625. return new FeatureGroup(layers);
  5626. };
  5627. /*
  5628. * @class Icon
  5629. * @aka L.Icon
  5630. *
  5631. * Represents an icon to provide when creating a marker.
  5632. *
  5633. * @example
  5634. *
  5635. * ```js
  5636. * var myIcon = L.icon({
  5637. * iconUrl: 'my-icon.png',
  5638. * iconRetinaUrl: 'my-icon@2x.png',
  5639. * iconSize: [38, 95],
  5640. * iconAnchor: [22, 94],
  5641. * popupAnchor: [-3, -76],
  5642. * shadowUrl: 'my-icon-shadow.png',
  5643. * shadowRetinaUrl: 'my-icon-shadow@2x.png',
  5644. * shadowSize: [68, 95],
  5645. * shadowAnchor: [22, 94]
  5646. * });
  5647. *
  5648. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  5649. * ```
  5650. *
  5651. * `L.Icon.Default` extends `L.Icon` and is the blue icon Leaflet uses for markers by default.
  5652. *
  5653. */
  5654. var Icon = Class.extend({
  5655. /* @section
  5656. * @aka Icon options
  5657. *
  5658. * @option iconUrl: String = null
  5659. * **(required)** The URL to the icon image (absolute or relative to your script path).
  5660. *
  5661. * @option iconRetinaUrl: String = null
  5662. * The URL to a retina sized version of the icon image (absolute or relative to your
  5663. * script path). Used for Retina screen devices.
  5664. *
  5665. * @option iconSize: Point = null
  5666. * Size of the icon image in pixels.
  5667. *
  5668. * @option iconAnchor: Point = null
  5669. * The coordinates of the "tip" of the icon (relative to its top left corner). The icon
  5670. * will be aligned so that this point is at the marker's geographical location. Centered
  5671. * by default if size is specified, also can be set in CSS with negative margins.
  5672. *
  5673. * @option popupAnchor: Point = [0, 0]
  5674. * The coordinates of the point from which popups will "open", relative to the icon anchor.
  5675. *
  5676. * @option tooltipAnchor: Point = [0, 0]
  5677. * The coordinates of the point from which tooltips will "open", relative to the icon anchor.
  5678. *
  5679. * @option shadowUrl: String = null
  5680. * The URL to the icon shadow image. If not specified, no shadow image will be created.
  5681. *
  5682. * @option shadowRetinaUrl: String = null
  5683. *
  5684. * @option shadowSize: Point = null
  5685. * Size of the shadow image in pixels.
  5686. *
  5687. * @option shadowAnchor: Point = null
  5688. * The coordinates of the "tip" of the shadow (relative to its top left corner) (the same
  5689. * as iconAnchor if not specified).
  5690. *
  5691. * @option className: String = ''
  5692. * A custom class name to assign to both icon and shadow images. Empty by default.
  5693. */
  5694. options: {
  5695. popupAnchor: [0, 0],
  5696. tooltipAnchor: [0, 0],
  5697. },
  5698. initialize: function (options) {
  5699. setOptions(this, options);
  5700. },
  5701. // @method createIcon(oldIcon?: HTMLElement): HTMLElement
  5702. // Called internally when the icon has to be shown, returns a `<img>` HTML element
  5703. // styled according to the options.
  5704. createIcon: function (oldIcon) {
  5705. return this._createIcon('icon', oldIcon);
  5706. },
  5707. // @method createShadow(oldIcon?: HTMLElement): HTMLElement
  5708. // As `createIcon`, but for the shadow beneath it.
  5709. createShadow: function (oldIcon) {
  5710. return this._createIcon('shadow', oldIcon);
  5711. },
  5712. _createIcon: function (name, oldIcon) {
  5713. var src = this._getIconUrl(name);
  5714. if (!src) {
  5715. if (name === 'icon') {
  5716. throw new Error('iconUrl not set in Icon options (see the docs).');
  5717. }
  5718. return null;
  5719. }
  5720. var img = this._createImg(src, oldIcon && oldIcon.tagName === 'IMG' ? oldIcon : null);
  5721. this._setIconStyles(img, name);
  5722. return img;
  5723. },
  5724. _setIconStyles: function (img, name) {
  5725. var options = this.options;
  5726. var sizeOption = options[name + 'Size'];
  5727. if (typeof sizeOption === 'number') {
  5728. sizeOption = [sizeOption, sizeOption];
  5729. }
  5730. var size = toPoint(sizeOption),
  5731. anchor = toPoint(name === 'shadow' && options.shadowAnchor || options.iconAnchor ||
  5732. size && size.divideBy(2, true));
  5733. img.className = 'leaflet-marker-' + name + ' ' + (options.className || '');
  5734. if (anchor) {
  5735. img.style.marginLeft = (-anchor.x) + 'px';
  5736. img.style.marginTop = (-anchor.y) + 'px';
  5737. }
  5738. if (size) {
  5739. img.style.width = size.x + 'px';
  5740. img.style.height = size.y + 'px';
  5741. }
  5742. },
  5743. _createImg: function (src, el) {
  5744. el = el || document.createElement('img');
  5745. el.src = src;
  5746. return el;
  5747. },
  5748. _getIconUrl: function (name) {
  5749. return retina && this.options[name + 'RetinaUrl'] || this.options[name + 'Url'];
  5750. }
  5751. });
  5752. // @factory L.icon(options: Icon options)
  5753. // Creates an icon instance with the given options.
  5754. function icon(options) {
  5755. return new Icon(options);
  5756. }
  5757. /*
  5758. * @miniclass Icon.Default (Icon)
  5759. * @aka L.Icon.Default
  5760. * @section
  5761. *
  5762. * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
  5763. * no icon is specified. Points to the blue marker image distributed with Leaflet
  5764. * releases.
  5765. *
  5766. * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
  5767. * (which is a set of `Icon options`).
  5768. *
  5769. * If you want to _completely_ replace the default icon, override the
  5770. * `L.Marker.prototype.options.icon` with your own icon instead.
  5771. */
  5772. var IconDefault = Icon.extend({
  5773. options: {
  5774. iconUrl: 'marker-icon.png',
  5775. iconRetinaUrl: 'marker-icon-2x.png',
  5776. shadowUrl: 'marker-shadow.png',
  5777. iconSize: [25, 41],
  5778. iconAnchor: [12, 41],
  5779. popupAnchor: [1, -34],
  5780. tooltipAnchor: [16, -28],
  5781. shadowSize: [41, 41]
  5782. },
  5783. _getIconUrl: function (name) {
  5784. if (!IconDefault.imagePath) { // Deprecated, backwards-compatibility only
  5785. IconDefault.imagePath = this._detectIconPath();
  5786. }
  5787. // @option imagePath: String
  5788. // `Icon.Default` will try to auto-detect the location of the
  5789. // blue icon images. If you are placing these images in a non-standard
  5790. // way, set this option to point to the right path.
  5791. return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
  5792. },
  5793. _detectIconPath: function () {
  5794. var el = create$1('div', 'leaflet-default-icon-path', document.body);
  5795. var path = getStyle(el, 'background-image') ||
  5796. getStyle(el, 'backgroundImage'); // IE8
  5797. document.body.removeChild(el);
  5798. if (path === null || path.indexOf('url') !== 0) {
  5799. path = '';
  5800. } else {
  5801. path = path.replace(/^url\(["']?/, '').replace(/marker-icon\.png["']?\)$/, '');
  5802. }
  5803. return path;
  5804. }
  5805. });
  5806. /*
  5807. * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
  5808. */
  5809. /* @namespace Marker
  5810. * @section Interaction handlers
  5811. *
  5812. * 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:
  5813. *
  5814. * ```js
  5815. * marker.dragging.disable();
  5816. * ```
  5817. *
  5818. * @property dragging: Handler
  5819. * Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)).
  5820. */
  5821. var MarkerDrag = Handler.extend({
  5822. initialize: function (marker) {
  5823. this._marker = marker;
  5824. },
  5825. addHooks: function () {
  5826. var icon = this._marker._icon;
  5827. if (!this._draggable) {
  5828. this._draggable = new Draggable(icon, icon, true);
  5829. }
  5830. this._draggable.on({
  5831. dragstart: this._onDragStart,
  5832. predrag: this._onPreDrag,
  5833. drag: this._onDrag,
  5834. dragend: this._onDragEnd
  5835. }, this).enable();
  5836. addClass(icon, 'leaflet-marker-draggable');
  5837. },
  5838. removeHooks: function () {
  5839. this._draggable.off({
  5840. dragstart: this._onDragStart,
  5841. predrag: this._onPreDrag,
  5842. drag: this._onDrag,
  5843. dragend: this._onDragEnd
  5844. }, this).disable();
  5845. if (this._marker._icon) {
  5846. removeClass(this._marker._icon, 'leaflet-marker-draggable');
  5847. }
  5848. },
  5849. moved: function () {
  5850. return this._draggable && this._draggable._moved;
  5851. },
  5852. _adjustPan: function (e) {
  5853. var marker = this._marker,
  5854. map = marker._map,
  5855. speed = this._marker.options.autoPanSpeed,
  5856. padding = this._marker.options.autoPanPadding,
  5857. iconPos = L.DomUtil.getPosition(marker._icon),
  5858. bounds = map.getPixelBounds(),
  5859. origin = map.getPixelOrigin();
  5860. var panBounds = toBounds(
  5861. bounds.min._subtract(origin).add(padding),
  5862. bounds.max._subtract(origin).subtract(padding)
  5863. );
  5864. if (!panBounds.contains(iconPos)) {
  5865. // Compute incremental movement
  5866. var movement = toPoint(
  5867. (Math.max(panBounds.max.x, iconPos.x) - panBounds.max.x) / (bounds.max.x - panBounds.max.x) -
  5868. (Math.min(panBounds.min.x, iconPos.x) - panBounds.min.x) / (bounds.min.x - panBounds.min.x),
  5869. (Math.max(panBounds.max.y, iconPos.y) - panBounds.max.y) / (bounds.max.y - panBounds.max.y) -
  5870. (Math.min(panBounds.min.y, iconPos.y) - panBounds.min.y) / (bounds.min.y - panBounds.min.y)
  5871. ).multiplyBy(speed);
  5872. map.panBy(movement, {animate: false});
  5873. this._draggable._newPos._add(movement);
  5874. this._draggable._startPos._add(movement);
  5875. L.DomUtil.setPosition(marker._icon, this._draggable._newPos);
  5876. this._onDrag(e);
  5877. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5878. }
  5879. },
  5880. _onDragStart: function () {
  5881. // @section Dragging events
  5882. // @event dragstart: Event
  5883. // Fired when the user starts dragging the marker.
  5884. // @event movestart: Event
  5885. // Fired when the marker starts moving (because of dragging).
  5886. this._oldLatLng = this._marker.getLatLng();
  5887. this._marker
  5888. .closePopup()
  5889. .fire('movestart')
  5890. .fire('dragstart');
  5891. },
  5892. _onPreDrag: function (e) {
  5893. if (this._marker.options.autoPan) {
  5894. cancelAnimFrame(this._panRequest);
  5895. this._panRequest = requestAnimFrame(this._adjustPan.bind(this, e));
  5896. }
  5897. },
  5898. _onDrag: function (e) {
  5899. var marker = this._marker,
  5900. shadow = marker._shadow,
  5901. iconPos = getPosition(marker._icon),
  5902. latlng = marker._map.layerPointToLatLng(iconPos);
  5903. // update shadow position
  5904. if (shadow) {
  5905. setPosition(shadow, iconPos);
  5906. }
  5907. marker._latlng = latlng;
  5908. e.latlng = latlng;
  5909. e.oldLatLng = this._oldLatLng;
  5910. // @event drag: Event
  5911. // Fired repeatedly while the user drags the marker.
  5912. marker
  5913. .fire('move', e)
  5914. .fire('drag', e);
  5915. },
  5916. _onDragEnd: function (e) {
  5917. // @event dragend: DragEndEvent
  5918. // Fired when the user stops dragging the marker.
  5919. cancelAnimFrame(this._panRequest);
  5920. // @event moveend: Event
  5921. // Fired when the marker stops moving (because of dragging).
  5922. delete this._oldLatLng;
  5923. this._marker
  5924. .fire('moveend')
  5925. .fire('dragend', e);
  5926. }
  5927. });
  5928. /*
  5929. * @class Marker
  5930. * @inherits Interactive layer
  5931. * @aka L.Marker
  5932. * L.Marker is used to display clickable/draggable icons on the map. Extends `Layer`.
  5933. *
  5934. * @example
  5935. *
  5936. * ```js
  5937. * L.marker([50.5, 30.5]).addTo(map);
  5938. * ```
  5939. */
  5940. var Marker = Layer.extend({
  5941. // @section
  5942. // @aka Marker options
  5943. options: {
  5944. // @option icon: Icon = *
  5945. // Icon instance to use for rendering the marker.
  5946. // See [Icon documentation](#L.Icon) for details on how to customize the marker icon.
  5947. // If not specified, a common instance of `L.Icon.Default` is used.
  5948. icon: new IconDefault(),
  5949. // Option inherited from "Interactive layer" abstract class
  5950. interactive: true,
  5951. // @option draggable: Boolean = false
  5952. // Whether the marker is draggable with mouse/touch or not.
  5953. draggable: false,
  5954. // @option autoPan: Boolean = false
  5955. // Set it to `true` if you want the map to do panning animation when marker hits the edges.
  5956. autoPan: false,
  5957. // @option autoPanPadding: Point = Point(50, 50)
  5958. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  5959. autoPanPadding: [50, 50],
  5960. // @option autoPanSpeed: Number = 10
  5961. // Number of pixels the map should move by.
  5962. autoPanSpeed: 10,
  5963. // @option keyboard: Boolean = true
  5964. // Whether the marker can be tabbed to with a keyboard and clicked by pressing enter.
  5965. keyboard: true,
  5966. // @option title: String = ''
  5967. // Text for the browser tooltip that appear on marker hover (no tooltip by default).
  5968. title: '',
  5969. // @option alt: String = ''
  5970. // Text for the `alt` attribute of the icon image (useful for accessibility).
  5971. alt: '',
  5972. // @option zIndexOffset: Number = 0
  5973. // 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).
  5974. zIndexOffset: 0,
  5975. // @option opacity: Number = 1.0
  5976. // The opacity of the marker.
  5977. opacity: 1,
  5978. // @option riseOnHover: Boolean = false
  5979. // If `true`, the marker will get on top of others when you hover the mouse over it.
  5980. riseOnHover: false,
  5981. // @option riseOffset: Number = 250
  5982. // The z-index offset used for the `riseOnHover` feature.
  5983. riseOffset: 250,
  5984. // @option pane: String = 'markerPane'
  5985. // `Map pane` where the markers icon will be added.
  5986. pane: 'markerPane',
  5987. // @option bubblingMouseEvents: Boolean = false
  5988. // When `true`, a mouse event on this marker will trigger the same event on the map
  5989. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  5990. bubblingMouseEvents: false
  5991. },
  5992. /* @section
  5993. *
  5994. * In addition to [shared layer methods](#Layer) like `addTo()` and `remove()` and [popup methods](#Popup) like bindPopup() you can also use the following methods:
  5995. */
  5996. initialize: function (latlng, options) {
  5997. setOptions(this, options);
  5998. this._latlng = toLatLng(latlng);
  5999. },
  6000. onAdd: function (map) {
  6001. this._zoomAnimated = this._zoomAnimated && map.options.markerZoomAnimation;
  6002. if (this._zoomAnimated) {
  6003. map.on('zoomanim', this._animateZoom, this);
  6004. }
  6005. this._initIcon();
  6006. this.update();
  6007. },
  6008. onRemove: function (map) {
  6009. if (this.dragging && this.dragging.enabled()) {
  6010. this.options.draggable = true;
  6011. this.dragging.removeHooks();
  6012. }
  6013. delete this.dragging;
  6014. if (this._zoomAnimated) {
  6015. map.off('zoomanim', this._animateZoom, this);
  6016. }
  6017. this._removeIcon();
  6018. this._removeShadow();
  6019. },
  6020. getEvents: function () {
  6021. return {
  6022. zoom: this.update,
  6023. viewreset: this.update
  6024. };
  6025. },
  6026. // @method getLatLng: LatLng
  6027. // Returns the current geographical position of the marker.
  6028. getLatLng: function () {
  6029. return this._latlng;
  6030. },
  6031. // @method setLatLng(latlng: LatLng): this
  6032. // Changes the marker position to the given point.
  6033. setLatLng: function (latlng) {
  6034. var oldLatLng = this._latlng;
  6035. this._latlng = toLatLng(latlng);
  6036. this.update();
  6037. // @event move: Event
  6038. // 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`.
  6039. return this.fire('move', {oldLatLng: oldLatLng, latlng: this._latlng});
  6040. },
  6041. // @method setZIndexOffset(offset: Number): this
  6042. // Changes the [zIndex offset](#marker-zindexoffset) of the marker.
  6043. setZIndexOffset: function (offset) {
  6044. this.options.zIndexOffset = offset;
  6045. return this.update();
  6046. },
  6047. // @method setIcon(icon: Icon): this
  6048. // Changes the marker icon.
  6049. setIcon: function (icon) {
  6050. this.options.icon = icon;
  6051. if (this._map) {
  6052. this._initIcon();
  6053. this.update();
  6054. }
  6055. if (this._popup) {
  6056. this.bindPopup(this._popup, this._popup.options);
  6057. }
  6058. return this;
  6059. },
  6060. getElement: function () {
  6061. return this._icon;
  6062. },
  6063. update: function () {
  6064. if (this._icon && this._map) {
  6065. var pos = this._map.latLngToLayerPoint(this._latlng).round();
  6066. this._setPos(pos);
  6067. }
  6068. return this;
  6069. },
  6070. _initIcon: function () {
  6071. var options = this.options,
  6072. classToAdd = 'leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  6073. var icon = options.icon.createIcon(this._icon),
  6074. addIcon = false;
  6075. // if we're not reusing the icon, remove the old one and init new one
  6076. if (icon !== this._icon) {
  6077. if (this._icon) {
  6078. this._removeIcon();
  6079. }
  6080. addIcon = true;
  6081. if (options.title) {
  6082. icon.title = options.title;
  6083. }
  6084. if (icon.tagName === 'IMG') {
  6085. icon.alt = options.alt || '';
  6086. }
  6087. }
  6088. addClass(icon, classToAdd);
  6089. if (options.keyboard) {
  6090. icon.tabIndex = '0';
  6091. }
  6092. this._icon = icon;
  6093. if (options.riseOnHover) {
  6094. this.on({
  6095. mouseover: this._bringToFront,
  6096. mouseout: this._resetZIndex
  6097. });
  6098. }
  6099. var newShadow = options.icon.createShadow(this._shadow),
  6100. addShadow = false;
  6101. if (newShadow !== this._shadow) {
  6102. this._removeShadow();
  6103. addShadow = true;
  6104. }
  6105. if (newShadow) {
  6106. addClass(newShadow, classToAdd);
  6107. newShadow.alt = '';
  6108. }
  6109. this._shadow = newShadow;
  6110. if (options.opacity < 1) {
  6111. this._updateOpacity();
  6112. }
  6113. if (addIcon) {
  6114. this.getPane().appendChild(this._icon);
  6115. }
  6116. this._initInteraction();
  6117. if (newShadow && addShadow) {
  6118. this.getPane('shadowPane').appendChild(this._shadow);
  6119. }
  6120. },
  6121. _removeIcon: function () {
  6122. if (this.options.riseOnHover) {
  6123. this.off({
  6124. mouseover: this._bringToFront,
  6125. mouseout: this._resetZIndex
  6126. });
  6127. }
  6128. remove(this._icon);
  6129. this.removeInteractiveTarget(this._icon);
  6130. this._icon = null;
  6131. },
  6132. _removeShadow: function () {
  6133. if (this._shadow) {
  6134. remove(this._shadow);
  6135. }
  6136. this._shadow = null;
  6137. },
  6138. _setPos: function (pos) {
  6139. setPosition(this._icon, pos);
  6140. if (this._shadow) {
  6141. setPosition(this._shadow, pos);
  6142. }
  6143. this._zIndex = pos.y + this.options.zIndexOffset;
  6144. this._resetZIndex();
  6145. },
  6146. _updateZIndex: function (offset) {
  6147. this._icon.style.zIndex = this._zIndex + offset;
  6148. },
  6149. _animateZoom: function (opt) {
  6150. var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center).round();
  6151. this._setPos(pos);
  6152. },
  6153. _initInteraction: function () {
  6154. if (!this.options.interactive) { return; }
  6155. addClass(this._icon, 'leaflet-interactive');
  6156. this.addInteractiveTarget(this._icon);
  6157. if (MarkerDrag) {
  6158. var draggable = this.options.draggable;
  6159. if (this.dragging) {
  6160. draggable = this.dragging.enabled();
  6161. this.dragging.disable();
  6162. }
  6163. this.dragging = new MarkerDrag(this);
  6164. if (draggable) {
  6165. this.dragging.enable();
  6166. }
  6167. }
  6168. },
  6169. // @method setOpacity(opacity: Number): this
  6170. // Changes the opacity of the marker.
  6171. setOpacity: function (opacity) {
  6172. this.options.opacity = opacity;
  6173. if (this._map) {
  6174. this._updateOpacity();
  6175. }
  6176. return this;
  6177. },
  6178. _updateOpacity: function () {
  6179. var opacity = this.options.opacity;
  6180. setOpacity(this._icon, opacity);
  6181. if (this._shadow) {
  6182. setOpacity(this._shadow, opacity);
  6183. }
  6184. },
  6185. _bringToFront: function () {
  6186. this._updateZIndex(this.options.riseOffset);
  6187. },
  6188. _resetZIndex: function () {
  6189. this._updateZIndex(0);
  6190. },
  6191. _getPopupAnchor: function () {
  6192. return this.options.icon.options.popupAnchor;
  6193. },
  6194. _getTooltipAnchor: function () {
  6195. return this.options.icon.options.tooltipAnchor;
  6196. }
  6197. });
  6198. // factory L.marker(latlng: LatLng, options? : Marker options)
  6199. // @factory L.marker(latlng: LatLng, options? : Marker options)
  6200. // Instantiates a Marker object given a geographical point and optionally an options object.
  6201. function marker(latlng, options) {
  6202. return new Marker(latlng, options);
  6203. }
  6204. /*
  6205. * @class Path
  6206. * @aka L.Path
  6207. * @inherits Interactive layer
  6208. *
  6209. * An abstract class that contains options and constants shared between vector
  6210. * overlays (Polygon, Polyline, Circle). Do not use it directly. Extends `Layer`.
  6211. */
  6212. var Path = Layer.extend({
  6213. // @section
  6214. // @aka Path options
  6215. options: {
  6216. // @option stroke: Boolean = true
  6217. // Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles.
  6218. stroke: true,
  6219. // @option color: String = '#3388ff'
  6220. // Stroke color
  6221. color: '#3388ff',
  6222. // @option weight: Number = 3
  6223. // Stroke width in pixels
  6224. weight: 3,
  6225. // @option opacity: Number = 1.0
  6226. // Stroke opacity
  6227. opacity: 1,
  6228. // @option lineCap: String= 'round'
  6229. // A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke.
  6230. lineCap: 'round',
  6231. // @option lineJoin: String = 'round'
  6232. // A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke.
  6233. lineJoin: 'round',
  6234. // @option dashArray: String = null
  6235. // 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).
  6236. dashArray: null,
  6237. // @option dashOffset: String = null
  6238. // 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).
  6239. dashOffset: null,
  6240. // @option fill: Boolean = depends
  6241. // Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles.
  6242. fill: false,
  6243. // @option fillColor: String = *
  6244. // Fill color. Defaults to the value of the [`color`](#path-color) option
  6245. fillColor: null,
  6246. // @option fillOpacity: Number = 0.2
  6247. // Fill opacity.
  6248. fillOpacity: 0.2,
  6249. // @option fillRule: String = 'evenodd'
  6250. // A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined.
  6251. fillRule: 'evenodd',
  6252. // className: '',
  6253. // Option inherited from "Interactive layer" abstract class
  6254. interactive: true,
  6255. // @option bubblingMouseEvents: Boolean = true
  6256. // When `true`, a mouse event on this path will trigger the same event on the map
  6257. // (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used).
  6258. bubblingMouseEvents: true
  6259. },
  6260. beforeAdd: function (map) {
  6261. // Renderer is set here because we need to call renderer.getEvents
  6262. // before this.getEvents.
  6263. this._renderer = map.getRenderer(this);
  6264. },
  6265. onAdd: function () {
  6266. this._renderer._initPath(this);
  6267. this._reset();
  6268. this._renderer._addPath(this);
  6269. },
  6270. onRemove: function () {
  6271. this._renderer._removePath(this);
  6272. },
  6273. // @method redraw(): this
  6274. // Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.
  6275. redraw: function () {
  6276. if (this._map) {
  6277. this._renderer._updatePath(this);
  6278. }
  6279. return this;
  6280. },
  6281. // @method setStyle(style: Path options): this
  6282. // Changes the appearance of a Path based on the options in the `Path options` object.
  6283. setStyle: function (style) {
  6284. setOptions(this, style);
  6285. if (this._renderer) {
  6286. this._renderer._updateStyle(this);
  6287. }
  6288. return this;
  6289. },
  6290. // @method bringToFront(): this
  6291. // Brings the layer to the top of all path layers.
  6292. bringToFront: function () {
  6293. if (this._renderer) {
  6294. this._renderer._bringToFront(this);
  6295. }
  6296. return this;
  6297. },
  6298. // @method bringToBack(): this
  6299. // Brings the layer to the bottom of all path layers.
  6300. bringToBack: function () {
  6301. if (this._renderer) {
  6302. this._renderer._bringToBack(this);
  6303. }
  6304. return this;
  6305. },
  6306. getElement: function () {
  6307. return this._path;
  6308. },
  6309. _reset: function () {
  6310. // defined in child classes
  6311. this._project();
  6312. this._update();
  6313. },
  6314. _clickTolerance: function () {
  6315. // used when doing hit detection for Canvas layers
  6316. return (this.options.stroke ? this.options.weight / 2 : 0) + this._renderer.options.tolerance;
  6317. }
  6318. });
  6319. /*
  6320. * @class CircleMarker
  6321. * @aka L.CircleMarker
  6322. * @inherits Path
  6323. *
  6324. * A circle of a fixed size with radius specified in pixels. Extends `Path`.
  6325. */
  6326. var CircleMarker = Path.extend({
  6327. // @section
  6328. // @aka CircleMarker options
  6329. options: {
  6330. fill: true,
  6331. // @option radius: Number = 10
  6332. // Radius of the circle marker, in pixels
  6333. radius: 10
  6334. },
  6335. initialize: function (latlng, options) {
  6336. setOptions(this, options);
  6337. this._latlng = toLatLng(latlng);
  6338. this._radius = this.options.radius;
  6339. },
  6340. // @method setLatLng(latLng: LatLng): this
  6341. // Sets the position of a circle marker to a new location.
  6342. setLatLng: function (latlng) {
  6343. this._latlng = toLatLng(latlng);
  6344. this.redraw();
  6345. return this.fire('move', {latlng: this._latlng});
  6346. },
  6347. // @method getLatLng(): LatLng
  6348. // Returns the current geographical position of the circle marker
  6349. getLatLng: function () {
  6350. return this._latlng;
  6351. },
  6352. // @method setRadius(radius: Number): this
  6353. // Sets the radius of a circle marker. Units are in pixels.
  6354. setRadius: function (radius) {
  6355. this.options.radius = this._radius = radius;
  6356. return this.redraw();
  6357. },
  6358. // @method getRadius(): Number
  6359. // Returns the current radius of the circle
  6360. getRadius: function () {
  6361. return this._radius;
  6362. },
  6363. setStyle : function (options) {
  6364. var radius = options && options.radius || this._radius;
  6365. Path.prototype.setStyle.call(this, options);
  6366. this.setRadius(radius);
  6367. return this;
  6368. },
  6369. _project: function () {
  6370. this._point = this._map.latLngToLayerPoint(this._latlng);
  6371. this._updateBounds();
  6372. },
  6373. _updateBounds: function () {
  6374. var r = this._radius,
  6375. r2 = this._radiusY || r,
  6376. w = this._clickTolerance(),
  6377. p = [r + w, r2 + w];
  6378. this._pxBounds = new Bounds(this._point.subtract(p), this._point.add(p));
  6379. },
  6380. _update: function () {
  6381. if (this._map) {
  6382. this._updatePath();
  6383. }
  6384. },
  6385. _updatePath: function () {
  6386. this._renderer._updateCircle(this);
  6387. },
  6388. _empty: function () {
  6389. return this._radius && !this._renderer._bounds.intersects(this._pxBounds);
  6390. },
  6391. // Needed by the `Canvas` renderer for interactivity
  6392. _containsPoint: function (p) {
  6393. return p.distanceTo(this._point) <= this._radius + this._clickTolerance();
  6394. }
  6395. });
  6396. // @factory L.circleMarker(latlng: LatLng, options?: CircleMarker options)
  6397. // Instantiates a circle marker object given a geographical point, and an optional options object.
  6398. function circleMarker(latlng, options) {
  6399. return new CircleMarker(latlng, options);
  6400. }
  6401. /*
  6402. * @class Circle
  6403. * @aka L.Circle
  6404. * @inherits CircleMarker
  6405. *
  6406. * A class for drawing circle overlays on a map. Extends `CircleMarker`.
  6407. *
  6408. * It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).
  6409. *
  6410. * @example
  6411. *
  6412. * ```js
  6413. * L.circle([50.5, 30.5], {radius: 200}).addTo(map);
  6414. * ```
  6415. */
  6416. var Circle = CircleMarker.extend({
  6417. initialize: function (latlng, options, legacyOptions) {
  6418. if (typeof options === 'number') {
  6419. // Backwards compatibility with 0.7.x factory (latlng, radius, options?)
  6420. options = extend({}, legacyOptions, {radius: options});
  6421. }
  6422. setOptions(this, options);
  6423. this._latlng = toLatLng(latlng);
  6424. if (isNaN(this.options.radius)) { throw new Error('Circle radius cannot be NaN'); }
  6425. // @section
  6426. // @aka Circle options
  6427. // @option radius: Number; Radius of the circle, in meters.
  6428. this._mRadius = this.options.radius;
  6429. },
  6430. // @method setRadius(radius: Number): this
  6431. // Sets the radius of a circle. Units are in meters.
  6432. setRadius: function (radius) {
  6433. this._mRadius = radius;
  6434. return this.redraw();
  6435. },
  6436. // @method getRadius(): Number
  6437. // Returns the current radius of a circle. Units are in meters.
  6438. getRadius: function () {
  6439. return this._mRadius;
  6440. },
  6441. // @method getBounds(): LatLngBounds
  6442. // Returns the `LatLngBounds` of the path.
  6443. getBounds: function () {
  6444. var half = [this._radius, this._radiusY || this._radius];
  6445. return new LatLngBounds(
  6446. this._map.layerPointToLatLng(this._point.subtract(half)),
  6447. this._map.layerPointToLatLng(this._point.add(half)));
  6448. },
  6449. setStyle: Path.prototype.setStyle,
  6450. _project: function () {
  6451. var lng = this._latlng.lng,
  6452. lat = this._latlng.lat,
  6453. map = this._map,
  6454. crs = map.options.crs;
  6455. if (crs.distance === Earth.distance) {
  6456. var d = Math.PI / 180,
  6457. latR = (this._mRadius / Earth.R) / d,
  6458. top = map.project([lat + latR, lng]),
  6459. bottom = map.project([lat - latR, lng]),
  6460. p = top.add(bottom).divideBy(2),
  6461. lat2 = map.unproject(p).lat,
  6462. lngR = Math.acos((Math.cos(latR * d) - Math.sin(lat * d) * Math.sin(lat2 * d)) /
  6463. (Math.cos(lat * d) * Math.cos(lat2 * d))) / d;
  6464. if (isNaN(lngR) || lngR === 0) {
  6465. lngR = latR / Math.cos(Math.PI / 180 * lat); // Fallback for edge case, #2425
  6466. }
  6467. this._point = p.subtract(map.getPixelOrigin());
  6468. this._radius = isNaN(lngR) ? 0 : p.x - map.project([lat2, lng - lngR]).x;
  6469. this._radiusY = p.y - top.y;
  6470. } else {
  6471. var latlng2 = crs.unproject(crs.project(this._latlng).subtract([this._mRadius, 0]));
  6472. this._point = map.latLngToLayerPoint(this._latlng);
  6473. this._radius = this._point.x - map.latLngToLayerPoint(latlng2).x;
  6474. }
  6475. this._updateBounds();
  6476. }
  6477. });
  6478. // @factory L.circle(latlng: LatLng, options?: Circle options)
  6479. // Instantiates a circle object given a geographical point, and an options object
  6480. // which contains the circle radius.
  6481. // @alternative
  6482. // @factory L.circle(latlng: LatLng, radius: Number, options?: Circle options)
  6483. // Obsolete way of instantiating a circle, for compatibility with 0.7.x code.
  6484. // Do not use in new applications or plugins.
  6485. function circle(latlng, options, legacyOptions) {
  6486. return new Circle(latlng, options, legacyOptions);
  6487. }
  6488. /*
  6489. * @class Polyline
  6490. * @aka L.Polyline
  6491. * @inherits Path
  6492. *
  6493. * A class for drawing polyline overlays on a map. Extends `Path`.
  6494. *
  6495. * @example
  6496. *
  6497. * ```js
  6498. * // create a red polyline from an array of LatLng points
  6499. * var latlngs = [
  6500. * [45.51, -122.68],
  6501. * [37.77, -122.43],
  6502. * [34.04, -118.2]
  6503. * ];
  6504. *
  6505. * var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
  6506. *
  6507. * // zoom the map to the polyline
  6508. * map.fitBounds(polyline.getBounds());
  6509. * ```
  6510. *
  6511. * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape:
  6512. *
  6513. * ```js
  6514. * // create a red polyline from an array of arrays of LatLng points
  6515. * var latlngs = [
  6516. * [[45.51, -122.68],
  6517. * [37.77, -122.43],
  6518. * [34.04, -118.2]],
  6519. * [[40.78, -73.91],
  6520. * [41.83, -87.62],
  6521. * [32.76, -96.72]]
  6522. * ];
  6523. * ```
  6524. */
  6525. var Polyline = Path.extend({
  6526. // @section
  6527. // @aka Polyline options
  6528. options: {
  6529. // @option smoothFactor: Number = 1.0
  6530. // How much to simplify the polyline on each zoom level. More means
  6531. // better performance and smoother look, and less means more accurate representation.
  6532. smoothFactor: 1.0,
  6533. // @option noClip: Boolean = false
  6534. // Disable polyline clipping.
  6535. noClip: false
  6536. },
  6537. initialize: function (latlngs, options) {
  6538. setOptions(this, options);
  6539. this._setLatLngs(latlngs);
  6540. },
  6541. // @method getLatLngs(): LatLng[]
  6542. // Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.
  6543. getLatLngs: function () {
  6544. return this._latlngs;
  6545. },
  6546. // @method setLatLngs(latlngs: LatLng[]): this
  6547. // Replaces all the points in the polyline with the given array of geographical points.
  6548. setLatLngs: function (latlngs) {
  6549. this._setLatLngs(latlngs);
  6550. return this.redraw();
  6551. },
  6552. // @method isEmpty(): Boolean
  6553. // Returns `true` if the Polyline has no LatLngs.
  6554. isEmpty: function () {
  6555. return !this._latlngs.length;
  6556. },
  6557. // @method closestLayerPoint: Point
  6558. // Returns the point closest to `p` on the Polyline.
  6559. closestLayerPoint: function (p) {
  6560. var minDistance = Infinity,
  6561. minPoint = null,
  6562. closest = _sqClosestPointOnSegment,
  6563. p1, p2;
  6564. for (var j = 0, jLen = this._parts.length; j < jLen; j++) {
  6565. var points = this._parts[j];
  6566. for (var i = 1, len = points.length; i < len; i++) {
  6567. p1 = points[i - 1];
  6568. p2 = points[i];
  6569. var sqDist = closest(p, p1, p2, true);
  6570. if (sqDist < minDistance) {
  6571. minDistance = sqDist;
  6572. minPoint = closest(p, p1, p2);
  6573. }
  6574. }
  6575. }
  6576. if (minPoint) {
  6577. minPoint.distance = Math.sqrt(minDistance);
  6578. }
  6579. return minPoint;
  6580. },
  6581. // @method getCenter(): LatLng
  6582. // Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
  6583. getCenter: function () {
  6584. // throws error when not yet added to map as this center calculation requires projected coordinates
  6585. if (!this._map) {
  6586. throw new Error('Must add layer to map before using getCenter()');
  6587. }
  6588. var i, halfDist, segDist, dist, p1, p2, ratio,
  6589. points = this._rings[0],
  6590. len = points.length;
  6591. if (!len) { return null; }
  6592. // polyline centroid algorithm; only uses the first ring if there are multiple
  6593. for (i = 0, halfDist = 0; i < len - 1; i++) {
  6594. halfDist += points[i].distanceTo(points[i + 1]) / 2;
  6595. }
  6596. // The line is so small in the current view that all points are on the same pixel.
  6597. if (halfDist === 0) {
  6598. return this._map.layerPointToLatLng(points[0]);
  6599. }
  6600. for (i = 0, dist = 0; i < len - 1; i++) {
  6601. p1 = points[i];
  6602. p2 = points[i + 1];
  6603. segDist = p1.distanceTo(p2);
  6604. dist += segDist;
  6605. if (dist > halfDist) {
  6606. ratio = (dist - halfDist) / segDist;
  6607. return this._map.layerPointToLatLng([
  6608. p2.x - ratio * (p2.x - p1.x),
  6609. p2.y - ratio * (p2.y - p1.y)
  6610. ]);
  6611. }
  6612. }
  6613. },
  6614. // @method getBounds(): LatLngBounds
  6615. // Returns the `LatLngBounds` of the path.
  6616. getBounds: function () {
  6617. return this._bounds;
  6618. },
  6619. // @method addLatLng(latlng: LatLng, latlngs? LatLng[]): this
  6620. // Adds a given point to the polyline. By default, adds to the first ring of
  6621. // the polyline in case of a multi-polyline, but can be overridden by passing
  6622. // a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)).
  6623. addLatLng: function (latlng, latlngs) {
  6624. latlngs = latlngs || this._defaultShape();
  6625. latlng = toLatLng(latlng);
  6626. latlngs.push(latlng);
  6627. this._bounds.extend(latlng);
  6628. return this.redraw();
  6629. },
  6630. _setLatLngs: function (latlngs) {
  6631. this._bounds = new LatLngBounds();
  6632. this._latlngs = this._convertLatLngs(latlngs);
  6633. },
  6634. _defaultShape: function () {
  6635. return isFlat(this._latlngs) ? this._latlngs : this._latlngs[0];
  6636. },
  6637. // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way
  6638. _convertLatLngs: function (latlngs) {
  6639. var result = [],
  6640. flat = isFlat(latlngs);
  6641. for (var i = 0, len = latlngs.length; i < len; i++) {
  6642. if (flat) {
  6643. result[i] = toLatLng(latlngs[i]);
  6644. this._bounds.extend(result[i]);
  6645. } else {
  6646. result[i] = this._convertLatLngs(latlngs[i]);
  6647. }
  6648. }
  6649. return result;
  6650. },
  6651. _project: function () {
  6652. var pxBounds = new Bounds();
  6653. this._rings = [];
  6654. this._projectLatlngs(this._latlngs, this._rings, pxBounds);
  6655. var w = this._clickTolerance(),
  6656. p = new Point(w, w);
  6657. if (this._bounds.isValid() && pxBounds.isValid()) {
  6658. pxBounds.min._subtract(p);
  6659. pxBounds.max._add(p);
  6660. this._pxBounds = pxBounds;
  6661. }
  6662. },
  6663. // recursively turns latlngs into a set of rings with projected coordinates
  6664. _projectLatlngs: function (latlngs, result, projectedBounds) {
  6665. var flat = latlngs[0] instanceof LatLng,
  6666. len = latlngs.length,
  6667. i, ring;
  6668. if (flat) {
  6669. ring = [];
  6670. for (i = 0; i < len; i++) {
  6671. ring[i] = this._map.latLngToLayerPoint(latlngs[i]);
  6672. projectedBounds.extend(ring[i]);
  6673. }
  6674. result.push(ring);
  6675. } else {
  6676. for (i = 0; i < len; i++) {
  6677. this._projectLatlngs(latlngs[i], result, projectedBounds);
  6678. }
  6679. }
  6680. },
  6681. // clip polyline by renderer bounds so that we have less to render for performance
  6682. _clipPoints: function () {
  6683. var bounds = this._renderer._bounds;
  6684. this._parts = [];
  6685. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6686. return;
  6687. }
  6688. if (this.options.noClip) {
  6689. this._parts = this._rings;
  6690. return;
  6691. }
  6692. var parts = this._parts,
  6693. i, j, k, len, len2, segment, points;
  6694. for (i = 0, k = 0, len = this._rings.length; i < len; i++) {
  6695. points = this._rings[i];
  6696. for (j = 0, len2 = points.length; j < len2 - 1; j++) {
  6697. segment = clipSegment(points[j], points[j + 1], bounds, j, true);
  6698. if (!segment) { continue; }
  6699. parts[k] = parts[k] || [];
  6700. parts[k].push(segment[0]);
  6701. // if segment goes out of screen, or it's the last one, it's the end of the line part
  6702. if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) {
  6703. parts[k].push(segment[1]);
  6704. k++;
  6705. }
  6706. }
  6707. }
  6708. },
  6709. // simplify each clipped part of the polyline for performance
  6710. _simplifyPoints: function () {
  6711. var parts = this._parts,
  6712. tolerance = this.options.smoothFactor;
  6713. for (var i = 0, len = parts.length; i < len; i++) {
  6714. parts[i] = simplify(parts[i], tolerance);
  6715. }
  6716. },
  6717. _update: function () {
  6718. if (!this._map) { return; }
  6719. this._clipPoints();
  6720. this._simplifyPoints();
  6721. this._updatePath();
  6722. },
  6723. _updatePath: function () {
  6724. this._renderer._updatePoly(this);
  6725. },
  6726. // Needed by the `Canvas` renderer for interactivity
  6727. _containsPoint: function (p, closed) {
  6728. var i, j, k, len, len2, part,
  6729. w = this._clickTolerance();
  6730. if (!this._pxBounds || !this._pxBounds.contains(p)) { return false; }
  6731. // hit detection for polylines
  6732. for (i = 0, len = this._parts.length; i < len; i++) {
  6733. part = this._parts[i];
  6734. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6735. if (!closed && (j === 0)) { continue; }
  6736. if (pointToSegmentDistance(p, part[k], part[j]) <= w) {
  6737. return true;
  6738. }
  6739. }
  6740. }
  6741. return false;
  6742. }
  6743. });
  6744. // @factory L.polyline(latlngs: LatLng[], options?: Polyline options)
  6745. // Instantiates a polyline object given an array of geographical points and
  6746. // optionally an options object. You can create a `Polyline` object with
  6747. // multiple separate lines (`MultiPolyline`) by passing an array of arrays
  6748. // of geographic points.
  6749. function polyline(latlngs, options) {
  6750. return new Polyline(latlngs, options);
  6751. }
  6752. // Retrocompat. Allow plugins to support Leaflet versions before and after 1.1.
  6753. Polyline._flat = _flat;
  6754. /*
  6755. * @class Polygon
  6756. * @aka L.Polygon
  6757. * @inherits Polyline
  6758. *
  6759. * A class for drawing polygon overlays on a map. Extends `Polyline`.
  6760. *
  6761. * 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.
  6762. *
  6763. *
  6764. * @example
  6765. *
  6766. * ```js
  6767. * // create a red polygon from an array of LatLng points
  6768. * var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];
  6769. *
  6770. * var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map);
  6771. *
  6772. * // zoom the map to the polygon
  6773. * map.fitBounds(polygon.getBounds());
  6774. * ```
  6775. *
  6776. * 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:
  6777. *
  6778. * ```js
  6779. * var latlngs = [
  6780. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6781. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6782. * ];
  6783. * ```
  6784. *
  6785. * Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.
  6786. *
  6787. * ```js
  6788. * var latlngs = [
  6789. * [ // first polygon
  6790. * [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  6791. * [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  6792. * ],
  6793. * [ // second polygon
  6794. * [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  6795. * ]
  6796. * ];
  6797. * ```
  6798. */
  6799. var Polygon = Polyline.extend({
  6800. options: {
  6801. fill: true
  6802. },
  6803. isEmpty: function () {
  6804. return !this._latlngs.length || !this._latlngs[0].length;
  6805. },
  6806. getCenter: function () {
  6807. // throws error when not yet added to map as this center calculation requires projected coordinates
  6808. if (!this._map) {
  6809. throw new Error('Must add layer to map before using getCenter()');
  6810. }
  6811. var i, j, p1, p2, f, area, x, y, center,
  6812. points = this._rings[0],
  6813. len = points.length;
  6814. if (!len) { return null; }
  6815. // polygon centroid algorithm; only uses the first ring if there are multiple
  6816. area = x = y = 0;
  6817. for (i = 0, j = len - 1; i < len; j = i++) {
  6818. p1 = points[i];
  6819. p2 = points[j];
  6820. f = p1.y * p2.x - p2.y * p1.x;
  6821. x += (p1.x + p2.x) * f;
  6822. y += (p1.y + p2.y) * f;
  6823. area += f * 3;
  6824. }
  6825. if (area === 0) {
  6826. // Polygon is so small that all points are on same pixel.
  6827. center = points[0];
  6828. } else {
  6829. center = [x / area, y / area];
  6830. }
  6831. return this._map.layerPointToLatLng(center);
  6832. },
  6833. _convertLatLngs: function (latlngs) {
  6834. var result = Polyline.prototype._convertLatLngs.call(this, latlngs),
  6835. len = result.length;
  6836. // remove last point if it equals first one
  6837. if (len >= 2 && result[0] instanceof LatLng && result[0].equals(result[len - 1])) {
  6838. result.pop();
  6839. }
  6840. return result;
  6841. },
  6842. _setLatLngs: function (latlngs) {
  6843. Polyline.prototype._setLatLngs.call(this, latlngs);
  6844. if (isFlat(this._latlngs)) {
  6845. this._latlngs = [this._latlngs];
  6846. }
  6847. },
  6848. _defaultShape: function () {
  6849. return isFlat(this._latlngs[0]) ? this._latlngs[0] : this._latlngs[0][0];
  6850. },
  6851. _clipPoints: function () {
  6852. // polygons need a different clipping algorithm so we redefine that
  6853. var bounds = this._renderer._bounds,
  6854. w = this.options.weight,
  6855. p = new Point(w, w);
  6856. // increase clip padding by stroke width to avoid stroke on clip edges
  6857. bounds = new Bounds(bounds.min.subtract(p), bounds.max.add(p));
  6858. this._parts = [];
  6859. if (!this._pxBounds || !this._pxBounds.intersects(bounds)) {
  6860. return;
  6861. }
  6862. if (this.options.noClip) {
  6863. this._parts = this._rings;
  6864. return;
  6865. }
  6866. for (var i = 0, len = this._rings.length, clipped; i < len; i++) {
  6867. clipped = clipPolygon(this._rings[i], bounds, true);
  6868. if (clipped.length) {
  6869. this._parts.push(clipped);
  6870. }
  6871. }
  6872. },
  6873. _updatePath: function () {
  6874. this._renderer._updatePoly(this, true);
  6875. },
  6876. // Needed by the `Canvas` renderer for interactivity
  6877. _containsPoint: function (p) {
  6878. var inside = false,
  6879. part, p1, p2, i, j, k, len, len2;
  6880. if (!this._pxBounds.contains(p)) { return false; }
  6881. // ray casting algorithm for detecting if point is in polygon
  6882. for (i = 0, len = this._parts.length; i < len; i++) {
  6883. part = this._parts[i];
  6884. for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
  6885. p1 = part[j];
  6886. p2 = part[k];
  6887. 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)) {
  6888. inside = !inside;
  6889. }
  6890. }
  6891. }
  6892. // also check if it's on polygon stroke
  6893. return inside || Polyline.prototype._containsPoint.call(this, p, true);
  6894. }
  6895. });
  6896. // @factory L.polygon(latlngs: LatLng[], options?: Polyline options)
  6897. function polygon(latlngs, options) {
  6898. return new Polygon(latlngs, options);
  6899. }
  6900. /*
  6901. * @class GeoJSON
  6902. * @aka L.GeoJSON
  6903. * @inherits FeatureGroup
  6904. *
  6905. * Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse
  6906. * GeoJSON data and display it on the map. Extends `FeatureGroup`.
  6907. *
  6908. * @example
  6909. *
  6910. * ```js
  6911. * L.geoJSON(data, {
  6912. * style: function (feature) {
  6913. * return {color: feature.properties.color};
  6914. * }
  6915. * }).bindPopup(function (layer) {
  6916. * return layer.feature.properties.description;
  6917. * }).addTo(map);
  6918. * ```
  6919. */
  6920. var GeoJSON = FeatureGroup.extend({
  6921. /* @section
  6922. * @aka GeoJSON options
  6923. *
  6924. * @option pointToLayer: Function = *
  6925. * A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally
  6926. * called when data is added, passing the GeoJSON point feature and its `LatLng`.
  6927. * The default is to spawn a default `Marker`:
  6928. * ```js
  6929. * function(geoJsonPoint, latlng) {
  6930. * return L.marker(latlng);
  6931. * }
  6932. * ```
  6933. *
  6934. * @option style: Function = *
  6935. * A `Function` defining the `Path options` for styling GeoJSON lines and polygons,
  6936. * called internally when data is added.
  6937. * The default value is to not override any defaults:
  6938. * ```js
  6939. * function (geoJsonFeature) {
  6940. * return {}
  6941. * }
  6942. * ```
  6943. *
  6944. * @option onEachFeature: Function = *
  6945. * A `Function` that will be called once for each created `Feature`, after it has
  6946. * been created and styled. Useful for attaching events and popups to features.
  6947. * The default is to do nothing with the newly created layers:
  6948. * ```js
  6949. * function (feature, layer) {}
  6950. * ```
  6951. *
  6952. * @option filter: Function = *
  6953. * A `Function` that will be used to decide whether to include a feature or not.
  6954. * The default is to include all features:
  6955. * ```js
  6956. * function (geoJsonFeature) {
  6957. * return true;
  6958. * }
  6959. * ```
  6960. * Note: dynamically changing the `filter` option will have effect only on newly
  6961. * added data. It will _not_ re-evaluate already included features.
  6962. *
  6963. * @option coordsToLatLng: Function = *
  6964. * A `Function` that will be used for converting GeoJSON coordinates to `LatLng`s.
  6965. * The default is the `coordsToLatLng` static method.
  6966. */
  6967. initialize: function (geojson, options) {
  6968. setOptions(this, options);
  6969. this._layers = {};
  6970. if (geojson) {
  6971. this.addData(geojson);
  6972. }
  6973. },
  6974. // @method addData( <GeoJSON> data ): this
  6975. // Adds a GeoJSON object to the layer.
  6976. addData: function (geojson) {
  6977. var features = isArray(geojson) ? geojson : geojson.features,
  6978. i, len, feature;
  6979. if (features) {
  6980. for (i = 0, len = features.length; i < len; i++) {
  6981. // only add this if geometry or geometries are set and not null
  6982. feature = features[i];
  6983. if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
  6984. this.addData(feature);
  6985. }
  6986. }
  6987. return this;
  6988. }
  6989. var options = this.options;
  6990. if (options.filter && !options.filter(geojson)) { return this; }
  6991. var layer = geometryToLayer(geojson, options);
  6992. if (!layer) {
  6993. return this;
  6994. }
  6995. layer.feature = asFeature(geojson);
  6996. layer.defaultOptions = layer.options;
  6997. this.resetStyle(layer);
  6998. if (options.onEachFeature) {
  6999. options.onEachFeature(geojson, layer);
  7000. }
  7001. return this.addLayer(layer);
  7002. },
  7003. // @method resetStyle( <Path> layer ): this
  7004. // Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events.
  7005. resetStyle: function (layer) {
  7006. // reset any custom styles
  7007. layer.options = extend({}, layer.defaultOptions);
  7008. this._setLayerStyle(layer, this.options.style);
  7009. return this;
  7010. },
  7011. // @method setStyle( <Function> style ): this
  7012. // Changes styles of GeoJSON vector layers with the given style function.
  7013. setStyle: function (style) {
  7014. return this.eachLayer(function (layer) {
  7015. this._setLayerStyle(layer, style);
  7016. }, this);
  7017. },
  7018. _setLayerStyle: function (layer, style) {
  7019. if (typeof style === 'function') {
  7020. style = style(layer.feature);
  7021. }
  7022. if (layer.setStyle) {
  7023. layer.setStyle(style);
  7024. }
  7025. }
  7026. });
  7027. // @section
  7028. // There are several static functions which can be called without instantiating L.GeoJSON:
  7029. // @function geometryToLayer(featureData: Object, options?: GeoJSON options): Layer
  7030. // Creates a `Layer` from a given GeoJSON feature. Can use a custom
  7031. // [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng)
  7032. // functions if provided as options.
  7033. function geometryToLayer(geojson, options) {
  7034. var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
  7035. coords = geometry ? geometry.coordinates : null,
  7036. layers = [],
  7037. pointToLayer = options && options.pointToLayer,
  7038. _coordsToLatLng = options && options.coordsToLatLng || coordsToLatLng,
  7039. latlng, latlngs, i, len;
  7040. if (!coords && !geometry) {
  7041. return null;
  7042. }
  7043. switch (geometry.type) {
  7044. case 'Point':
  7045. latlng = _coordsToLatLng(coords);
  7046. return pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng);
  7047. case 'MultiPoint':
  7048. for (i = 0, len = coords.length; i < len; i++) {
  7049. latlng = _coordsToLatLng(coords[i]);
  7050. layers.push(pointToLayer ? pointToLayer(geojson, latlng) : new Marker(latlng));
  7051. }
  7052. return new FeatureGroup(layers);
  7053. case 'LineString':
  7054. case 'MultiLineString':
  7055. latlngs = coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, _coordsToLatLng);
  7056. return new Polyline(latlngs, options);
  7057. case 'Polygon':
  7058. case 'MultiPolygon':
  7059. latlngs = coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, _coordsToLatLng);
  7060. return new Polygon(latlngs, options);
  7061. case 'GeometryCollection':
  7062. for (i = 0, len = geometry.geometries.length; i < len; i++) {
  7063. var layer = geometryToLayer({
  7064. geometry: geometry.geometries[i],
  7065. type: 'Feature',
  7066. properties: geojson.properties
  7067. }, options);
  7068. if (layer) {
  7069. layers.push(layer);
  7070. }
  7071. }
  7072. return new FeatureGroup(layers);
  7073. default:
  7074. throw new Error('Invalid GeoJSON object.');
  7075. }
  7076. }
  7077. // @function coordsToLatLng(coords: Array): LatLng
  7078. // Creates a `LatLng` object from an array of 2 numbers (longitude, latitude)
  7079. // or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.
  7080. function coordsToLatLng(coords) {
  7081. return new LatLng(coords[1], coords[0], coords[2]);
  7082. }
  7083. // @function coordsToLatLngs(coords: Array, levelsDeep?: Number, coordsToLatLng?: Function): Array
  7084. // Creates a multidimensional array of `LatLng`s from a GeoJSON coordinates array.
  7085. // `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default).
  7086. // Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function.
  7087. function coordsToLatLngs(coords, levelsDeep, _coordsToLatLng) {
  7088. var latlngs = [];
  7089. for (var i = 0, len = coords.length, latlng; i < len; i++) {
  7090. latlng = levelsDeep ?
  7091. coordsToLatLngs(coords[i], levelsDeep - 1, _coordsToLatLng) :
  7092. (_coordsToLatLng || coordsToLatLng)(coords[i]);
  7093. latlngs.push(latlng);
  7094. }
  7095. return latlngs;
  7096. }
  7097. // @function latLngToCoords(latlng: LatLng, precision?: Number): Array
  7098. // Reverse of [`coordsToLatLng`](#geojson-coordstolatlng)
  7099. function latLngToCoords(latlng, precision) {
  7100. precision = typeof precision === 'number' ? precision : 6;
  7101. return latlng.alt !== undefined ?
  7102. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision), formatNum(latlng.alt, precision)] :
  7103. [formatNum(latlng.lng, precision), formatNum(latlng.lat, precision)];
  7104. }
  7105. // @function latLngsToCoords(latlngs: Array, levelsDeep?: Number, closed?: Boolean): Array
  7106. // Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs)
  7107. // `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.
  7108. function latLngsToCoords(latlngs, levelsDeep, closed, precision) {
  7109. var coords = [];
  7110. for (var i = 0, len = latlngs.length; i < len; i++) {
  7111. coords.push(levelsDeep ?
  7112. latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) :
  7113. latLngToCoords(latlngs[i], precision));
  7114. }
  7115. if (!levelsDeep && closed) {
  7116. coords.push(coords[0]);
  7117. }
  7118. return coords;
  7119. }
  7120. function getFeature(layer, newGeometry) {
  7121. return layer.feature ?
  7122. extend({}, layer.feature, {geometry: newGeometry}) :
  7123. asFeature(newGeometry);
  7124. }
  7125. // @function asFeature(geojson: Object): Object
  7126. // Normalize GeoJSON geometries/features into GeoJSON features.
  7127. function asFeature(geojson) {
  7128. if (geojson.type === 'Feature' || geojson.type === 'FeatureCollection') {
  7129. return geojson;
  7130. }
  7131. return {
  7132. type: 'Feature',
  7133. properties: {},
  7134. geometry: geojson
  7135. };
  7136. }
  7137. var PointToGeoJSON = {
  7138. toGeoJSON: function (precision) {
  7139. return getFeature(this, {
  7140. type: 'Point',
  7141. coordinates: latLngToCoords(this.getLatLng(), precision)
  7142. });
  7143. }
  7144. };
  7145. // @namespace Marker
  7146. // @method toGeoJSON(): Object
  7147. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON `Point` Feature).
  7148. Marker.include(PointToGeoJSON);
  7149. // @namespace CircleMarker
  7150. // @method toGeoJSON(): Object
  7151. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON `Point` Feature).
  7152. Circle.include(PointToGeoJSON);
  7153. CircleMarker.include(PointToGeoJSON);
  7154. // @namespace Polyline
  7155. // @method toGeoJSON(): Object
  7156. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature).
  7157. Polyline.include({
  7158. toGeoJSON: function (precision) {
  7159. var multi = !isFlat(this._latlngs);
  7160. var coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision);
  7161. return getFeature(this, {
  7162. type: (multi ? 'Multi' : '') + 'LineString',
  7163. coordinates: coords
  7164. });
  7165. }
  7166. });
  7167. // @namespace Polygon
  7168. // @method toGeoJSON(): Object
  7169. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON `Polygon` or `MultiPolygon` Feature).
  7170. Polygon.include({
  7171. toGeoJSON: function (precision) {
  7172. var holes = !isFlat(this._latlngs),
  7173. multi = holes && !isFlat(this._latlngs[0]);
  7174. var coords = latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true, precision);
  7175. if (!holes) {
  7176. coords = [coords];
  7177. }
  7178. return getFeature(this, {
  7179. type: (multi ? 'Multi' : '') + 'Polygon',
  7180. coordinates: coords
  7181. });
  7182. }
  7183. });
  7184. // @namespace LayerGroup
  7185. LayerGroup.include({
  7186. toMultiPoint: function (precision) {
  7187. var coords = [];
  7188. this.eachLayer(function (layer) {
  7189. coords.push(layer.toGeoJSON(precision).geometry.coordinates);
  7190. });
  7191. return getFeature(this, {
  7192. type: 'MultiPoint',
  7193. coordinates: coords
  7194. });
  7195. },
  7196. // @method toGeoJSON(): Object
  7197. // Returns a [`GeoJSON`](http://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`).
  7198. toGeoJSON: function (precision) {
  7199. var type = this.feature && this.feature.geometry && this.feature.geometry.type;
  7200. if (type === 'MultiPoint') {
  7201. return this.toMultiPoint(precision);
  7202. }
  7203. var isGeometryCollection = type === 'GeometryCollection',
  7204. jsons = [];
  7205. this.eachLayer(function (layer) {
  7206. if (layer.toGeoJSON) {
  7207. var json = layer.toGeoJSON(precision);
  7208. if (isGeometryCollection) {
  7209. jsons.push(json.geometry);
  7210. } else {
  7211. var feature = asFeature(json);
  7212. // Squash nested feature collections
  7213. if (feature.type === 'FeatureCollection') {
  7214. jsons.push.apply(jsons, feature.features);
  7215. } else {
  7216. jsons.push(feature);
  7217. }
  7218. }
  7219. }
  7220. });
  7221. if (isGeometryCollection) {
  7222. return getFeature(this, {
  7223. geometries: jsons,
  7224. type: 'GeometryCollection'
  7225. });
  7226. }
  7227. return {
  7228. type: 'FeatureCollection',
  7229. features: jsons
  7230. };
  7231. }
  7232. });
  7233. // @namespace GeoJSON
  7234. // @factory L.geoJSON(geojson?: Object, options?: GeoJSON options)
  7235. // Creates a GeoJSON layer. Optionally accepts an object in
  7236. // [GeoJSON format](http://geojson.org/geojson-spec.html) to display on the map
  7237. // (you can alternatively add it later with `addData` method) and an `options` object.
  7238. function geoJSON(geojson, options) {
  7239. return new GeoJSON(geojson, options);
  7240. }
  7241. // Backward compatibility.
  7242. var geoJson = geoJSON;
  7243. /*
  7244. * @class ImageOverlay
  7245. * @aka L.ImageOverlay
  7246. * @inherits Interactive layer
  7247. *
  7248. * Used to load and display a single image over specific bounds of the map. Extends `Layer`.
  7249. *
  7250. * @example
  7251. *
  7252. * ```js
  7253. * var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
  7254. * imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
  7255. * L.imageOverlay(imageUrl, imageBounds).addTo(map);
  7256. * ```
  7257. */
  7258. var ImageOverlay = Layer.extend({
  7259. // @section
  7260. // @aka ImageOverlay options
  7261. options: {
  7262. // @option opacity: Number = 1.0
  7263. // The opacity of the image overlay.
  7264. opacity: 1,
  7265. // @option alt: String = ''
  7266. // Text for the `alt` attribute of the image (useful for accessibility).
  7267. alt: '',
  7268. // @option interactive: Boolean = false
  7269. // If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered.
  7270. interactive: false,
  7271. // @option crossOrigin: Boolean = false
  7272. // If true, the image will have its crossOrigin attribute set to ''. This is needed if you want to access image pixel data.
  7273. crossOrigin: false,
  7274. // @option errorOverlayUrl: String = ''
  7275. // URL to the overlay image to show in place of the overlay that failed to load.
  7276. errorOverlayUrl: '',
  7277. // @option zIndex: Number = 1
  7278. // The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the tile layer.
  7279. zIndex: 1,
  7280. // @option className: String = ''
  7281. // A custom class name to assign to the image. Empty by default.
  7282. className: '',
  7283. },
  7284. initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
  7285. this._url = url;
  7286. this._bounds = toLatLngBounds(bounds);
  7287. setOptions(this, options);
  7288. },
  7289. onAdd: function () {
  7290. if (!this._image) {
  7291. this._initImage();
  7292. if (this.options.opacity < 1) {
  7293. this._updateOpacity();
  7294. }
  7295. }
  7296. if (this.options.interactive) {
  7297. addClass(this._image, 'leaflet-interactive');
  7298. this.addInteractiveTarget(this._image);
  7299. }
  7300. this.getPane().appendChild(this._image);
  7301. this._reset();
  7302. },
  7303. onRemove: function () {
  7304. remove(this._image);
  7305. if (this.options.interactive) {
  7306. this.removeInteractiveTarget(this._image);
  7307. }
  7308. },
  7309. // @method setOpacity(opacity: Number): this
  7310. // Sets the opacity of the overlay.
  7311. setOpacity: function (opacity) {
  7312. this.options.opacity = opacity;
  7313. if (this._image) {
  7314. this._updateOpacity();
  7315. }
  7316. return this;
  7317. },
  7318. setStyle: function (styleOpts) {
  7319. if (styleOpts.opacity) {
  7320. this.setOpacity(styleOpts.opacity);
  7321. }
  7322. return this;
  7323. },
  7324. // @method bringToFront(): this
  7325. // Brings the layer to the top of all overlays.
  7326. bringToFront: function () {
  7327. if (this._map) {
  7328. toFront(this._image);
  7329. }
  7330. return this;
  7331. },
  7332. // @method bringToBack(): this
  7333. // Brings the layer to the bottom of all overlays.
  7334. bringToBack: function () {
  7335. if (this._map) {
  7336. toBack(this._image);
  7337. }
  7338. return this;
  7339. },
  7340. // @method setUrl(url: String): this
  7341. // Changes the URL of the image.
  7342. setUrl: function (url) {
  7343. this._url = url;
  7344. if (this._image) {
  7345. this._image.src = url;
  7346. }
  7347. return this;
  7348. },
  7349. // @method setBounds(bounds: LatLngBounds): this
  7350. // Update the bounds that this ImageOverlay covers
  7351. setBounds: function (bounds) {
  7352. this._bounds = toLatLngBounds(bounds);
  7353. if (this._map) {
  7354. this._reset();
  7355. }
  7356. return this;
  7357. },
  7358. getEvents: function () {
  7359. var events = {
  7360. zoom: this._reset,
  7361. viewreset: this._reset
  7362. };
  7363. if (this._zoomAnimated) {
  7364. events.zoomanim = this._animateZoom;
  7365. }
  7366. return events;
  7367. },
  7368. // @method: setZIndex(value: Number) : this
  7369. // Changes the [zIndex](#imageoverlay-zindex) of the image overlay.
  7370. setZIndex: function (value) {
  7371. this.options.zIndex = value;
  7372. this._updateZIndex();
  7373. return this;
  7374. },
  7375. // @method getBounds(): LatLngBounds
  7376. // Get the bounds that this ImageOverlay covers
  7377. getBounds: function () {
  7378. return this._bounds;
  7379. },
  7380. // @method getElement(): HTMLElement
  7381. // Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement)
  7382. // used by this overlay.
  7383. getElement: function () {
  7384. return this._image;
  7385. },
  7386. _initImage: function () {
  7387. var wasElementSupplied = this._url.tagName === 'IMG';
  7388. var img = this._image = wasElementSupplied ? this._url : create$1('img');
  7389. addClass(img, 'leaflet-image-layer');
  7390. if (this._zoomAnimated) { addClass(img, 'leaflet-zoom-animated'); }
  7391. if (this.options.className) { addClass(img, this.options.className); }
  7392. img.onselectstart = falseFn;
  7393. img.onmousemove = falseFn;
  7394. // @event load: Event
  7395. // Fired when the ImageOverlay layer has loaded its image
  7396. img.onload = bind(this.fire, this, 'load');
  7397. img.onerror = bind(this._overlayOnError, this, 'error');
  7398. if (this.options.crossOrigin) {
  7399. img.crossOrigin = '';
  7400. }
  7401. if (this.options.zIndex) {
  7402. this._updateZIndex();
  7403. }
  7404. if (wasElementSupplied) {
  7405. this._url = img.src;
  7406. return;
  7407. }
  7408. img.src = this._url;
  7409. img.alt = this.options.alt;
  7410. },
  7411. _animateZoom: function (e) {
  7412. var scale = this._map.getZoomScale(e.zoom),
  7413. offset = this._map._latLngBoundsToNewLayerBounds(this._bounds, e.zoom, e.center).min;
  7414. setTransform(this._image, offset, scale);
  7415. },
  7416. _reset: function () {
  7417. var image = this._image,
  7418. bounds = new Bounds(
  7419. this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
  7420. this._map.latLngToLayerPoint(this._bounds.getSouthEast())),
  7421. size = bounds.getSize();
  7422. setPosition(image, bounds.min);
  7423. image.style.width = size.x + 'px';
  7424. image.style.height = size.y + 'px';
  7425. },
  7426. _updateOpacity: function () {
  7427. setOpacity(this._image, this.options.opacity);
  7428. },
  7429. _updateZIndex: function () {
  7430. if (this._image && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  7431. this._image.style.zIndex = this.options.zIndex;
  7432. }
  7433. },
  7434. _overlayOnError: function () {
  7435. // @event error: Event
  7436. // Fired when the ImageOverlay layer has loaded its image
  7437. this.fire('error');
  7438. var errorUrl = this.options.errorOverlayUrl;
  7439. if (errorUrl && this._url !== errorUrl) {
  7440. this._url = errorUrl;
  7441. this._image.src = errorUrl;
  7442. }
  7443. }
  7444. });
  7445. // @factory L.imageOverlay(imageUrl: String, bounds: LatLngBounds, options?: ImageOverlay options)
  7446. // Instantiates an image overlay object given the URL of the image and the
  7447. // geographical bounds it is tied to.
  7448. var imageOverlay = function (url, bounds, options) {
  7449. return new ImageOverlay(url, bounds, options);
  7450. };
  7451. /*
  7452. * @class VideoOverlay
  7453. * @aka L.VideoOverlay
  7454. * @inherits ImageOverlay
  7455. *
  7456. * Used to load and display a video player over specific bounds of the map. Extends `ImageOverlay`.
  7457. *
  7458. * A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video)
  7459. * HTML5 element.
  7460. *
  7461. * @example
  7462. *
  7463. * ```js
  7464. * var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
  7465. * videoBounds = [[ 32, -130], [ 13, -100]];
  7466. * L.VideoOverlay(videoUrl, videoBounds ).addTo(map);
  7467. * ```
  7468. */
  7469. var VideoOverlay = ImageOverlay.extend({
  7470. // @section
  7471. // @aka VideoOverlay options
  7472. options: {
  7473. // @option autoplay: Boolean = true
  7474. // Whether the video starts playing automatically when loaded.
  7475. autoplay: true,
  7476. // @option loop: Boolean = true
  7477. // Whether the video will loop back to the beginning when played.
  7478. loop: true
  7479. },
  7480. _initImage: function () {
  7481. var wasElementSupplied = this._url.tagName === 'VIDEO';
  7482. var vid = this._image = wasElementSupplied ? this._url : create$1('video');
  7483. addClass(vid, 'leaflet-image-layer');
  7484. if (this._zoomAnimated) { addClass(vid, 'leaflet-zoom-animated'); }
  7485. vid.onselectstart = falseFn;
  7486. vid.onmousemove = falseFn;
  7487. // @event load: Event
  7488. // Fired when the video has finished loading the first frame
  7489. vid.onloadeddata = bind(this.fire, this, 'load');
  7490. if (wasElementSupplied) {
  7491. var sourceElements = vid.getElementsByTagName('source');
  7492. var sources = [];
  7493. for (var j = 0; j < sourceElements.length; j++) {
  7494. sources.push(sourceElements[j].src);
  7495. }
  7496. this._url = (sourceElements.length > 0) ? sources : [vid.src];
  7497. return;
  7498. }
  7499. if (!isArray(this._url)) { this._url = [this._url]; }
  7500. vid.autoplay = !!this.options.autoplay;
  7501. vid.loop = !!this.options.loop;
  7502. for (var i = 0; i < this._url.length; i++) {
  7503. var source = create$1('source');
  7504. source.src = this._url[i];
  7505. vid.appendChild(source);
  7506. }
  7507. }
  7508. // @method getElement(): HTMLVideoElement
  7509. // Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement)
  7510. // used by this overlay.
  7511. });
  7512. // @factory L.videoOverlay(video: String|Array|HTMLVideoElement, bounds: LatLngBounds, options?: VideoOverlay options)
  7513. // Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the
  7514. // geographical bounds it is tied to.
  7515. function videoOverlay(video, bounds, options) {
  7516. return new VideoOverlay(video, bounds, options);
  7517. }
  7518. /*
  7519. * @class DivOverlay
  7520. * @inherits Layer
  7521. * @aka L.DivOverlay
  7522. * Base model for L.Popup and L.Tooltip. Inherit from it for custom popup like plugins.
  7523. */
  7524. // @namespace DivOverlay
  7525. var DivOverlay = Layer.extend({
  7526. // @section
  7527. // @aka DivOverlay options
  7528. options: {
  7529. // @option offset: Point = Point(0, 7)
  7530. // The offset of the popup position. Useful to control the anchor
  7531. // of the popup when opening it on some overlays.
  7532. offset: [0, 7],
  7533. // @option className: String = ''
  7534. // A custom CSS class name to assign to the popup.
  7535. className: '',
  7536. // @option pane: String = 'popupPane'
  7537. // `Map pane` where the popup will be added.
  7538. pane: 'popupPane'
  7539. },
  7540. initialize: function (options, source) {
  7541. setOptions(this, options);
  7542. this._source = source;
  7543. },
  7544. onAdd: function (map) {
  7545. this._zoomAnimated = map._zoomAnimated;
  7546. if (!this._container) {
  7547. this._initLayout();
  7548. }
  7549. if (map._fadeAnimated) {
  7550. setOpacity(this._container, 0);
  7551. }
  7552. clearTimeout(this._removeTimeout);
  7553. this.getPane().appendChild(this._container);
  7554. this.update();
  7555. if (map._fadeAnimated) {
  7556. setOpacity(this._container, 1);
  7557. }
  7558. this.bringToFront();
  7559. },
  7560. onRemove: function (map) {
  7561. if (map._fadeAnimated) {
  7562. setOpacity(this._container, 0);
  7563. this._removeTimeout = setTimeout(bind(remove, undefined, this._container), 200);
  7564. } else {
  7565. remove(this._container);
  7566. }
  7567. },
  7568. // @namespace Popup
  7569. // @method getLatLng: LatLng
  7570. // Returns the geographical point of popup.
  7571. getLatLng: function () {
  7572. return this._latlng;
  7573. },
  7574. // @method setLatLng(latlng: LatLng): this
  7575. // Sets the geographical point where the popup will open.
  7576. setLatLng: function (latlng) {
  7577. this._latlng = toLatLng(latlng);
  7578. if (this._map) {
  7579. this._updatePosition();
  7580. this._adjustPan();
  7581. }
  7582. return this;
  7583. },
  7584. // @method getContent: String|HTMLElement
  7585. // Returns the content of the popup.
  7586. getContent: function () {
  7587. return this._content;
  7588. },
  7589. // @method setContent(htmlContent: String|HTMLElement|Function): this
  7590. // 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.
  7591. setContent: function (content) {
  7592. this._content = content;
  7593. this.update();
  7594. return this;
  7595. },
  7596. // @method getElement: String|HTMLElement
  7597. // Alias for [getContent()](#popup-getcontent)
  7598. getElement: function () {
  7599. return this._container;
  7600. },
  7601. // @method update: null
  7602. // Updates the popup content, layout and position. Useful for updating the popup after something inside changed, e.g. image loaded.
  7603. update: function () {
  7604. if (!this._map) { return; }
  7605. this._container.style.visibility = 'hidden';
  7606. this._updateContent();
  7607. this._updateLayout();
  7608. this._updatePosition();
  7609. this._container.style.visibility = '';
  7610. this._adjustPan();
  7611. },
  7612. getEvents: function () {
  7613. var events = {
  7614. zoom: this._updatePosition,
  7615. viewreset: this._updatePosition
  7616. };
  7617. if (this._zoomAnimated) {
  7618. events.zoomanim = this._animateZoom;
  7619. }
  7620. return events;
  7621. },
  7622. // @method isOpen: Boolean
  7623. // Returns `true` when the popup is visible on the map.
  7624. isOpen: function () {
  7625. return !!this._map && this._map.hasLayer(this);
  7626. },
  7627. // @method bringToFront: this
  7628. // Brings this popup in front of other popups (in the same map pane).
  7629. bringToFront: function () {
  7630. if (this._map) {
  7631. toFront(this._container);
  7632. }
  7633. return this;
  7634. },
  7635. // @method bringToBack: this
  7636. // Brings this popup to the back of other popups (in the same map pane).
  7637. bringToBack: function () {
  7638. if (this._map) {
  7639. toBack(this._container);
  7640. }
  7641. return this;
  7642. },
  7643. _updateContent: function () {
  7644. if (!this._content) { return; }
  7645. var node = this._contentNode;
  7646. var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content;
  7647. if (typeof content === 'string') {
  7648. node.innerHTML = content;
  7649. } else {
  7650. while (node.hasChildNodes()) {
  7651. node.removeChild(node.firstChild);
  7652. }
  7653. node.appendChild(content);
  7654. }
  7655. this.fire('contentupdate');
  7656. },
  7657. _updatePosition: function () {
  7658. if (!this._map) { return; }
  7659. var pos = this._map.latLngToLayerPoint(this._latlng),
  7660. offset = toPoint(this.options.offset),
  7661. anchor = this._getAnchor();
  7662. if (this._zoomAnimated) {
  7663. setPosition(this._container, pos.add(anchor));
  7664. } else {
  7665. offset = offset.add(pos).add(anchor);
  7666. }
  7667. var bottom = this._containerBottom = -offset.y,
  7668. left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x;
  7669. // bottom position the popup in case the height of the popup changes (images loading etc)
  7670. this._container.style.bottom = bottom + 'px';
  7671. this._container.style.left = left + 'px';
  7672. },
  7673. _getAnchor: function () {
  7674. return [0, 0];
  7675. }
  7676. });
  7677. /*
  7678. * @class Popup
  7679. * @inherits DivOverlay
  7680. * @aka L.Popup
  7681. * Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to
  7682. * open popups while making sure that only one popup is open at one time
  7683. * (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want.
  7684. *
  7685. * @example
  7686. *
  7687. * If you want to just bind a popup to marker click and then open it, it's really easy:
  7688. *
  7689. * ```js
  7690. * marker.bindPopup(popupContent).openPopup();
  7691. * ```
  7692. * Path overlays like polylines also have a `bindPopup` method.
  7693. * Here's a more complicated way to open a popup on a map:
  7694. *
  7695. * ```js
  7696. * var popup = L.popup()
  7697. * .setLatLng(latlng)
  7698. * .setContent('<p>Hello world!<br />This is a nice popup.</p>')
  7699. * .openOn(map);
  7700. * ```
  7701. */
  7702. // @namespace Popup
  7703. var Popup = DivOverlay.extend({
  7704. // @section
  7705. // @aka Popup options
  7706. options: {
  7707. // @option maxWidth: Number = 300
  7708. // Max width of the popup, in pixels.
  7709. maxWidth: 300,
  7710. // @option minWidth: Number = 50
  7711. // Min width of the popup, in pixels.
  7712. minWidth: 50,
  7713. // @option maxHeight: Number = null
  7714. // If set, creates a scrollable container of the given height
  7715. // inside a popup if its content exceeds it.
  7716. maxHeight: null,
  7717. // @option autoPan: Boolean = true
  7718. // Set it to `false` if you don't want the map to do panning animation
  7719. // to fit the opened popup.
  7720. autoPan: true,
  7721. // @option autoPanPaddingTopLeft: Point = null
  7722. // The margin between the popup and the top left corner of the map
  7723. // view after autopanning was performed.
  7724. autoPanPaddingTopLeft: null,
  7725. // @option autoPanPaddingBottomRight: Point = null
  7726. // The margin between the popup and the bottom right corner of the map
  7727. // view after autopanning was performed.
  7728. autoPanPaddingBottomRight: null,
  7729. // @option autoPanPadding: Point = Point(5, 5)
  7730. // Equivalent of setting both top left and bottom right autopan padding to the same value.
  7731. autoPanPadding: [5, 5],
  7732. // @option keepInView: Boolean = false
  7733. // Set it to `true` if you want to prevent users from panning the popup
  7734. // off of the screen while it is open.
  7735. keepInView: false,
  7736. // @option closeButton: Boolean = true
  7737. // Controls the presence of a close button in the popup.
  7738. closeButton: true,
  7739. // @option autoClose: Boolean = true
  7740. // Set it to `false` if you want to override the default behavior of
  7741. // the popup closing when another popup is opened.
  7742. autoClose: true,
  7743. // @option closeOnEscapeKey: Boolean = true
  7744. // Set it to `false` if you want to override the default behavior of
  7745. // the ESC key for closing of the popup.
  7746. closeOnEscapeKey: true,
  7747. // @option closeOnClick: Boolean = *
  7748. // Set it if you want to override the default behavior of the popup closing when user clicks
  7749. // on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option.
  7750. // @option className: String = ''
  7751. // A custom CSS class name to assign to the popup.
  7752. className: ''
  7753. },
  7754. // @namespace Popup
  7755. // @method openOn(map: Map): this
  7756. // Adds the popup to the map and closes the previous one. The same as `map.openPopup(popup)`.
  7757. openOn: function (map) {
  7758. map.openPopup(this);
  7759. return this;
  7760. },
  7761. onAdd: function (map) {
  7762. DivOverlay.prototype.onAdd.call(this, map);
  7763. // @namespace Map
  7764. // @section Popup events
  7765. // @event popupopen: PopupEvent
  7766. // Fired when a popup is opened in the map
  7767. map.fire('popupopen', {popup: this});
  7768. if (this._source) {
  7769. // @namespace Layer
  7770. // @section Popup events
  7771. // @event popupopen: PopupEvent
  7772. // Fired when a popup bound to this layer is opened
  7773. this._source.fire('popupopen', {popup: this}, true);
  7774. // For non-path layers, we toggle the popup when clicking
  7775. // again the layer, so prevent the map to reopen it.
  7776. if (!(this._source instanceof Path)) {
  7777. this._source.on('preclick', stopPropagation);
  7778. }
  7779. }
  7780. },
  7781. onRemove: function (map) {
  7782. DivOverlay.prototype.onRemove.call(this, map);
  7783. // @namespace Map
  7784. // @section Popup events
  7785. // @event popupclose: PopupEvent
  7786. // Fired when a popup in the map is closed
  7787. map.fire('popupclose', {popup: this});
  7788. if (this._source) {
  7789. // @namespace Layer
  7790. // @section Popup events
  7791. // @event popupclose: PopupEvent
  7792. // Fired when a popup bound to this layer is closed
  7793. this._source.fire('popupclose', {popup: this}, true);
  7794. if (!(this._source instanceof Path)) {
  7795. this._source.off('preclick', stopPropagation);
  7796. }
  7797. }
  7798. },
  7799. getEvents: function () {
  7800. var events = DivOverlay.prototype.getEvents.call(this);
  7801. if (this.options.closeOnClick !== undefined ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
  7802. events.preclick = this._close;
  7803. }
  7804. if (this.options.keepInView) {
  7805. events.moveend = this._adjustPan;
  7806. }
  7807. return events;
  7808. },
  7809. _close: function () {
  7810. if (this._map) {
  7811. this._map.closePopup(this);
  7812. }
  7813. },
  7814. _initLayout: function () {
  7815. var prefix = 'leaflet-popup',
  7816. container = this._container = create$1('div',
  7817. prefix + ' ' + (this.options.className || '') +
  7818. ' leaflet-zoom-animated');
  7819. var wrapper = this._wrapper = create$1('div', prefix + '-content-wrapper', container);
  7820. this._contentNode = create$1('div', prefix + '-content', wrapper);
  7821. disableClickPropagation(wrapper);
  7822. disableScrollPropagation(this._contentNode);
  7823. on(wrapper, 'contextmenu', stopPropagation);
  7824. this._tipContainer = create$1('div', prefix + '-tip-container', container);
  7825. this._tip = create$1('div', prefix + '-tip', this._tipContainer);
  7826. if (this.options.closeButton) {
  7827. var closeButton = this._closeButton = create$1('a', prefix + '-close-button', container);
  7828. closeButton.href = '#close';
  7829. closeButton.innerHTML = '&#215;';
  7830. on(closeButton, 'click', this._onCloseButtonClick, this);
  7831. }
  7832. },
  7833. _updateLayout: function () {
  7834. var container = this._contentNode,
  7835. style = container.style;
  7836. style.width = '';
  7837. style.whiteSpace = 'nowrap';
  7838. var width = container.offsetWidth;
  7839. width = Math.min(width, this.options.maxWidth);
  7840. width = Math.max(width, this.options.minWidth);
  7841. style.width = (width + 1) + 'px';
  7842. style.whiteSpace = '';
  7843. style.height = '';
  7844. var height = container.offsetHeight,
  7845. maxHeight = this.options.maxHeight,
  7846. scrolledClass = 'leaflet-popup-scrolled';
  7847. if (maxHeight && height > maxHeight) {
  7848. style.height = maxHeight + 'px';
  7849. addClass(container, scrolledClass);
  7850. } else {
  7851. removeClass(container, scrolledClass);
  7852. }
  7853. this._containerWidth = this._container.offsetWidth;
  7854. },
  7855. _animateZoom: function (e) {
  7856. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center),
  7857. anchor = this._getAnchor();
  7858. setPosition(this._container, pos.add(anchor));
  7859. },
  7860. _adjustPan: function () {
  7861. if (!this.options.autoPan || (this._map._panAnim && this._map._panAnim._inProgress)) { return; }
  7862. var map = this._map,
  7863. marginBottom = parseInt(getStyle(this._container, 'marginBottom'), 10) || 0,
  7864. containerHeight = this._container.offsetHeight + marginBottom,
  7865. containerWidth = this._containerWidth,
  7866. layerPos = new Point(this._containerLeft, -containerHeight - this._containerBottom);
  7867. layerPos._add(getPosition(this._container));
  7868. var containerPos = map.layerPointToContainerPoint(layerPos),
  7869. padding = toPoint(this.options.autoPanPadding),
  7870. paddingTL = toPoint(this.options.autoPanPaddingTopLeft || padding),
  7871. paddingBR = toPoint(this.options.autoPanPaddingBottomRight || padding),
  7872. size = map.getSize(),
  7873. dx = 0,
  7874. dy = 0;
  7875. if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
  7876. dx = containerPos.x + containerWidth - size.x + paddingBR.x;
  7877. }
  7878. if (containerPos.x - dx - paddingTL.x < 0) { // left
  7879. dx = containerPos.x - paddingTL.x;
  7880. }
  7881. if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
  7882. dy = containerPos.y + containerHeight - size.y + paddingBR.y;
  7883. }
  7884. if (containerPos.y - dy - paddingTL.y < 0) { // top
  7885. dy = containerPos.y - paddingTL.y;
  7886. }
  7887. // @namespace Map
  7888. // @section Popup events
  7889. // @event autopanstart: Event
  7890. // Fired when the map starts autopanning when opening a popup.
  7891. if (dx || dy) {
  7892. map
  7893. .fire('autopanstart')
  7894. .panBy([dx, dy]);
  7895. }
  7896. },
  7897. _onCloseButtonClick: function (e) {
  7898. this._close();
  7899. stop(e);
  7900. },
  7901. _getAnchor: function () {
  7902. // Where should we anchor the popup on the source layer?
  7903. return toPoint(this._source && this._source._getPopupAnchor ? this._source._getPopupAnchor() : [0, 0]);
  7904. }
  7905. });
  7906. // @namespace Popup
  7907. // @factory L.popup(options?: Popup options, source?: Layer)
  7908. // 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.
  7909. var popup = function (options, source) {
  7910. return new Popup(options, source);
  7911. };
  7912. /* @namespace Map
  7913. * @section Interaction Options
  7914. * @option closePopupOnClick: Boolean = true
  7915. * Set it to `false` if you don't want popups to close when user clicks the map.
  7916. */
  7917. Map.mergeOptions({
  7918. closePopupOnClick: true
  7919. });
  7920. // @namespace Map
  7921. // @section Methods for Layers and Controls
  7922. Map.include({
  7923. // @method openPopup(popup: Popup): this
  7924. // Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
  7925. // @alternative
  7926. // @method openPopup(content: String|HTMLElement, latlng: LatLng, options?: Popup options): this
  7927. // Creates a popup with the specified content and options and opens it in the given point on a map.
  7928. openPopup: function (popup, latlng, options) {
  7929. if (!(popup instanceof Popup)) {
  7930. popup = new Popup(options).setContent(popup);
  7931. }
  7932. if (latlng) {
  7933. popup.setLatLng(latlng);
  7934. }
  7935. if (this.hasLayer(popup)) {
  7936. return this;
  7937. }
  7938. if (this._popup && this._popup.options.autoClose) {
  7939. this.closePopup();
  7940. }
  7941. this._popup = popup;
  7942. return this.addLayer(popup);
  7943. },
  7944. // @method closePopup(popup?: Popup): this
  7945. // Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one).
  7946. closePopup: function (popup) {
  7947. if (!popup || popup === this._popup) {
  7948. popup = this._popup;
  7949. this._popup = null;
  7950. }
  7951. if (popup) {
  7952. this.removeLayer(popup);
  7953. }
  7954. return this;
  7955. }
  7956. });
  7957. /*
  7958. * @namespace Layer
  7959. * @section Popup methods example
  7960. *
  7961. * All layers share a set of methods convenient for binding popups to it.
  7962. *
  7963. * ```js
  7964. * var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
  7965. * layer.openPopup();
  7966. * layer.closePopup();
  7967. * ```
  7968. *
  7969. * 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.
  7970. */
  7971. // @section Popup methods
  7972. Layer.include({
  7973. // @method bindPopup(content: String|HTMLElement|Function|Popup, options?: Popup options): this
  7974. // Binds a popup to the layer with the passed `content` and sets up the
  7975. // necessary event listeners. If a `Function` is passed it will receive
  7976. // the layer as the first argument and should return a `String` or `HTMLElement`.
  7977. bindPopup: function (content, options) {
  7978. if (content instanceof Popup) {
  7979. setOptions(content, options);
  7980. this._popup = content;
  7981. content._source = this;
  7982. } else {
  7983. if (!this._popup || options) {
  7984. this._popup = new Popup(options, this);
  7985. }
  7986. this._popup.setContent(content);
  7987. }
  7988. if (!this._popupHandlersAdded) {
  7989. this.on({
  7990. click: this._openPopup,
  7991. keypress: this._onKeyPress,
  7992. remove: this.closePopup,
  7993. move: this._movePopup
  7994. });
  7995. this._popupHandlersAdded = true;
  7996. }
  7997. return this;
  7998. },
  7999. // @method unbindPopup(): this
  8000. // Removes the popup previously bound with `bindPopup`.
  8001. unbindPopup: function () {
  8002. if (this._popup) {
  8003. this.off({
  8004. click: this._openPopup,
  8005. keypress: this._onKeyPress,
  8006. remove: this.closePopup,
  8007. move: this._movePopup
  8008. });
  8009. this._popupHandlersAdded = false;
  8010. this._popup = null;
  8011. }
  8012. return this;
  8013. },
  8014. // @method openPopup(latlng?: LatLng): this
  8015. // Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed.
  8016. openPopup: function (layer, latlng) {
  8017. if (!(layer instanceof Layer)) {
  8018. latlng = layer;
  8019. layer = this;
  8020. }
  8021. if (layer instanceof FeatureGroup) {
  8022. for (var id in this._layers) {
  8023. layer = this._layers[id];
  8024. break;
  8025. }
  8026. }
  8027. if (!latlng) {
  8028. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8029. }
  8030. if (this._popup && this._map) {
  8031. // set popup source to this layer
  8032. this._popup._source = layer;
  8033. // update the popup (content, layout, ect...)
  8034. this._popup.update();
  8035. // open the popup on the map
  8036. this._map.openPopup(this._popup, latlng);
  8037. }
  8038. return this;
  8039. },
  8040. // @method closePopup(): this
  8041. // Closes the popup bound to this layer if it is open.
  8042. closePopup: function () {
  8043. if (this._popup) {
  8044. this._popup._close();
  8045. }
  8046. return this;
  8047. },
  8048. // @method togglePopup(): this
  8049. // Opens or closes the popup bound to this layer depending on its current state.
  8050. togglePopup: function (target) {
  8051. if (this._popup) {
  8052. if (this._popup._map) {
  8053. this.closePopup();
  8054. } else {
  8055. this.openPopup(target);
  8056. }
  8057. }
  8058. return this;
  8059. },
  8060. // @method isPopupOpen(): boolean
  8061. // Returns `true` if the popup bound to this layer is currently open.
  8062. isPopupOpen: function () {
  8063. return (this._popup ? this._popup.isOpen() : false);
  8064. },
  8065. // @method setPopupContent(content: String|HTMLElement|Popup): this
  8066. // Sets the content of the popup bound to this layer.
  8067. setPopupContent: function (content) {
  8068. if (this._popup) {
  8069. this._popup.setContent(content);
  8070. }
  8071. return this;
  8072. },
  8073. // @method getPopup(): Popup
  8074. // Returns the popup bound to this layer.
  8075. getPopup: function () {
  8076. return this._popup;
  8077. },
  8078. _openPopup: function (e) {
  8079. var layer = e.layer || e.target;
  8080. if (!this._popup) {
  8081. return;
  8082. }
  8083. if (!this._map) {
  8084. return;
  8085. }
  8086. // prevent map click
  8087. stop(e);
  8088. // if this inherits from Path its a vector and we can just
  8089. // open the popup at the new location
  8090. if (layer instanceof Path) {
  8091. this.openPopup(e.layer || e.target, e.latlng);
  8092. return;
  8093. }
  8094. // otherwise treat it like a marker and figure out
  8095. // if we should toggle it open/closed
  8096. if (this._map.hasLayer(this._popup) && this._popup._source === layer) {
  8097. this.closePopup();
  8098. } else {
  8099. this.openPopup(layer, e.latlng);
  8100. }
  8101. },
  8102. _movePopup: function (e) {
  8103. this._popup.setLatLng(e.latlng);
  8104. },
  8105. _onKeyPress: function (e) {
  8106. if (e.originalEvent.keyCode === 13) {
  8107. this._openPopup(e);
  8108. }
  8109. }
  8110. });
  8111. /*
  8112. * @class Tooltip
  8113. * @inherits DivOverlay
  8114. * @aka L.Tooltip
  8115. * Used to display small texts on top of map layers.
  8116. *
  8117. * @example
  8118. *
  8119. * ```js
  8120. * marker.bindTooltip("my tooltip text").openTooltip();
  8121. * ```
  8122. * Note about tooltip offset. Leaflet takes two options in consideration
  8123. * for computing tooltip offsetting:
  8124. * - the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip.
  8125. * Add a positive x offset to move the tooltip to the right, and a positive y offset to
  8126. * move it to the bottom. Negatives will move to the left and top.
  8127. * - the `tooltipAnchor` Icon option: this will only be considered for Marker. You
  8128. * should adapt this value if you use a custom icon.
  8129. */
  8130. // @namespace Tooltip
  8131. var Tooltip = DivOverlay.extend({
  8132. // @section
  8133. // @aka Tooltip options
  8134. options: {
  8135. // @option pane: String = 'tooltipPane'
  8136. // `Map pane` where the tooltip will be added.
  8137. pane: 'tooltipPane',
  8138. // @option offset: Point = Point(0, 0)
  8139. // Optional offset of the tooltip position.
  8140. offset: [0, 0],
  8141. // @option direction: String = 'auto'
  8142. // Direction where to open the tooltip. Possible values are: `right`, `left`,
  8143. // `top`, `bottom`, `center`, `auto`.
  8144. // `auto` will dynamically switch between `right` and `left` according to the tooltip
  8145. // position on the map.
  8146. direction: 'auto',
  8147. // @option permanent: Boolean = false
  8148. // Whether to open the tooltip permanently or only on mouseover.
  8149. permanent: false,
  8150. // @option sticky: Boolean = false
  8151. // If true, the tooltip will follow the mouse instead of being fixed at the feature center.
  8152. sticky: false,
  8153. // @option interactive: Boolean = false
  8154. // If true, the tooltip will listen to the feature events.
  8155. interactive: false,
  8156. // @option opacity: Number = 0.9
  8157. // Tooltip container opacity.
  8158. opacity: 0.9
  8159. },
  8160. onAdd: function (map) {
  8161. DivOverlay.prototype.onAdd.call(this, map);
  8162. this.setOpacity(this.options.opacity);
  8163. // @namespace Map
  8164. // @section Tooltip events
  8165. // @event tooltipopen: TooltipEvent
  8166. // Fired when a tooltip is opened in the map.
  8167. map.fire('tooltipopen', {tooltip: this});
  8168. if (this._source) {
  8169. // @namespace Layer
  8170. // @section Tooltip events
  8171. // @event tooltipopen: TooltipEvent
  8172. // Fired when a tooltip bound to this layer is opened.
  8173. this._source.fire('tooltipopen', {tooltip: this}, true);
  8174. }
  8175. },
  8176. onRemove: function (map) {
  8177. DivOverlay.prototype.onRemove.call(this, map);
  8178. // @namespace Map
  8179. // @section Tooltip events
  8180. // @event tooltipclose: TooltipEvent
  8181. // Fired when a tooltip in the map is closed.
  8182. map.fire('tooltipclose', {tooltip: this});
  8183. if (this._source) {
  8184. // @namespace Layer
  8185. // @section Tooltip events
  8186. // @event tooltipclose: TooltipEvent
  8187. // Fired when a tooltip bound to this layer is closed.
  8188. this._source.fire('tooltipclose', {tooltip: this}, true);
  8189. }
  8190. },
  8191. getEvents: function () {
  8192. var events = DivOverlay.prototype.getEvents.call(this);
  8193. if (touch && !this.options.permanent) {
  8194. events.preclick = this._close;
  8195. }
  8196. return events;
  8197. },
  8198. _close: function () {
  8199. if (this._map) {
  8200. this._map.closeTooltip(this);
  8201. }
  8202. },
  8203. _initLayout: function () {
  8204. var prefix = 'leaflet-tooltip',
  8205. className = prefix + ' ' + (this.options.className || '') + ' leaflet-zoom-' + (this._zoomAnimated ? 'animated' : 'hide');
  8206. this._contentNode = this._container = create$1('div', className);
  8207. },
  8208. _updateLayout: function () {},
  8209. _adjustPan: function () {},
  8210. _setPosition: function (pos) {
  8211. var map = this._map,
  8212. container = this._container,
  8213. centerPoint = map.latLngToContainerPoint(map.getCenter()),
  8214. tooltipPoint = map.layerPointToContainerPoint(pos),
  8215. direction = this.options.direction,
  8216. tooltipWidth = container.offsetWidth,
  8217. tooltipHeight = container.offsetHeight,
  8218. offset = toPoint(this.options.offset),
  8219. anchor = this._getAnchor();
  8220. if (direction === 'top') {
  8221. pos = pos.add(toPoint(-tooltipWidth / 2 + offset.x, -tooltipHeight + offset.y + anchor.y, true));
  8222. } else if (direction === 'bottom') {
  8223. pos = pos.subtract(toPoint(tooltipWidth / 2 - offset.x, -offset.y, true));
  8224. } else if (direction === 'center') {
  8225. pos = pos.subtract(toPoint(tooltipWidth / 2 + offset.x, tooltipHeight / 2 - anchor.y + offset.y, true));
  8226. } else if (direction === 'right' || direction === 'auto' && tooltipPoint.x < centerPoint.x) {
  8227. direction = 'right';
  8228. pos = pos.add(toPoint(offset.x + anchor.x, anchor.y - tooltipHeight / 2 + offset.y, true));
  8229. } else {
  8230. direction = 'left';
  8231. pos = pos.subtract(toPoint(tooltipWidth + anchor.x - offset.x, tooltipHeight / 2 - anchor.y - offset.y, true));
  8232. }
  8233. removeClass(container, 'leaflet-tooltip-right');
  8234. removeClass(container, 'leaflet-tooltip-left');
  8235. removeClass(container, 'leaflet-tooltip-top');
  8236. removeClass(container, 'leaflet-tooltip-bottom');
  8237. addClass(container, 'leaflet-tooltip-' + direction);
  8238. setPosition(container, pos);
  8239. },
  8240. _updatePosition: function () {
  8241. var pos = this._map.latLngToLayerPoint(this._latlng);
  8242. this._setPosition(pos);
  8243. },
  8244. setOpacity: function (opacity) {
  8245. this.options.opacity = opacity;
  8246. if (this._container) {
  8247. setOpacity(this._container, opacity);
  8248. }
  8249. },
  8250. _animateZoom: function (e) {
  8251. var pos = this._map._latLngToNewLayerPoint(this._latlng, e.zoom, e.center);
  8252. this._setPosition(pos);
  8253. },
  8254. _getAnchor: function () {
  8255. // Where should we anchor the tooltip on the source layer?
  8256. return toPoint(this._source && this._source._getTooltipAnchor && !this.options.sticky ? this._source._getTooltipAnchor() : [0, 0]);
  8257. }
  8258. });
  8259. // @namespace Tooltip
  8260. // @factory L.tooltip(options?: Tooltip options, source?: Layer)
  8261. // 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.
  8262. var tooltip = function (options, source) {
  8263. return new Tooltip(options, source);
  8264. };
  8265. // @namespace Map
  8266. // @section Methods for Layers and Controls
  8267. Map.include({
  8268. // @method openTooltip(tooltip: Tooltip): this
  8269. // Opens the specified tooltip.
  8270. // @alternative
  8271. // @method openTooltip(content: String|HTMLElement, latlng: LatLng, options?: Tooltip options): this
  8272. // Creates a tooltip with the specified content and options and open it.
  8273. openTooltip: function (tooltip, latlng, options) {
  8274. if (!(tooltip instanceof Tooltip)) {
  8275. tooltip = new Tooltip(options).setContent(tooltip);
  8276. }
  8277. if (latlng) {
  8278. tooltip.setLatLng(latlng);
  8279. }
  8280. if (this.hasLayer(tooltip)) {
  8281. return this;
  8282. }
  8283. return this.addLayer(tooltip);
  8284. },
  8285. // @method closeTooltip(tooltip?: Tooltip): this
  8286. // Closes the tooltip given as parameter.
  8287. closeTooltip: function (tooltip) {
  8288. if (tooltip) {
  8289. this.removeLayer(tooltip);
  8290. }
  8291. return this;
  8292. }
  8293. });
  8294. /*
  8295. * @namespace Layer
  8296. * @section Tooltip methods example
  8297. *
  8298. * All layers share a set of methods convenient for binding tooltips to it.
  8299. *
  8300. * ```js
  8301. * var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map);
  8302. * layer.openTooltip();
  8303. * layer.closeTooltip();
  8304. * ```
  8305. */
  8306. // @section Tooltip methods
  8307. Layer.include({
  8308. // @method bindTooltip(content: String|HTMLElement|Function|Tooltip, options?: Tooltip options): this
  8309. // Binds a tooltip to the layer with the passed `content` and sets up the
  8310. // necessary event listeners. If a `Function` is passed it will receive
  8311. // the layer as the first argument and should return a `String` or `HTMLElement`.
  8312. bindTooltip: function (content, options) {
  8313. if (content instanceof Tooltip) {
  8314. setOptions(content, options);
  8315. this._tooltip = content;
  8316. content._source = this;
  8317. } else {
  8318. if (!this._tooltip || options) {
  8319. this._tooltip = new Tooltip(options, this);
  8320. }
  8321. this._tooltip.setContent(content);
  8322. }
  8323. this._initTooltipInteractions();
  8324. if (this._tooltip.options.permanent && this._map && this._map.hasLayer(this)) {
  8325. this.openTooltip();
  8326. }
  8327. return this;
  8328. },
  8329. // @method unbindTooltip(): this
  8330. // Removes the tooltip previously bound with `bindTooltip`.
  8331. unbindTooltip: function () {
  8332. if (this._tooltip) {
  8333. this._initTooltipInteractions(true);
  8334. this.closeTooltip();
  8335. this._tooltip = null;
  8336. }
  8337. return this;
  8338. },
  8339. _initTooltipInteractions: function (remove$$1) {
  8340. if (!remove$$1 && this._tooltipHandlersAdded) { return; }
  8341. var onOff = remove$$1 ? 'off' : 'on',
  8342. events = {
  8343. remove: this.closeTooltip,
  8344. move: this._moveTooltip
  8345. };
  8346. if (!this._tooltip.options.permanent) {
  8347. events.mouseover = this._openTooltip;
  8348. events.mouseout = this.closeTooltip;
  8349. if (this._tooltip.options.sticky) {
  8350. events.mousemove = this._moveTooltip;
  8351. }
  8352. if (touch) {
  8353. events.click = this._openTooltip;
  8354. }
  8355. } else {
  8356. events.add = this._openTooltip;
  8357. }
  8358. this[onOff](events);
  8359. this._tooltipHandlersAdded = !remove$$1;
  8360. },
  8361. // @method openTooltip(latlng?: LatLng): this
  8362. // Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed.
  8363. openTooltip: function (layer, latlng) {
  8364. if (!(layer instanceof Layer)) {
  8365. latlng = layer;
  8366. layer = this;
  8367. }
  8368. if (layer instanceof FeatureGroup) {
  8369. for (var id in this._layers) {
  8370. layer = this._layers[id];
  8371. break;
  8372. }
  8373. }
  8374. if (!latlng) {
  8375. latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng();
  8376. }
  8377. if (this._tooltip && this._map) {
  8378. // set tooltip source to this layer
  8379. this._tooltip._source = layer;
  8380. // update the tooltip (content, layout, ect...)
  8381. this._tooltip.update();
  8382. // open the tooltip on the map
  8383. this._map.openTooltip(this._tooltip, latlng);
  8384. // Tooltip container may not be defined if not permanent and never
  8385. // opened.
  8386. if (this._tooltip.options.interactive && this._tooltip._container) {
  8387. addClass(this._tooltip._container, 'leaflet-clickable');
  8388. this.addInteractiveTarget(this._tooltip._container);
  8389. }
  8390. }
  8391. return this;
  8392. },
  8393. // @method closeTooltip(): this
  8394. // Closes the tooltip bound to this layer if it is open.
  8395. closeTooltip: function () {
  8396. if (this._tooltip) {
  8397. this._tooltip._close();
  8398. if (this._tooltip.options.interactive && this._tooltip._container) {
  8399. removeClass(this._tooltip._container, 'leaflet-clickable');
  8400. this.removeInteractiveTarget(this._tooltip._container);
  8401. }
  8402. }
  8403. return this;
  8404. },
  8405. // @method toggleTooltip(): this
  8406. // Opens or closes the tooltip bound to this layer depending on its current state.
  8407. toggleTooltip: function (target) {
  8408. if (this._tooltip) {
  8409. if (this._tooltip._map) {
  8410. this.closeTooltip();
  8411. } else {
  8412. this.openTooltip(target);
  8413. }
  8414. }
  8415. return this;
  8416. },
  8417. // @method isTooltipOpen(): boolean
  8418. // Returns `true` if the tooltip bound to this layer is currently open.
  8419. isTooltipOpen: function () {
  8420. return this._tooltip.isOpen();
  8421. },
  8422. // @method setTooltipContent(content: String|HTMLElement|Tooltip): this
  8423. // Sets the content of the tooltip bound to this layer.
  8424. setTooltipContent: function (content) {
  8425. if (this._tooltip) {
  8426. this._tooltip.setContent(content);
  8427. }
  8428. return this;
  8429. },
  8430. // @method getTooltip(): Tooltip
  8431. // Returns the tooltip bound to this layer.
  8432. getTooltip: function () {
  8433. return this._tooltip;
  8434. },
  8435. _openTooltip: function (e) {
  8436. var layer = e.layer || e.target;
  8437. if (!this._tooltip || !this._map) {
  8438. return;
  8439. }
  8440. this.openTooltip(layer, this._tooltip.options.sticky ? e.latlng : undefined);
  8441. },
  8442. _moveTooltip: function (e) {
  8443. var latlng = e.latlng, containerPoint, layerPoint;
  8444. if (this._tooltip.options.sticky && e.originalEvent) {
  8445. containerPoint = this._map.mouseEventToContainerPoint(e.originalEvent);
  8446. layerPoint = this._map.containerPointToLayerPoint(containerPoint);
  8447. latlng = this._map.layerPointToLatLng(layerPoint);
  8448. }
  8449. this._tooltip.setLatLng(latlng);
  8450. }
  8451. });
  8452. /*
  8453. * @class DivIcon
  8454. * @aka L.DivIcon
  8455. * @inherits Icon
  8456. *
  8457. * Represents a lightweight icon for markers that uses a simple `<div>`
  8458. * element instead of an image. Inherits from `Icon` but ignores the `iconUrl` and shadow options.
  8459. *
  8460. * @example
  8461. * ```js
  8462. * var myIcon = L.divIcon({className: 'my-div-icon'});
  8463. * // you can set .my-div-icon styles in CSS
  8464. *
  8465. * L.marker([50.505, 30.57], {icon: myIcon}).addTo(map);
  8466. * ```
  8467. *
  8468. * By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow.
  8469. */
  8470. var DivIcon = Icon.extend({
  8471. options: {
  8472. // @section
  8473. // @aka DivIcon options
  8474. iconSize: [12, 12], // also can be set through CSS
  8475. // iconAnchor: (Point),
  8476. // popupAnchor: (Point),
  8477. // @option html: String = ''
  8478. // Custom HTML code to put inside the div element, empty by default.
  8479. html: false,
  8480. // @option bgPos: Point = [0, 0]
  8481. // Optional relative position of the background, in pixels
  8482. bgPos: null,
  8483. className: 'leaflet-div-icon'
  8484. },
  8485. createIcon: function (oldIcon) {
  8486. var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
  8487. options = this.options;
  8488. div.innerHTML = options.html !== false ? options.html : '';
  8489. if (options.bgPos) {
  8490. var bgPos = toPoint(options.bgPos);
  8491. div.style.backgroundPosition = (-bgPos.x) + 'px ' + (-bgPos.y) + 'px';
  8492. }
  8493. this._setIconStyles(div, 'icon');
  8494. return div;
  8495. },
  8496. createShadow: function () {
  8497. return null;
  8498. }
  8499. });
  8500. // @factory L.divIcon(options: DivIcon options)
  8501. // Creates a `DivIcon` instance with the given options.
  8502. function divIcon(options) {
  8503. return new DivIcon(options);
  8504. }
  8505. Icon.Default = IconDefault;
  8506. /*
  8507. * @class GridLayer
  8508. * @inherits Layer
  8509. * @aka L.GridLayer
  8510. *
  8511. * Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`.
  8512. * 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.
  8513. *
  8514. *
  8515. * @section Synchronous usage
  8516. * @example
  8517. *
  8518. * 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.
  8519. *
  8520. * ```js
  8521. * var CanvasLayer = L.GridLayer.extend({
  8522. * createTile: function(coords){
  8523. * // create a <canvas> element for drawing
  8524. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8525. *
  8526. * // setup tile width and height according to the options
  8527. * var size = this.getTileSize();
  8528. * tile.width = size.x;
  8529. * tile.height = size.y;
  8530. *
  8531. * // get a canvas context and draw something on it using coords.x, coords.y and coords.z
  8532. * var ctx = tile.getContext('2d');
  8533. *
  8534. * // return the tile so it can be rendered on screen
  8535. * return tile;
  8536. * }
  8537. * });
  8538. * ```
  8539. *
  8540. * @section Asynchronous usage
  8541. * @example
  8542. *
  8543. * 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.
  8544. *
  8545. * ```js
  8546. * var CanvasLayer = L.GridLayer.extend({
  8547. * createTile: function(coords, done){
  8548. * var error;
  8549. *
  8550. * // create a <canvas> element for drawing
  8551. * var tile = L.DomUtil.create('canvas', 'leaflet-tile');
  8552. *
  8553. * // setup tile width and height according to the options
  8554. * var size = this.getTileSize();
  8555. * tile.width = size.x;
  8556. * tile.height = size.y;
  8557. *
  8558. * // draw something asynchronously and pass the tile to the done() callback
  8559. * setTimeout(function() {
  8560. * done(error, tile);
  8561. * }, 1000);
  8562. *
  8563. * return tile;
  8564. * }
  8565. * });
  8566. * ```
  8567. *
  8568. * @section
  8569. */
  8570. var GridLayer = Layer.extend({
  8571. // @section
  8572. // @aka GridLayer options
  8573. options: {
  8574. // @option tileSize: Number|Point = 256
  8575. // Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise.
  8576. tileSize: 256,
  8577. // @option opacity: Number = 1.0
  8578. // Opacity of the tiles. Can be used in the `createTile()` function.
  8579. opacity: 1,
  8580. // @option updateWhenIdle: Boolean = (depends)
  8581. // Load new tiles only when panning ends.
  8582. // `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation.
  8583. // `false` otherwise in order to display new tiles _during_ panning, since it is easy to pan outside the
  8584. // [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers.
  8585. updateWhenIdle: mobile,
  8586. // @option updateWhenZooming: Boolean = true
  8587. // 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.
  8588. updateWhenZooming: true,
  8589. // @option updateInterval: Number = 200
  8590. // Tiles will not update more than once every `updateInterval` milliseconds when panning.
  8591. updateInterval: 200,
  8592. // @option zIndex: Number = 1
  8593. // The explicit zIndex of the tile layer.
  8594. zIndex: 1,
  8595. // @option bounds: LatLngBounds = undefined
  8596. // If set, tiles will only be loaded inside the set `LatLngBounds`.
  8597. bounds: null,
  8598. // @option minZoom: Number = 0
  8599. // The minimum zoom level down to which this layer will be displayed (inclusive).
  8600. minZoom: 0,
  8601. // @option maxZoom: Number = undefined
  8602. // The maximum zoom level up to which this layer will be displayed (inclusive).
  8603. maxZoom: undefined,
  8604. // @option maxNativeZoom: Number = undefined
  8605. // Maximum zoom number the tile source has available. If it is specified,
  8606. // the tiles on all zoom levels higher than `maxNativeZoom` will be loaded
  8607. // from `maxNativeZoom` level and auto-scaled.
  8608. maxNativeZoom: undefined,
  8609. // @option minNativeZoom: Number = undefined
  8610. // Minimum zoom number the tile source has available. If it is specified,
  8611. // the tiles on all zoom levels lower than `minNativeZoom` will be loaded
  8612. // from `minNativeZoom` level and auto-scaled.
  8613. minNativeZoom: undefined,
  8614. // @option noWrap: Boolean = false
  8615. // Whether the layer is wrapped around the antimeridian. If `true`, the
  8616. // GridLayer will only be displayed once at low zoom levels. Has no
  8617. // effect when the [map CRS](#map-crs) doesn't wrap around. Can be used
  8618. // in combination with [`bounds`](#gridlayer-bounds) to prevent requesting
  8619. // tiles outside the CRS limits.
  8620. noWrap: false,
  8621. // @option pane: String = 'tilePane'
  8622. // `Map pane` where the grid layer will be added.
  8623. pane: 'tilePane',
  8624. // @option className: String = ''
  8625. // A custom class name to assign to the tile layer. Empty by default.
  8626. className: '',
  8627. // @option keepBuffer: Number = 2
  8628. // When panning the map, keep this many rows and columns of tiles before unloading them.
  8629. keepBuffer: 2
  8630. },
  8631. initialize: function (options) {
  8632. setOptions(this, options);
  8633. },
  8634. onAdd: function () {
  8635. this._initContainer();
  8636. this._levels = {};
  8637. this._tiles = {};
  8638. this._resetView();
  8639. this._update();
  8640. },
  8641. beforeAdd: function (map) {
  8642. map._addZoomLimit(this);
  8643. },
  8644. onRemove: function (map) {
  8645. this._removeAllTiles();
  8646. remove(this._container);
  8647. map._removeZoomLimit(this);
  8648. this._container = null;
  8649. this._tileZoom = undefined;
  8650. },
  8651. // @method bringToFront: this
  8652. // Brings the tile layer to the top of all tile layers.
  8653. bringToFront: function () {
  8654. if (this._map) {
  8655. toFront(this._container);
  8656. this._setAutoZIndex(Math.max);
  8657. }
  8658. return this;
  8659. },
  8660. // @method bringToBack: this
  8661. // Brings the tile layer to the bottom of all tile layers.
  8662. bringToBack: function () {
  8663. if (this._map) {
  8664. toBack(this._container);
  8665. this._setAutoZIndex(Math.min);
  8666. }
  8667. return this;
  8668. },
  8669. // @method getContainer: HTMLElement
  8670. // Returns the HTML element that contains the tiles for this layer.
  8671. getContainer: function () {
  8672. return this._container;
  8673. },
  8674. // @method setOpacity(opacity: Number): this
  8675. // Changes the [opacity](#gridlayer-opacity) of the grid layer.
  8676. setOpacity: function (opacity) {
  8677. this.options.opacity = opacity;
  8678. this._updateOpacity();
  8679. return this;
  8680. },
  8681. // @method setZIndex(zIndex: Number): this
  8682. // Changes the [zIndex](#gridlayer-zindex) of the grid layer.
  8683. setZIndex: function (zIndex) {
  8684. this.options.zIndex = zIndex;
  8685. this._updateZIndex();
  8686. return this;
  8687. },
  8688. // @method isLoading: Boolean
  8689. // Returns `true` if any tile in the grid layer has not finished loading.
  8690. isLoading: function () {
  8691. return this._loading;
  8692. },
  8693. // @method redraw: this
  8694. // Causes the layer to clear all the tiles and request them again.
  8695. redraw: function () {
  8696. if (this._map) {
  8697. this._removeAllTiles();
  8698. this._update();
  8699. }
  8700. return this;
  8701. },
  8702. getEvents: function () {
  8703. var events = {
  8704. viewprereset: this._invalidateAll,
  8705. viewreset: this._resetView,
  8706. zoom: this._resetView,
  8707. moveend: this._onMoveEnd
  8708. };
  8709. if (!this.options.updateWhenIdle) {
  8710. // update tiles on move, but not more often than once per given interval
  8711. if (!this._onMove) {
  8712. this._onMove = throttle(this._onMoveEnd, this.options.updateInterval, this);
  8713. }
  8714. events.move = this._onMove;
  8715. }
  8716. if (this._zoomAnimated) {
  8717. events.zoomanim = this._animateZoom;
  8718. }
  8719. return events;
  8720. },
  8721. // @section Extension methods
  8722. // Layers extending `GridLayer` shall reimplement the following method.
  8723. // @method createTile(coords: Object, done?: Function): HTMLElement
  8724. // Called only internally, must be overridden by classes extending `GridLayer`.
  8725. // Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback
  8726. // is specified, it must be called when the tile has finished loading and drawing.
  8727. createTile: function () {
  8728. return document.createElement('div');
  8729. },
  8730. // @section
  8731. // @method getTileSize: Point
  8732. // Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method.
  8733. getTileSize: function () {
  8734. var s = this.options.tileSize;
  8735. return s instanceof Point ? s : new Point(s, s);
  8736. },
  8737. _updateZIndex: function () {
  8738. if (this._container && this.options.zIndex !== undefined && this.options.zIndex !== null) {
  8739. this._container.style.zIndex = this.options.zIndex;
  8740. }
  8741. },
  8742. _setAutoZIndex: function (compare) {
  8743. // go through all other layers of the same pane, set zIndex to max + 1 (front) or min - 1 (back)
  8744. var layers = this.getPane().children,
  8745. edgeZIndex = -compare(-Infinity, Infinity); // -Infinity for max, Infinity for min
  8746. for (var i = 0, len = layers.length, zIndex; i < len; i++) {
  8747. zIndex = layers[i].style.zIndex;
  8748. if (layers[i] !== this._container && zIndex) {
  8749. edgeZIndex = compare(edgeZIndex, +zIndex);
  8750. }
  8751. }
  8752. if (isFinite(edgeZIndex)) {
  8753. this.options.zIndex = edgeZIndex + compare(-1, 1);
  8754. this._updateZIndex();
  8755. }
  8756. },
  8757. _updateOpacity: function () {
  8758. if (!this._map) { return; }
  8759. // IE doesn't inherit filter opacity properly, so we're forced to set it on tiles
  8760. if (ielt9) { return; }
  8761. setOpacity(this._container, this.options.opacity);
  8762. var now = +new Date(),
  8763. nextFrame = false,
  8764. willPrune = false;
  8765. for (var key in this._tiles) {
  8766. var tile = this._tiles[key];
  8767. if (!tile.current || !tile.loaded) { continue; }
  8768. var fade = Math.min(1, (now - tile.loaded) / 200);
  8769. setOpacity(tile.el, fade);
  8770. if (fade < 1) {
  8771. nextFrame = true;
  8772. } else {
  8773. if (tile.active) {
  8774. willPrune = true;
  8775. } else {
  8776. this._onOpaqueTile(tile);
  8777. }
  8778. tile.active = true;
  8779. }
  8780. }
  8781. if (willPrune && !this._noPrune) { this._pruneTiles(); }
  8782. if (nextFrame) {
  8783. cancelAnimFrame(this._fadeFrame);
  8784. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  8785. }
  8786. },
  8787. _onOpaqueTile: falseFn,
  8788. _initContainer: function () {
  8789. if (this._container) { return; }
  8790. this._container = create$1('div', 'leaflet-layer ' + (this.options.className || ''));
  8791. this._updateZIndex();
  8792. if (this.options.opacity < 1) {
  8793. this._updateOpacity();
  8794. }
  8795. this.getPane().appendChild(this._container);
  8796. },
  8797. _updateLevels: function () {
  8798. var zoom = this._tileZoom,
  8799. maxZoom = this.options.maxZoom;
  8800. if (zoom === undefined) { return undefined; }
  8801. for (var z in this._levels) {
  8802. if (this._levels[z].el.children.length || z === zoom) {
  8803. this._levels[z].el.style.zIndex = maxZoom - Math.abs(zoom - z);
  8804. this._onUpdateLevel(z);
  8805. } else {
  8806. remove(this._levels[z].el);
  8807. this._removeTilesAtZoom(z);
  8808. this._onRemoveLevel(z);
  8809. delete this._levels[z];
  8810. }
  8811. }
  8812. var level = this._levels[zoom],
  8813. map = this._map;
  8814. if (!level) {
  8815. level = this._levels[zoom] = {};
  8816. level.el = create$1('div', 'leaflet-tile-container leaflet-zoom-animated', this._container);
  8817. level.el.style.zIndex = maxZoom;
  8818. level.origin = map.project(map.unproject(map.getPixelOrigin()), zoom).round();
  8819. level.zoom = zoom;
  8820. this._setZoomTransform(level, map.getCenter(), map.getZoom());
  8821. // force the browser to consider the newly added element for transition
  8822. falseFn(level.el.offsetWidth);
  8823. this._onCreateLevel(level);
  8824. }
  8825. this._level = level;
  8826. return level;
  8827. },
  8828. _onUpdateLevel: falseFn,
  8829. _onRemoveLevel: falseFn,
  8830. _onCreateLevel: falseFn,
  8831. _pruneTiles: function () {
  8832. if (!this._map) {
  8833. return;
  8834. }
  8835. var key, tile;
  8836. var zoom = this._map.getZoom();
  8837. if (zoom > this.options.maxZoom ||
  8838. zoom < this.options.minZoom) {
  8839. this._removeAllTiles();
  8840. return;
  8841. }
  8842. for (key in this._tiles) {
  8843. tile = this._tiles[key];
  8844. tile.retain = tile.current;
  8845. }
  8846. for (key in this._tiles) {
  8847. tile = this._tiles[key];
  8848. if (tile.current && !tile.active) {
  8849. var coords = tile.coords;
  8850. if (!this._retainParent(coords.x, coords.y, coords.z, coords.z - 5)) {
  8851. this._retainChildren(coords.x, coords.y, coords.z, coords.z + 2);
  8852. }
  8853. }
  8854. }
  8855. for (key in this._tiles) {
  8856. if (!this._tiles[key].retain) {
  8857. this._removeTile(key);
  8858. }
  8859. }
  8860. },
  8861. _removeTilesAtZoom: function (zoom) {
  8862. for (var key in this._tiles) {
  8863. if (this._tiles[key].coords.z !== zoom) {
  8864. continue;
  8865. }
  8866. this._removeTile(key);
  8867. }
  8868. },
  8869. _removeAllTiles: function () {
  8870. for (var key in this._tiles) {
  8871. this._removeTile(key);
  8872. }
  8873. },
  8874. _invalidateAll: function () {
  8875. for (var z in this._levels) {
  8876. remove(this._levels[z].el);
  8877. this._onRemoveLevel(z);
  8878. delete this._levels[z];
  8879. }
  8880. this._removeAllTiles();
  8881. this._tileZoom = undefined;
  8882. },
  8883. _retainParent: function (x, y, z, minZoom) {
  8884. var x2 = Math.floor(x / 2),
  8885. y2 = Math.floor(y / 2),
  8886. z2 = z - 1,
  8887. coords2 = new Point(+x2, +y2);
  8888. coords2.z = +z2;
  8889. var key = this._tileCoordsToKey(coords2),
  8890. tile = this._tiles[key];
  8891. if (tile && tile.active) {
  8892. tile.retain = true;
  8893. return true;
  8894. } else if (tile && tile.loaded) {
  8895. tile.retain = true;
  8896. }
  8897. if (z2 > minZoom) {
  8898. return this._retainParent(x2, y2, z2, minZoom);
  8899. }
  8900. return false;
  8901. },
  8902. _retainChildren: function (x, y, z, maxZoom) {
  8903. for (var i = 2 * x; i < 2 * x + 2; i++) {
  8904. for (var j = 2 * y; j < 2 * y + 2; j++) {
  8905. var coords = new Point(i, j);
  8906. coords.z = z + 1;
  8907. var key = this._tileCoordsToKey(coords),
  8908. tile = this._tiles[key];
  8909. if (tile && tile.active) {
  8910. tile.retain = true;
  8911. continue;
  8912. } else if (tile && tile.loaded) {
  8913. tile.retain = true;
  8914. }
  8915. if (z + 1 < maxZoom) {
  8916. this._retainChildren(i, j, z + 1, maxZoom);
  8917. }
  8918. }
  8919. }
  8920. },
  8921. _resetView: function (e) {
  8922. var animating = e && (e.pinch || e.flyTo);
  8923. this._setView(this._map.getCenter(), this._map.getZoom(), animating, animating);
  8924. },
  8925. _animateZoom: function (e) {
  8926. this._setView(e.center, e.zoom, true, e.noUpdate);
  8927. },
  8928. _clampZoom: function (zoom) {
  8929. var options = this.options;
  8930. if (undefined !== options.minNativeZoom && zoom < options.minNativeZoom) {
  8931. return options.minNativeZoom;
  8932. }
  8933. if (undefined !== options.maxNativeZoom && options.maxNativeZoom < zoom) {
  8934. return options.maxNativeZoom;
  8935. }
  8936. return zoom;
  8937. },
  8938. _setView: function (center, zoom, noPrune, noUpdate) {
  8939. var tileZoom = this._clampZoom(Math.round(zoom));
  8940. if ((this.options.maxZoom !== undefined && tileZoom > this.options.maxZoom) ||
  8941. (this.options.minZoom !== undefined && tileZoom < this.options.minZoom)) {
  8942. tileZoom = undefined;
  8943. }
  8944. var tileZoomChanged = this.options.updateWhenZooming && (tileZoom !== this._tileZoom);
  8945. if (!noUpdate || tileZoomChanged) {
  8946. this._tileZoom = tileZoom;
  8947. if (this._abortLoading) {
  8948. this._abortLoading();
  8949. }
  8950. this._updateLevels();
  8951. this._resetGrid();
  8952. if (tileZoom !== undefined) {
  8953. this._update(center);
  8954. }
  8955. if (!noPrune) {
  8956. this._pruneTiles();
  8957. }
  8958. // Flag to prevent _updateOpacity from pruning tiles during
  8959. // a zoom anim or a pinch gesture
  8960. this._noPrune = !!noPrune;
  8961. }
  8962. this._setZoomTransforms(center, zoom);
  8963. },
  8964. _setZoomTransforms: function (center, zoom) {
  8965. for (var i in this._levels) {
  8966. this._setZoomTransform(this._levels[i], center, zoom);
  8967. }
  8968. },
  8969. _setZoomTransform: function (level, center, zoom) {
  8970. var scale = this._map.getZoomScale(zoom, level.zoom),
  8971. translate = level.origin.multiplyBy(scale)
  8972. .subtract(this._map._getNewPixelOrigin(center, zoom)).round();
  8973. if (any3d) {
  8974. setTransform(level.el, translate, scale);
  8975. } else {
  8976. setPosition(level.el, translate);
  8977. }
  8978. },
  8979. _resetGrid: function () {
  8980. var map = this._map,
  8981. crs = map.options.crs,
  8982. tileSize = this._tileSize = this.getTileSize(),
  8983. tileZoom = this._tileZoom;
  8984. var bounds = this._map.getPixelWorldBounds(this._tileZoom);
  8985. if (bounds) {
  8986. this._globalTileRange = this._pxBoundsToTileRange(bounds);
  8987. }
  8988. this._wrapX = crs.wrapLng && !this.options.noWrap && [
  8989. Math.floor(map.project([0, crs.wrapLng[0]], tileZoom).x / tileSize.x),
  8990. Math.ceil(map.project([0, crs.wrapLng[1]], tileZoom).x / tileSize.y)
  8991. ];
  8992. this._wrapY = crs.wrapLat && !this.options.noWrap && [
  8993. Math.floor(map.project([crs.wrapLat[0], 0], tileZoom).y / tileSize.x),
  8994. Math.ceil(map.project([crs.wrapLat[1], 0], tileZoom).y / tileSize.y)
  8995. ];
  8996. },
  8997. _onMoveEnd: function () {
  8998. if (!this._map || this._map._animatingZoom) { return; }
  8999. this._update();
  9000. },
  9001. _getTiledPixelBounds: function (center) {
  9002. var map = this._map,
  9003. mapZoom = map._animatingZoom ? Math.max(map._animateToZoom, map.getZoom()) : map.getZoom(),
  9004. scale = map.getZoomScale(mapZoom, this._tileZoom),
  9005. pixelCenter = map.project(center, this._tileZoom).floor(),
  9006. halfSize = map.getSize().divideBy(scale * 2);
  9007. return new Bounds(pixelCenter.subtract(halfSize), pixelCenter.add(halfSize));
  9008. },
  9009. // Private method to load tiles in the grid's active zoom level according to map bounds
  9010. _update: function (center) {
  9011. var map = this._map;
  9012. if (!map) { return; }
  9013. var zoom = this._clampZoom(map.getZoom());
  9014. if (center === undefined) { center = map.getCenter(); }
  9015. if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom
  9016. var pixelBounds = this._getTiledPixelBounds(center),
  9017. tileRange = this._pxBoundsToTileRange(pixelBounds),
  9018. tileCenter = tileRange.getCenter(),
  9019. queue = [],
  9020. margin = this.options.keepBuffer,
  9021. noPruneRange = new Bounds(tileRange.getBottomLeft().subtract([margin, -margin]),
  9022. tileRange.getTopRight().add([margin, -margin]));
  9023. // Sanity check: panic if the tile range contains Infinity somewhere.
  9024. if (!(isFinite(tileRange.min.x) &&
  9025. isFinite(tileRange.min.y) &&
  9026. isFinite(tileRange.max.x) &&
  9027. isFinite(tileRange.max.y))) { throw new Error('Attempted to load an infinite number of tiles'); }
  9028. for (var key in this._tiles) {
  9029. var c = this._tiles[key].coords;
  9030. if (c.z !== this._tileZoom || !noPruneRange.contains(new Point(c.x, c.y))) {
  9031. this._tiles[key].current = false;
  9032. }
  9033. }
  9034. // _update just loads more tiles. If the tile zoom level differs too much
  9035. // from the map's, let _setView reset levels and prune old tiles.
  9036. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; }
  9037. // create a queue of coordinates to load tiles from
  9038. for (var j = tileRange.min.y; j <= tileRange.max.y; j++) {
  9039. for (var i = tileRange.min.x; i <= tileRange.max.x; i++) {
  9040. var coords = new Point(i, j);
  9041. coords.z = this._tileZoom;
  9042. if (!this._isValidTile(coords)) { continue; }
  9043. var tile = this._tiles[this._tileCoordsToKey(coords)];
  9044. if (tile) {
  9045. tile.current = true;
  9046. } else {
  9047. queue.push(coords);
  9048. }
  9049. }
  9050. }
  9051. // sort tile queue to load tiles in order of their distance to center
  9052. queue.sort(function (a, b) {
  9053. return a.distanceTo(tileCenter) - b.distanceTo(tileCenter);
  9054. });
  9055. if (queue.length !== 0) {
  9056. // if it's the first batch of tiles to load
  9057. if (!this._loading) {
  9058. this._loading = true;
  9059. // @event loading: Event
  9060. // Fired when the grid layer starts loading tiles.
  9061. this.fire('loading');
  9062. }
  9063. // create DOM fragment to append tiles in one batch
  9064. var fragment = document.createDocumentFragment();
  9065. for (i = 0; i < queue.length; i++) {
  9066. this._addTile(queue[i], fragment);
  9067. }
  9068. this._level.el.appendChild(fragment);
  9069. }
  9070. },
  9071. _isValidTile: function (coords) {
  9072. var crs = this._map.options.crs;
  9073. if (!crs.infinite) {
  9074. // don't load tile if it's out of bounds and not wrapped
  9075. var bounds = this._globalTileRange;
  9076. if ((!crs.wrapLng && (coords.x < bounds.min.x || coords.x > bounds.max.x)) ||
  9077. (!crs.wrapLat && (coords.y < bounds.min.y || coords.y > bounds.max.y))) { return false; }
  9078. }
  9079. if (!this.options.bounds) { return true; }
  9080. // don't load tile if it doesn't intersect the bounds in options
  9081. var tileBounds = this._tileCoordsToBounds(coords);
  9082. return toLatLngBounds(this.options.bounds).overlaps(tileBounds);
  9083. },
  9084. _keyToBounds: function (key) {
  9085. return this._tileCoordsToBounds(this._keyToTileCoords(key));
  9086. },
  9087. _tileCoordsToNwSe: function (coords) {
  9088. var map = this._map,
  9089. tileSize = this.getTileSize(),
  9090. nwPoint = coords.scaleBy(tileSize),
  9091. sePoint = nwPoint.add(tileSize),
  9092. nw = map.unproject(nwPoint, coords.z),
  9093. se = map.unproject(sePoint, coords.z);
  9094. return [nw, se];
  9095. },
  9096. // converts tile coordinates to its geographical bounds
  9097. _tileCoordsToBounds: function (coords) {
  9098. var bp = this._tileCoordsToNwSe(coords),
  9099. bounds = new LatLngBounds(bp[0], bp[1]);
  9100. if (!this.options.noWrap) {
  9101. bounds = this._map.wrapLatLngBounds(bounds);
  9102. }
  9103. return bounds;
  9104. },
  9105. // converts tile coordinates to key for the tile cache
  9106. _tileCoordsToKey: function (coords) {
  9107. return coords.x + ':' + coords.y + ':' + coords.z;
  9108. },
  9109. // converts tile cache key to coordinates
  9110. _keyToTileCoords: function (key) {
  9111. var k = key.split(':'),
  9112. coords = new Point(+k[0], +k[1]);
  9113. coords.z = +k[2];
  9114. return coords;
  9115. },
  9116. _removeTile: function (key) {
  9117. var tile = this._tiles[key];
  9118. if (!tile) { return; }
  9119. // Cancels any pending http requests associated with the tile
  9120. // unless we're on Android's stock browser,
  9121. // see https://github.com/Leaflet/Leaflet/issues/137
  9122. if (!androidStock) {
  9123. tile.el.setAttribute('src', emptyImageUrl);
  9124. }
  9125. remove(tile.el);
  9126. delete this._tiles[key];
  9127. // @event tileunload: TileEvent
  9128. // Fired when a tile is removed (e.g. when a tile goes off the screen).
  9129. this.fire('tileunload', {
  9130. tile: tile.el,
  9131. coords: this._keyToTileCoords(key)
  9132. });
  9133. },
  9134. _initTile: function (tile) {
  9135. addClass(tile, 'leaflet-tile');
  9136. var tileSize = this.getTileSize();
  9137. tile.style.width = tileSize.x + 'px';
  9138. tile.style.height = tileSize.y + 'px';
  9139. tile.onselectstart = falseFn;
  9140. tile.onmousemove = falseFn;
  9141. // update opacity on tiles in IE7-8 because of filter inheritance problems
  9142. if (ielt9 && this.options.opacity < 1) {
  9143. setOpacity(tile, this.options.opacity);
  9144. }
  9145. // without this hack, tiles disappear after zoom on Chrome for Android
  9146. // https://github.com/Leaflet/Leaflet/issues/2078
  9147. if (android && !android23) {
  9148. tile.style.WebkitBackfaceVisibility = 'hidden';
  9149. }
  9150. },
  9151. _addTile: function (coords, container) {
  9152. var tilePos = this._getTilePos(coords),
  9153. key = this._tileCoordsToKey(coords);
  9154. var tile = this.createTile(this._wrapCoords(coords), bind(this._tileReady, this, coords));
  9155. this._initTile(tile);
  9156. // if createTile is defined with a second argument ("done" callback),
  9157. // we know that tile is async and will be ready later; otherwise
  9158. if (this.createTile.length < 2) {
  9159. // mark tile as ready, but delay one frame for opacity animation to happen
  9160. requestAnimFrame(bind(this._tileReady, this, coords, null, tile));
  9161. }
  9162. setPosition(tile, tilePos);
  9163. // save tile in cache
  9164. this._tiles[key] = {
  9165. el: tile,
  9166. coords: coords,
  9167. current: true
  9168. };
  9169. container.appendChild(tile);
  9170. // @event tileloadstart: TileEvent
  9171. // Fired when a tile is requested and starts loading.
  9172. this.fire('tileloadstart', {
  9173. tile: tile,
  9174. coords: coords
  9175. });
  9176. },
  9177. _tileReady: function (coords, err, tile) {
  9178. if (!this._map) { return; }
  9179. if (err) {
  9180. // @event tileerror: TileErrorEvent
  9181. // Fired when there is an error loading a tile.
  9182. this.fire('tileerror', {
  9183. error: err,
  9184. tile: tile,
  9185. coords: coords
  9186. });
  9187. }
  9188. var key = this._tileCoordsToKey(coords);
  9189. tile = this._tiles[key];
  9190. if (!tile) { return; }
  9191. tile.loaded = +new Date();
  9192. if (this._map._fadeAnimated) {
  9193. setOpacity(tile.el, 0);
  9194. cancelAnimFrame(this._fadeFrame);
  9195. this._fadeFrame = requestAnimFrame(this._updateOpacity, this);
  9196. } else {
  9197. tile.active = true;
  9198. this._pruneTiles();
  9199. }
  9200. if (!err) {
  9201. addClass(tile.el, 'leaflet-tile-loaded');
  9202. // @event tileload: TileEvent
  9203. // Fired when a tile loads.
  9204. this.fire('tileload', {
  9205. tile: tile.el,
  9206. coords: coords
  9207. });
  9208. }
  9209. if (this._noTilesToLoad()) {
  9210. this._loading = false;
  9211. // @event load: Event
  9212. // Fired when the grid layer loaded all visible tiles.
  9213. this.fire('load');
  9214. if (ielt9 || !this._map._fadeAnimated) {
  9215. requestAnimFrame(this._pruneTiles, this);
  9216. } else {
  9217. // Wait a bit more than 0.2 secs (the duration of the tile fade-in)
  9218. // to trigger a pruning.
  9219. setTimeout(bind(this._pruneTiles, this), 250);
  9220. }
  9221. }
  9222. },
  9223. _getTilePos: function (coords) {
  9224. return coords.scaleBy(this.getTileSize()).subtract(this._level.origin);
  9225. },
  9226. _wrapCoords: function (coords) {
  9227. var newCoords = new Point(
  9228. this._wrapX ? wrapNum(coords.x, this._wrapX) : coords.x,
  9229. this._wrapY ? wrapNum(coords.y, this._wrapY) : coords.y);
  9230. newCoords.z = coords.z;
  9231. return newCoords;
  9232. },
  9233. _pxBoundsToTileRange: function (bounds) {
  9234. var tileSize = this.getTileSize();
  9235. return new Bounds(
  9236. bounds.min.unscaleBy(tileSize).floor(),
  9237. bounds.max.unscaleBy(tileSize).ceil().subtract([1, 1]));
  9238. },
  9239. _noTilesToLoad: function () {
  9240. for (var key in this._tiles) {
  9241. if (!this._tiles[key].loaded) { return false; }
  9242. }
  9243. return true;
  9244. }
  9245. });
  9246. // @factory L.gridLayer(options?: GridLayer options)
  9247. // Creates a new instance of GridLayer with the supplied options.
  9248. function gridLayer(options) {
  9249. return new GridLayer(options);
  9250. }
  9251. /*
  9252. * @class TileLayer
  9253. * @inherits GridLayer
  9254. * @aka L.TileLayer
  9255. * Used to load and display tile layers on the map. Extends `GridLayer`.
  9256. *
  9257. * @example
  9258. *
  9259. * ```js
  9260. * L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
  9261. * ```
  9262. *
  9263. * @section URL template
  9264. * @example
  9265. *
  9266. * A string of the following form:
  9267. *
  9268. * ```
  9269. * 'http://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'
  9270. * ```
  9271. *
  9272. * `{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.
  9273. *
  9274. * You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this:
  9275. *
  9276. * ```
  9277. * L.tileLayer('http://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});
  9278. * ```
  9279. */
  9280. var TileLayer = GridLayer.extend({
  9281. // @section
  9282. // @aka TileLayer options
  9283. options: {
  9284. // @option minZoom: Number = 0
  9285. // The minimum zoom level down to which this layer will be displayed (inclusive).
  9286. minZoom: 0,
  9287. // @option maxZoom: Number = 18
  9288. // The maximum zoom level up to which this layer will be displayed (inclusive).
  9289. maxZoom: 18,
  9290. // @option subdomains: String|String[] = 'abc'
  9291. // 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.
  9292. subdomains: 'abc',
  9293. // @option errorTileUrl: String = ''
  9294. // URL to the tile image to show in place of the tile that failed to load.
  9295. errorTileUrl: '',
  9296. // @option zoomOffset: Number = 0
  9297. // The zoom number used in tile URLs will be offset with this value.
  9298. zoomOffset: 0,
  9299. // @option tms: Boolean = false
  9300. // If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services).
  9301. tms: false,
  9302. // @option zoomReverse: Boolean = false
  9303. // If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`)
  9304. zoomReverse: false,
  9305. // @option detectRetina: Boolean = false
  9306. // 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.
  9307. detectRetina: false,
  9308. // @option crossOrigin: Boolean = false
  9309. // If true, all tiles will have their crossOrigin attribute set to ''. This is needed if you want to access tile pixel data.
  9310. crossOrigin: false
  9311. },
  9312. initialize: function (url, options) {
  9313. this._url = url;
  9314. options = setOptions(this, options);
  9315. // detecting retina displays, adjusting tileSize and zoom levels
  9316. if (options.detectRetina && retina && options.maxZoom > 0) {
  9317. options.tileSize = Math.floor(options.tileSize / 2);
  9318. if (!options.zoomReverse) {
  9319. options.zoomOffset++;
  9320. options.maxZoom--;
  9321. } else {
  9322. options.zoomOffset--;
  9323. options.minZoom++;
  9324. }
  9325. options.minZoom = Math.max(0, options.minZoom);
  9326. }
  9327. if (typeof options.subdomains === 'string') {
  9328. options.subdomains = options.subdomains.split('');
  9329. }
  9330. // for https://github.com/Leaflet/Leaflet/issues/137
  9331. if (!android) {
  9332. this.on('tileunload', this._onTileRemove);
  9333. }
  9334. },
  9335. // @method setUrl(url: String, noRedraw?: Boolean): this
  9336. // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`).
  9337. setUrl: function (url, noRedraw) {
  9338. this._url = url;
  9339. if (!noRedraw) {
  9340. this.redraw();
  9341. }
  9342. return this;
  9343. },
  9344. // @method createTile(coords: Object, done?: Function): HTMLElement
  9345. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  9346. // to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done`
  9347. // callback is called when the tile has been loaded.
  9348. createTile: function (coords, done) {
  9349. var tile = document.createElement('img');
  9350. on(tile, 'load', bind(this._tileOnLoad, this, done, tile));
  9351. on(tile, 'error', bind(this._tileOnError, this, done, tile));
  9352. if (this.options.crossOrigin) {
  9353. tile.crossOrigin = '';
  9354. }
  9355. /*
  9356. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  9357. http://www.w3.org/TR/WCAG20-TECHS/H67
  9358. */
  9359. tile.alt = '';
  9360. /*
  9361. Set role="presentation" to force screen readers to ignore this
  9362. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  9363. */
  9364. tile.setAttribute('role', 'presentation');
  9365. tile.src = this.getTileUrl(coords);
  9366. return tile;
  9367. },
  9368. // @section Extension methods
  9369. // @uninheritable
  9370. // Layers extending `TileLayer` might reimplement the following method.
  9371. // @method getTileUrl(coords: Object): String
  9372. // Called only internally, returns the URL for a tile given its coordinates.
  9373. // Classes extending `TileLayer` can override this function to provide custom tile URL naming schemes.
  9374. getTileUrl: function (coords) {
  9375. var data = {
  9376. r: retina ? '@2x' : '',
  9377. s: this._getSubdomain(coords),
  9378. x: coords.x,
  9379. y: coords.y,
  9380. z: this._getZoomForUrl()
  9381. };
  9382. if (this._map && !this._map.options.crs.infinite) {
  9383. var invertedY = this._globalTileRange.max.y - coords.y;
  9384. if (this.options.tms) {
  9385. data['y'] = invertedY;
  9386. }
  9387. data['-y'] = invertedY;
  9388. }
  9389. return template(this._url, extend(data, this.options));
  9390. },
  9391. _tileOnLoad: function (done, tile) {
  9392. // For https://github.com/Leaflet/Leaflet/issues/3332
  9393. if (ielt9) {
  9394. setTimeout(bind(done, this, null, tile), 0);
  9395. } else {
  9396. done(null, tile);
  9397. }
  9398. },
  9399. _tileOnError: function (done, tile, e) {
  9400. var errorUrl = this.options.errorTileUrl;
  9401. if (errorUrl && tile.getAttribute('src') !== errorUrl) {
  9402. tile.src = errorUrl;
  9403. }
  9404. done(e, tile);
  9405. },
  9406. _onTileRemove: function (e) {
  9407. e.tile.onload = null;
  9408. },
  9409. _getZoomForUrl: function () {
  9410. var zoom = this._tileZoom,
  9411. maxZoom = this.options.maxZoom,
  9412. zoomReverse = this.options.zoomReverse,
  9413. zoomOffset = this.options.zoomOffset;
  9414. if (zoomReverse) {
  9415. zoom = maxZoom - zoom;
  9416. }
  9417. return zoom + zoomOffset;
  9418. },
  9419. _getSubdomain: function (tilePoint) {
  9420. var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
  9421. return this.options.subdomains[index];
  9422. },
  9423. // stops loading all tiles in the background layer
  9424. _abortLoading: function () {
  9425. var i, tile;
  9426. for (i in this._tiles) {
  9427. if (this._tiles[i].coords.z !== this._tileZoom) {
  9428. tile = this._tiles[i].el;
  9429. tile.onload = falseFn;
  9430. tile.onerror = falseFn;
  9431. if (!tile.complete) {
  9432. tile.src = emptyImageUrl;
  9433. remove(tile);
  9434. delete this._tiles[i];
  9435. }
  9436. }
  9437. }
  9438. }
  9439. });
  9440. // @factory L.tilelayer(urlTemplate: String, options?: TileLayer options)
  9441. // Instantiates a tile layer object given a `URL template` and optionally an options object.
  9442. function tileLayer(url, options) {
  9443. return new TileLayer(url, options);
  9444. }
  9445. /*
  9446. * @class TileLayer.WMS
  9447. * @inherits TileLayer
  9448. * @aka L.TileLayer.WMS
  9449. * Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends `TileLayer`.
  9450. *
  9451. * @example
  9452. *
  9453. * ```js
  9454. * var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
  9455. * layers: 'nexrad-n0r-900913',
  9456. * format: 'image/png',
  9457. * transparent: true,
  9458. * attribution: "Weather data © 2012 IEM Nexrad"
  9459. * });
  9460. * ```
  9461. */
  9462. var TileLayerWMS = TileLayer.extend({
  9463. // @section
  9464. // @aka TileLayer.WMS options
  9465. // If any custom options not documented here are used, they will be sent to the
  9466. // WMS server as extra parameters in each request URL. This can be useful for
  9467. // [non-standard vendor WMS parameters](http://docs.geoserver.org/stable/en/user/services/wms/vendor.html).
  9468. defaultWmsParams: {
  9469. service: 'WMS',
  9470. request: 'GetMap',
  9471. // @option layers: String = ''
  9472. // **(required)** Comma-separated list of WMS layers to show.
  9473. layers: '',
  9474. // @option styles: String = ''
  9475. // Comma-separated list of WMS styles.
  9476. styles: '',
  9477. // @option format: String = 'image/jpeg'
  9478. // WMS image format (use `'image/png'` for layers with transparency).
  9479. format: 'image/jpeg',
  9480. // @option transparent: Boolean = false
  9481. // If `true`, the WMS service will return images with transparency.
  9482. transparent: false,
  9483. // @option version: String = '1.1.1'
  9484. // Version of the WMS service to use
  9485. version: '1.1.1'
  9486. },
  9487. options: {
  9488. // @option crs: CRS = null
  9489. // Coordinate Reference System to use for the WMS requests, defaults to
  9490. // map CRS. Don't change this if you're not sure what it means.
  9491. crs: null,
  9492. // @option uppercase: Boolean = false
  9493. // If `true`, WMS request parameter keys will be uppercase.
  9494. uppercase: false
  9495. },
  9496. initialize: function (url, options) {
  9497. this._url = url;
  9498. var wmsParams = extend({}, this.defaultWmsParams);
  9499. // all keys that are not TileLayer options go to WMS params
  9500. for (var i in options) {
  9501. if (!(i in this.options)) {
  9502. wmsParams[i] = options[i];
  9503. }
  9504. }
  9505. options = setOptions(this, options);
  9506. var realRetina = options.detectRetina && retina ? 2 : 1;
  9507. var tileSize = this.getTileSize();
  9508. wmsParams.width = tileSize.x * realRetina;
  9509. wmsParams.height = tileSize.y * realRetina;
  9510. this.wmsParams = wmsParams;
  9511. },
  9512. onAdd: function (map) {
  9513. this._crs = this.options.crs || map.options.crs;
  9514. this._wmsVersion = parseFloat(this.wmsParams.version);
  9515. var projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
  9516. this.wmsParams[projectionKey] = this._crs.code;
  9517. TileLayer.prototype.onAdd.call(this, map);
  9518. },
  9519. getTileUrl: function (coords) {
  9520. var tileBounds = this._tileCoordsToNwSe(coords),
  9521. crs = this._crs,
  9522. bounds = toBounds(crs.project(tileBounds[0]), crs.project(tileBounds[1])),
  9523. min = bounds.min,
  9524. max = bounds.max,
  9525. bbox = (this._wmsVersion >= 1.3 && this._crs === EPSG4326 ?
  9526. [min.y, min.x, max.y, max.x] :
  9527. [min.x, min.y, max.x, max.y]).join(','),
  9528. url = L.TileLayer.prototype.getTileUrl.call(this, coords);
  9529. return url +
  9530. getParamString(this.wmsParams, url, this.options.uppercase) +
  9531. (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
  9532. },
  9533. // @method setParams(params: Object, noRedraw?: Boolean): this
  9534. // Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true).
  9535. setParams: function (params, noRedraw) {
  9536. extend(this.wmsParams, params);
  9537. if (!noRedraw) {
  9538. this.redraw();
  9539. }
  9540. return this;
  9541. }
  9542. });
  9543. // @factory L.tileLayer.wms(baseUrl: String, options: TileLayer.WMS options)
  9544. // Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.
  9545. function tileLayerWMS(url, options) {
  9546. return new TileLayerWMS(url, options);
  9547. }
  9548. TileLayer.WMS = TileLayerWMS;
  9549. tileLayer.wms = tileLayerWMS;
  9550. /*
  9551. * @class Renderer
  9552. * @inherits Layer
  9553. * @aka L.Renderer
  9554. *
  9555. * Base class for vector renderer implementations (`SVG`, `Canvas`). Handles the
  9556. * DOM container of the renderer, its bounds, and its zoom animation.
  9557. *
  9558. * A `Renderer` works as an implicit layer group for all `Path`s - the renderer
  9559. * itself can be added or removed to the map. All paths use a renderer, which can
  9560. * be implicit (the map will decide the type of renderer and use it automatically)
  9561. * or explicit (using the [`renderer`](#path-renderer) option of the path).
  9562. *
  9563. * Do not use this class directly, use `SVG` and `Canvas` instead.
  9564. *
  9565. * @event update: Event
  9566. * Fired when the renderer updates its bounds, center and zoom, for example when
  9567. * its map has moved
  9568. */
  9569. var Renderer = Layer.extend({
  9570. // @section
  9571. // @aka Renderer options
  9572. options: {
  9573. // @option padding: Number = 0.1
  9574. // How much to extend the clip area around the map view (relative to its size)
  9575. // e.g. 0.1 would be 10% of map view in each direction
  9576. padding: 0.1,
  9577. // @option tolerance: Number = 0
  9578. // How much to extend click tolerance round a path/object on the map
  9579. tolerance : 0
  9580. },
  9581. initialize: function (options) {
  9582. setOptions(this, options);
  9583. stamp(this);
  9584. this._layers = this._layers || {};
  9585. },
  9586. onAdd: function () {
  9587. if (!this._container) {
  9588. this._initContainer(); // defined by renderer implementations
  9589. if (this._zoomAnimated) {
  9590. addClass(this._container, 'leaflet-zoom-animated');
  9591. }
  9592. }
  9593. this.getPane().appendChild(this._container);
  9594. this._update();
  9595. this.on('update', this._updatePaths, this);
  9596. },
  9597. onRemove: function () {
  9598. this.off('update', this._updatePaths, this);
  9599. this._destroyContainer();
  9600. },
  9601. getEvents: function () {
  9602. var events = {
  9603. viewreset: this._reset,
  9604. zoom: this._onZoom,
  9605. moveend: this._update,
  9606. zoomend: this._onZoomEnd
  9607. };
  9608. if (this._zoomAnimated) {
  9609. events.zoomanim = this._onAnimZoom;
  9610. }
  9611. return events;
  9612. },
  9613. _onAnimZoom: function (ev) {
  9614. this._updateTransform(ev.center, ev.zoom);
  9615. },
  9616. _onZoom: function () {
  9617. this._updateTransform(this._map.getCenter(), this._map.getZoom());
  9618. },
  9619. _updateTransform: function (center, zoom) {
  9620. var scale = this._map.getZoomScale(zoom, this._zoom),
  9621. position = getPosition(this._container),
  9622. viewHalf = this._map.getSize().multiplyBy(0.5 + this.options.padding),
  9623. currentCenterPoint = this._map.project(this._center, zoom),
  9624. destCenterPoint = this._map.project(center, zoom),
  9625. centerOffset = destCenterPoint.subtract(currentCenterPoint),
  9626. topLeftOffset = viewHalf.multiplyBy(-scale).add(position).add(viewHalf).subtract(centerOffset);
  9627. if (any3d) {
  9628. setTransform(this._container, topLeftOffset, scale);
  9629. } else {
  9630. setPosition(this._container, topLeftOffset);
  9631. }
  9632. },
  9633. _reset: function () {
  9634. this._update();
  9635. this._updateTransform(this._center, this._zoom);
  9636. for (var id in this._layers) {
  9637. this._layers[id]._reset();
  9638. }
  9639. },
  9640. _onZoomEnd: function () {
  9641. for (var id in this._layers) {
  9642. this._layers[id]._project();
  9643. }
  9644. },
  9645. _updatePaths: function () {
  9646. for (var id in this._layers) {
  9647. this._layers[id]._update();
  9648. }
  9649. },
  9650. _update: function () {
  9651. // Update pixel bounds of renderer container (for positioning/sizing/clipping later)
  9652. // Subclasses are responsible of firing the 'update' event.
  9653. var p = this.options.padding,
  9654. size = this._map.getSize(),
  9655. min = this._map.containerPointToLayerPoint(size.multiplyBy(-p)).round();
  9656. this._bounds = new Bounds(min, min.add(size.multiplyBy(1 + p * 2)).round());
  9657. this._center = this._map.getCenter();
  9658. this._zoom = this._map.getZoom();
  9659. }
  9660. });
  9661. /*
  9662. * @class Canvas
  9663. * @inherits Renderer
  9664. * @aka L.Canvas
  9665. *
  9666. * Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API).
  9667. * Inherits `Renderer`.
  9668. *
  9669. * Due to [technical limitations](http://caniuse.com/#search=canvas), Canvas is not
  9670. * available in all web browsers, notably IE8, and overlapping geometries might
  9671. * not display properly in some edge cases.
  9672. *
  9673. * @example
  9674. *
  9675. * Use Canvas by default for all paths in the map:
  9676. *
  9677. * ```js
  9678. * var map = L.map('map', {
  9679. * renderer: L.canvas()
  9680. * });
  9681. * ```
  9682. *
  9683. * Use a Canvas renderer with extra padding for specific vector geometries:
  9684. *
  9685. * ```js
  9686. * var map = L.map('map');
  9687. * var myRenderer = L.canvas({ padding: 0.5 });
  9688. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  9689. * var circle = L.circle( center, { renderer: myRenderer } );
  9690. * ```
  9691. */
  9692. var Canvas = Renderer.extend({
  9693. getEvents: function () {
  9694. var events = Renderer.prototype.getEvents.call(this);
  9695. events.viewprereset = this._onViewPreReset;
  9696. return events;
  9697. },
  9698. _onViewPreReset: function () {
  9699. // Set a flag so that a viewprereset+moveend+viewreset only updates&redraws once
  9700. this._postponeUpdatePaths = true;
  9701. },
  9702. onAdd: function () {
  9703. Renderer.prototype.onAdd.call(this);
  9704. // Redraw vectors since canvas is cleared upon removal,
  9705. // in case of removing the renderer itself from the map.
  9706. this._draw();
  9707. },
  9708. _initContainer: function () {
  9709. var container = this._container = document.createElement('canvas');
  9710. on(container, 'mousemove', throttle(this._onMouseMove, 32, this), this);
  9711. on(container, 'click dblclick mousedown mouseup contextmenu', this._onClick, this);
  9712. on(container, 'mouseout', this._handleMouseOut, this);
  9713. this._ctx = container.getContext('2d');
  9714. },
  9715. _destroyContainer: function () {
  9716. delete this._ctx;
  9717. remove(this._container);
  9718. off(this._container);
  9719. delete this._container;
  9720. },
  9721. _updatePaths: function () {
  9722. if (this._postponeUpdatePaths) { return; }
  9723. var layer;
  9724. this._redrawBounds = null;
  9725. for (var id in this._layers) {
  9726. layer = this._layers[id];
  9727. layer._update();
  9728. }
  9729. this._redraw();
  9730. },
  9731. _update: function () {
  9732. if (this._map._animatingZoom && this._bounds) { return; }
  9733. this._drawnLayers = {};
  9734. Renderer.prototype._update.call(this);
  9735. var b = this._bounds,
  9736. container = this._container,
  9737. size = b.getSize(),
  9738. m = retina ? 2 : 1;
  9739. setPosition(container, b.min);
  9740. // set canvas size (also clearing it); use double size on retina
  9741. container.width = m * size.x;
  9742. container.height = m * size.y;
  9743. container.style.width = size.x + 'px';
  9744. container.style.height = size.y + 'px';
  9745. if (retina) {
  9746. this._ctx.scale(2, 2);
  9747. }
  9748. // translate so we use the same path coordinates after canvas element moves
  9749. this._ctx.translate(-b.min.x, -b.min.y);
  9750. // Tell paths to redraw themselves
  9751. this.fire('update');
  9752. },
  9753. _reset: function () {
  9754. Renderer.prototype._reset.call(this);
  9755. if (this._postponeUpdatePaths) {
  9756. this._postponeUpdatePaths = false;
  9757. this._updatePaths();
  9758. }
  9759. },
  9760. _initPath: function (layer) {
  9761. this._updateDashArray(layer);
  9762. this._layers[stamp(layer)] = layer;
  9763. var order = layer._order = {
  9764. layer: layer,
  9765. prev: this._drawLast,
  9766. next: null
  9767. };
  9768. if (this._drawLast) { this._drawLast.next = order; }
  9769. this._drawLast = order;
  9770. this._drawFirst = this._drawFirst || this._drawLast;
  9771. },
  9772. _addPath: function (layer) {
  9773. this._requestRedraw(layer);
  9774. },
  9775. _removePath: function (layer) {
  9776. var order = layer._order;
  9777. var next = order.next;
  9778. var prev = order.prev;
  9779. if (next) {
  9780. next.prev = prev;
  9781. } else {
  9782. this._drawLast = prev;
  9783. }
  9784. if (prev) {
  9785. prev.next = next;
  9786. } else {
  9787. this._drawFirst = next;
  9788. }
  9789. delete layer._order;
  9790. delete this._layers[L.stamp(layer)];
  9791. this._requestRedraw(layer);
  9792. },
  9793. _updatePath: function (layer) {
  9794. // Redraw the union of the layer's old pixel
  9795. // bounds and the new pixel bounds.
  9796. this._extendRedrawBounds(layer);
  9797. layer._project();
  9798. layer._update();
  9799. // The redraw will extend the redraw bounds
  9800. // with the new pixel bounds.
  9801. this._requestRedraw(layer);
  9802. },
  9803. _updateStyle: function (layer) {
  9804. this._updateDashArray(layer);
  9805. this._requestRedraw(layer);
  9806. },
  9807. _updateDashArray: function (layer) {
  9808. if (layer.options.dashArray) {
  9809. var parts = layer.options.dashArray.split(','),
  9810. dashArray = [],
  9811. i;
  9812. for (i = 0; i < parts.length; i++) {
  9813. dashArray.push(Number(parts[i]));
  9814. }
  9815. layer.options._dashArray = dashArray;
  9816. }
  9817. },
  9818. _requestRedraw: function (layer) {
  9819. if (!this._map) { return; }
  9820. this._extendRedrawBounds(layer);
  9821. this._redrawRequest = this._redrawRequest || requestAnimFrame(this._redraw, this);
  9822. },
  9823. _extendRedrawBounds: function (layer) {
  9824. if (layer._pxBounds) {
  9825. var padding = (layer.options.weight || 0) + 1;
  9826. this._redrawBounds = this._redrawBounds || new Bounds();
  9827. this._redrawBounds.extend(layer._pxBounds.min.subtract([padding, padding]));
  9828. this._redrawBounds.extend(layer._pxBounds.max.add([padding, padding]));
  9829. }
  9830. },
  9831. _redraw: function () {
  9832. this._redrawRequest = null;
  9833. if (this._redrawBounds) {
  9834. this._redrawBounds.min._floor();
  9835. this._redrawBounds.max._ceil();
  9836. }
  9837. this._clear(); // clear layers in redraw bounds
  9838. this._draw(); // draw layers
  9839. this._redrawBounds = null;
  9840. },
  9841. _clear: function () {
  9842. var bounds = this._redrawBounds;
  9843. if (bounds) {
  9844. var size = bounds.getSize();
  9845. this._ctx.clearRect(bounds.min.x, bounds.min.y, size.x, size.y);
  9846. } else {
  9847. this._ctx.clearRect(0, 0, this._container.width, this._container.height);
  9848. }
  9849. },
  9850. _draw: function () {
  9851. var layer, bounds = this._redrawBounds;
  9852. this._ctx.save();
  9853. if (bounds) {
  9854. var size = bounds.getSize();
  9855. this._ctx.beginPath();
  9856. this._ctx.rect(bounds.min.x, bounds.min.y, size.x, size.y);
  9857. this._ctx.clip();
  9858. }
  9859. this._drawing = true;
  9860. for (var order = this._drawFirst; order; order = order.next) {
  9861. layer = order.layer;
  9862. if (!bounds || (layer._pxBounds && layer._pxBounds.intersects(bounds))) {
  9863. layer._updatePath();
  9864. }
  9865. }
  9866. this._drawing = false;
  9867. this._ctx.restore(); // Restore state before clipping.
  9868. },
  9869. _updatePoly: function (layer, closed) {
  9870. if (!this._drawing) { return; }
  9871. var i, j, len2, p,
  9872. parts = layer._parts,
  9873. len = parts.length,
  9874. ctx = this._ctx;
  9875. if (!len) { return; }
  9876. this._drawnLayers[layer._leaflet_id] = layer;
  9877. ctx.beginPath();
  9878. for (i = 0; i < len; i++) {
  9879. for (j = 0, len2 = parts[i].length; j < len2; j++) {
  9880. p = parts[i][j];
  9881. ctx[j ? 'lineTo' : 'moveTo'](p.x, p.y);
  9882. }
  9883. if (closed) {
  9884. ctx.closePath();
  9885. }
  9886. }
  9887. this._fillStroke(ctx, layer);
  9888. // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
  9889. },
  9890. _updateCircle: function (layer) {
  9891. if (!this._drawing || layer._empty()) { return; }
  9892. var p = layer._point,
  9893. ctx = this._ctx,
  9894. r = Math.max(Math.round(layer._radius), 1),
  9895. s = (Math.max(Math.round(layer._radiusY), 1) || r) / r;
  9896. this._drawnLayers[layer._leaflet_id] = layer;
  9897. if (s !== 1) {
  9898. ctx.save();
  9899. ctx.scale(1, s);
  9900. }
  9901. ctx.beginPath();
  9902. ctx.arc(p.x, p.y / s, r, 0, Math.PI * 2, false);
  9903. if (s !== 1) {
  9904. ctx.restore();
  9905. }
  9906. this._fillStroke(ctx, layer);
  9907. },
  9908. _fillStroke: function (ctx, layer) {
  9909. var options = layer.options;
  9910. if (options.fill) {
  9911. ctx.globalAlpha = options.fillOpacity;
  9912. ctx.fillStyle = options.fillColor || options.color;
  9913. ctx.fill(options.fillRule || 'evenodd');
  9914. }
  9915. if (options.stroke && options.weight !== 0) {
  9916. if (ctx.setLineDash) {
  9917. ctx.setLineDash(layer.options && layer.options._dashArray || []);
  9918. }
  9919. ctx.globalAlpha = options.opacity;
  9920. ctx.lineWidth = options.weight;
  9921. ctx.strokeStyle = options.color;
  9922. ctx.lineCap = options.lineCap;
  9923. ctx.lineJoin = options.lineJoin;
  9924. ctx.stroke();
  9925. }
  9926. },
  9927. // Canvas obviously doesn't have mouse events for individual drawn objects,
  9928. // so we emulate that by calculating what's under the mouse on mousemove/click manually
  9929. _onClick: function (e) {
  9930. var point = this._map.mouseEventToLayerPoint(e), layer, clickedLayer;
  9931. for (var order = this._drawFirst; order; order = order.next) {
  9932. layer = order.layer;
  9933. if (layer.options.interactive && layer._containsPoint(point) && !this._map._draggableMoved(layer)) {
  9934. clickedLayer = layer;
  9935. }
  9936. }
  9937. if (clickedLayer) {
  9938. fakeStop(e);
  9939. this._fireEvent([clickedLayer], e);
  9940. }
  9941. },
  9942. _onMouseMove: function (e) {
  9943. if (!this._map || this._map.dragging.moving() || this._map._animatingZoom) { return; }
  9944. var point = this._map.mouseEventToLayerPoint(e);
  9945. this._handleMouseHover(e, point);
  9946. },
  9947. _handleMouseOut: function (e) {
  9948. var layer = this._hoveredLayer;
  9949. if (layer) {
  9950. // if we're leaving the layer, fire mouseout
  9951. removeClass(this._container, 'leaflet-interactive');
  9952. this._fireEvent([layer], e, 'mouseout');
  9953. this._hoveredLayer = null;
  9954. }
  9955. },
  9956. _handleMouseHover: function (e, point) {
  9957. var layer, candidateHoveredLayer;
  9958. for (var order = this._drawFirst; order; order = order.next) {
  9959. layer = order.layer;
  9960. if (layer.options.interactive && layer._containsPoint(point)) {
  9961. candidateHoveredLayer = layer;
  9962. }
  9963. }
  9964. if (candidateHoveredLayer !== this._hoveredLayer) {
  9965. this._handleMouseOut(e);
  9966. if (candidateHoveredLayer) {
  9967. addClass(this._container, 'leaflet-interactive'); // change cursor
  9968. this._fireEvent([candidateHoveredLayer], e, 'mouseover');
  9969. this._hoveredLayer = candidateHoveredLayer;
  9970. }
  9971. }
  9972. if (this._hoveredLayer) {
  9973. this._fireEvent([this._hoveredLayer], e);
  9974. }
  9975. },
  9976. _fireEvent: function (layers, e, type) {
  9977. this._map._fireDOMEvent(e, type || e.type, layers);
  9978. },
  9979. _bringToFront: function (layer) {
  9980. var order = layer._order;
  9981. var next = order.next;
  9982. var prev = order.prev;
  9983. if (next) {
  9984. next.prev = prev;
  9985. } else {
  9986. // Already last
  9987. return;
  9988. }
  9989. if (prev) {
  9990. prev.next = next;
  9991. } else if (next) {
  9992. // Update first entry unless this is the
  9993. // single entry
  9994. this._drawFirst = next;
  9995. }
  9996. order.prev = this._drawLast;
  9997. this._drawLast.next = order;
  9998. order.next = null;
  9999. this._drawLast = order;
  10000. this._requestRedraw(layer);
  10001. },
  10002. _bringToBack: function (layer) {
  10003. var order = layer._order;
  10004. var next = order.next;
  10005. var prev = order.prev;
  10006. if (prev) {
  10007. prev.next = next;
  10008. } else {
  10009. // Already first
  10010. return;
  10011. }
  10012. if (next) {
  10013. next.prev = prev;
  10014. } else if (prev) {
  10015. // Update last entry unless this is the
  10016. // single entry
  10017. this._drawLast = prev;
  10018. }
  10019. order.prev = null;
  10020. order.next = this._drawFirst;
  10021. this._drawFirst.prev = order;
  10022. this._drawFirst = order;
  10023. this._requestRedraw(layer);
  10024. }
  10025. });
  10026. // @factory L.canvas(options?: Renderer options)
  10027. // Creates a Canvas renderer with the given options.
  10028. function canvas$1(options) {
  10029. return canvas ? new Canvas(options) : null;
  10030. }
  10031. /*
  10032. * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
  10033. */
  10034. var vmlCreate = (function () {
  10035. try {
  10036. document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
  10037. return function (name) {
  10038. return document.createElement('<lvml:' + name + ' class="lvml">');
  10039. };
  10040. } catch (e) {
  10041. return function (name) {
  10042. return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
  10043. };
  10044. }
  10045. })();
  10046. /*
  10047. * @class SVG
  10048. *
  10049. * 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.
  10050. *
  10051. * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility
  10052. * with old versions of Internet Explorer.
  10053. */
  10054. // mixin to redefine some SVG methods to handle VML syntax which is similar but with some differences
  10055. var vmlMixin = {
  10056. _initContainer: function () {
  10057. this._container = create$1('div', 'leaflet-vml-container');
  10058. },
  10059. _update: function () {
  10060. if (this._map._animatingZoom) { return; }
  10061. Renderer.prototype._update.call(this);
  10062. this.fire('update');
  10063. },
  10064. _initPath: function (layer) {
  10065. var container = layer._container = vmlCreate('shape');
  10066. addClass(container, 'leaflet-vml-shape ' + (this.options.className || ''));
  10067. container.coordsize = '1 1';
  10068. layer._path = vmlCreate('path');
  10069. container.appendChild(layer._path);
  10070. this._updateStyle(layer);
  10071. this._layers[stamp(layer)] = layer;
  10072. },
  10073. _addPath: function (layer) {
  10074. var container = layer._container;
  10075. this._container.appendChild(container);
  10076. if (layer.options.interactive) {
  10077. layer.addInteractiveTarget(container);
  10078. }
  10079. },
  10080. _removePath: function (layer) {
  10081. var container = layer._container;
  10082. remove(container);
  10083. layer.removeInteractiveTarget(container);
  10084. delete this._layers[stamp(layer)];
  10085. },
  10086. _updateStyle: function (layer) {
  10087. var stroke = layer._stroke,
  10088. fill = layer._fill,
  10089. options = layer.options,
  10090. container = layer._container;
  10091. container.stroked = !!options.stroke;
  10092. container.filled = !!options.fill;
  10093. if (options.stroke) {
  10094. if (!stroke) {
  10095. stroke = layer._stroke = vmlCreate('stroke');
  10096. }
  10097. container.appendChild(stroke);
  10098. stroke.weight = options.weight + 'px';
  10099. stroke.color = options.color;
  10100. stroke.opacity = options.opacity;
  10101. if (options.dashArray) {
  10102. stroke.dashStyle = isArray(options.dashArray) ?
  10103. options.dashArray.join(' ') :
  10104. options.dashArray.replace(/( *, *)/g, ' ');
  10105. } else {
  10106. stroke.dashStyle = '';
  10107. }
  10108. stroke.endcap = options.lineCap.replace('butt', 'flat');
  10109. stroke.joinstyle = options.lineJoin;
  10110. } else if (stroke) {
  10111. container.removeChild(stroke);
  10112. layer._stroke = null;
  10113. }
  10114. if (options.fill) {
  10115. if (!fill) {
  10116. fill = layer._fill = vmlCreate('fill');
  10117. }
  10118. container.appendChild(fill);
  10119. fill.color = options.fillColor || options.color;
  10120. fill.opacity = options.fillOpacity;
  10121. } else if (fill) {
  10122. container.removeChild(fill);
  10123. layer._fill = null;
  10124. }
  10125. },
  10126. _updateCircle: function (layer) {
  10127. var p = layer._point.round(),
  10128. r = Math.round(layer._radius),
  10129. r2 = Math.round(layer._radiusY || r);
  10130. this._setPath(layer, layer._empty() ? 'M0 0' :
  10131. 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360));
  10132. },
  10133. _setPath: function (layer, path) {
  10134. layer._path.v = path;
  10135. },
  10136. _bringToFront: function (layer) {
  10137. toFront(layer._container);
  10138. },
  10139. _bringToBack: function (layer) {
  10140. toBack(layer._container);
  10141. }
  10142. };
  10143. var create$2 = vml ? vmlCreate : svgCreate;
  10144. /*
  10145. * @class SVG
  10146. * @inherits Renderer
  10147. * @aka L.SVG
  10148. *
  10149. * Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG).
  10150. * Inherits `Renderer`.
  10151. *
  10152. * Due to [technical limitations](http://caniuse.com/#search=svg), SVG is not
  10153. * available in all web browsers, notably Android 2.x and 3.x.
  10154. *
  10155. * Although SVG is not available on IE7 and IE8, these browsers support
  10156. * [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language)
  10157. * (a now deprecated technology), and the SVG renderer will fall back to VML in
  10158. * this case.
  10159. *
  10160. * @example
  10161. *
  10162. * Use SVG by default for all paths in the map:
  10163. *
  10164. * ```js
  10165. * var map = L.map('map', {
  10166. * renderer: L.svg()
  10167. * });
  10168. * ```
  10169. *
  10170. * Use a SVG renderer with extra padding for specific vector geometries:
  10171. *
  10172. * ```js
  10173. * var map = L.map('map');
  10174. * var myRenderer = L.svg({ padding: 0.5 });
  10175. * var line = L.polyline( coordinates, { renderer: myRenderer } );
  10176. * var circle = L.circle( center, { renderer: myRenderer } );
  10177. * ```
  10178. */
  10179. var SVG = Renderer.extend({
  10180. getEvents: function () {
  10181. var events = Renderer.prototype.getEvents.call(this);
  10182. events.zoomstart = this._onZoomStart;
  10183. return events;
  10184. },
  10185. _initContainer: function () {
  10186. this._container = create$2('svg');
  10187. // makes it possible to click through svg root; we'll reset it back in individual paths
  10188. this._container.setAttribute('pointer-events', 'none');
  10189. this._rootGroup = create$2('g');
  10190. this._container.appendChild(this._rootGroup);
  10191. },
  10192. _destroyContainer: function () {
  10193. remove(this._container);
  10194. off(this._container);
  10195. delete this._container;
  10196. delete this._rootGroup;
  10197. delete this._svgSize;
  10198. },
  10199. _onZoomStart: function () {
  10200. // Drag-then-pinch interactions might mess up the center and zoom.
  10201. // In this case, the easiest way to prevent this is re-do the renderer
  10202. // bounds and padding when the zooming starts.
  10203. this._update();
  10204. },
  10205. _update: function () {
  10206. if (this._map._animatingZoom && this._bounds) { return; }
  10207. Renderer.prototype._update.call(this);
  10208. var b = this._bounds,
  10209. size = b.getSize(),
  10210. container = this._container;
  10211. // set size of svg-container if changed
  10212. if (!this._svgSize || !this._svgSize.equals(size)) {
  10213. this._svgSize = size;
  10214. container.setAttribute('width', size.x);
  10215. container.setAttribute('height', size.y);
  10216. }
  10217. // movement: update container viewBox so that we don't have to change coordinates of individual layers
  10218. setPosition(container, b.min);
  10219. container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
  10220. this.fire('update');
  10221. },
  10222. // methods below are called by vector layers implementations
  10223. _initPath: function (layer) {
  10224. var path = layer._path = create$2('path');
  10225. // @namespace Path
  10226. // @option className: String = null
  10227. // Custom class name set on an element. Only for SVG renderer.
  10228. if (layer.options.className) {
  10229. addClass(path, layer.options.className);
  10230. }
  10231. if (layer.options.interactive) {
  10232. addClass(path, 'leaflet-interactive');
  10233. }
  10234. this._updateStyle(layer);
  10235. this._layers[stamp(layer)] = layer;
  10236. },
  10237. _addPath: function (layer) {
  10238. if (!this._rootGroup) { this._initContainer(); }
  10239. this._rootGroup.appendChild(layer._path);
  10240. layer.addInteractiveTarget(layer._path);
  10241. },
  10242. _removePath: function (layer) {
  10243. remove(layer._path);
  10244. layer.removeInteractiveTarget(layer._path);
  10245. delete this._layers[stamp(layer)];
  10246. },
  10247. _updatePath: function (layer) {
  10248. layer._project();
  10249. layer._update();
  10250. },
  10251. _updateStyle: function (layer) {
  10252. var path = layer._path,
  10253. options = layer.options;
  10254. if (!path) { return; }
  10255. if (options.stroke) {
  10256. path.setAttribute('stroke', options.color);
  10257. path.setAttribute('stroke-opacity', options.opacity);
  10258. path.setAttribute('stroke-width', options.weight);
  10259. path.setAttribute('stroke-linecap', options.lineCap);
  10260. path.setAttribute('stroke-linejoin', options.lineJoin);
  10261. if (options.dashArray) {
  10262. path.setAttribute('stroke-dasharray', options.dashArray);
  10263. } else {
  10264. path.removeAttribute('stroke-dasharray');
  10265. }
  10266. if (options.dashOffset) {
  10267. path.setAttribute('stroke-dashoffset', options.dashOffset);
  10268. } else {
  10269. path.removeAttribute('stroke-dashoffset');
  10270. }
  10271. } else {
  10272. path.setAttribute('stroke', 'none');
  10273. }
  10274. if (options.fill) {
  10275. path.setAttribute('fill', options.fillColor || options.color);
  10276. path.setAttribute('fill-opacity', options.fillOpacity);
  10277. path.setAttribute('fill-rule', options.fillRule || 'evenodd');
  10278. } else {
  10279. path.setAttribute('fill', 'none');
  10280. }
  10281. },
  10282. _updatePoly: function (layer, closed) {
  10283. this._setPath(layer, pointsToPath(layer._parts, closed));
  10284. },
  10285. _updateCircle: function (layer) {
  10286. var p = layer._point,
  10287. r = Math.max(Math.round(layer._radius), 1),
  10288. r2 = Math.max(Math.round(layer._radiusY), 1) || r,
  10289. arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
  10290. // drawing a circle with two half-arcs
  10291. var d = layer._empty() ? 'M0 0' :
  10292. 'M' + (p.x - r) + ',' + p.y +
  10293. arc + (r * 2) + ',0 ' +
  10294. arc + (-r * 2) + ',0 ';
  10295. this._setPath(layer, d);
  10296. },
  10297. _setPath: function (layer, path) {
  10298. layer._path.setAttribute('d', path);
  10299. },
  10300. // SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
  10301. _bringToFront: function (layer) {
  10302. toFront(layer._path);
  10303. },
  10304. _bringToBack: function (layer) {
  10305. toBack(layer._path);
  10306. }
  10307. });
  10308. if (vml) {
  10309. SVG.include(vmlMixin);
  10310. }
  10311. // @namespace SVG
  10312. // @factory L.svg(options?: Renderer options)
  10313. // Creates a SVG renderer with the given options.
  10314. function svg$1(options) {
  10315. return svg || vml ? new SVG(options) : null;
  10316. }
  10317. Map.include({
  10318. // @namespace Map; @method getRenderer(layer: Path): Renderer
  10319. // Returns the instance of `Renderer` that should be used to render the given
  10320. // `Path`. It will ensure that the `renderer` options of the map and paths
  10321. // are respected, and that the renderers do exist on the map.
  10322. getRenderer: function (layer) {
  10323. // @namespace Path; @option renderer: Renderer
  10324. // Use this specific instance of `Renderer` for this path. Takes
  10325. // precedence over the map's [default renderer](#map-renderer).
  10326. var renderer = layer.options.renderer || this._getPaneRenderer(layer.options.pane) || this.options.renderer || this._renderer;
  10327. if (!renderer) {
  10328. // @namespace Map; @option preferCanvas: Boolean = false
  10329. // Whether `Path`s should be rendered on a `Canvas` renderer.
  10330. // By default, all `Path`s are rendered in a `SVG` renderer.
  10331. renderer = this._renderer = (this.options.preferCanvas && canvas$1()) || svg$1();
  10332. }
  10333. if (!this.hasLayer(renderer)) {
  10334. this.addLayer(renderer);
  10335. }
  10336. return renderer;
  10337. },
  10338. _getPaneRenderer: function (name) {
  10339. if (name === 'overlayPane' || name === undefined) {
  10340. return false;
  10341. }
  10342. var renderer = this._paneRenderers[name];
  10343. if (renderer === undefined) {
  10344. renderer = (SVG && svg$1({pane: name})) || (Canvas && canvas$1({pane: name}));
  10345. this._paneRenderers[name] = renderer;
  10346. }
  10347. return renderer;
  10348. }
  10349. });
  10350. /*
  10351. * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
  10352. */
  10353. /*
  10354. * @class Rectangle
  10355. * @aka L.Rectangle
  10356. * @inherits Polygon
  10357. *
  10358. * A class for drawing rectangle overlays on a map. Extends `Polygon`.
  10359. *
  10360. * @example
  10361. *
  10362. * ```js
  10363. * // define rectangle geographical bounds
  10364. * var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];
  10365. *
  10366. * // create an orange rectangle
  10367. * L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);
  10368. *
  10369. * // zoom the map to the rectangle bounds
  10370. * map.fitBounds(bounds);
  10371. * ```
  10372. *
  10373. */
  10374. var Rectangle = Polygon.extend({
  10375. initialize: function (latLngBounds, options) {
  10376. Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
  10377. },
  10378. // @method setBounds(latLngBounds: LatLngBounds): this
  10379. // Redraws the rectangle with the passed bounds.
  10380. setBounds: function (latLngBounds) {
  10381. return this.setLatLngs(this._boundsToLatLngs(latLngBounds));
  10382. },
  10383. _boundsToLatLngs: function (latLngBounds) {
  10384. latLngBounds = toLatLngBounds(latLngBounds);
  10385. return [
  10386. latLngBounds.getSouthWest(),
  10387. latLngBounds.getNorthWest(),
  10388. latLngBounds.getNorthEast(),
  10389. latLngBounds.getSouthEast()
  10390. ];
  10391. }
  10392. });
  10393. // @factory L.rectangle(latLngBounds: LatLngBounds, options?: Polyline options)
  10394. function rectangle(latLngBounds, options) {
  10395. return new Rectangle(latLngBounds, options);
  10396. }
  10397. SVG.create = create$2;
  10398. SVG.pointsToPath = pointsToPath;
  10399. GeoJSON.geometryToLayer = geometryToLayer;
  10400. GeoJSON.coordsToLatLng = coordsToLatLng;
  10401. GeoJSON.coordsToLatLngs = coordsToLatLngs;
  10402. GeoJSON.latLngToCoords = latLngToCoords;
  10403. GeoJSON.latLngsToCoords = latLngsToCoords;
  10404. GeoJSON.getFeature = getFeature;
  10405. GeoJSON.asFeature = asFeature;
  10406. /*
  10407. * L.Handler.BoxZoom is used to add shift-drag zoom interaction to the map
  10408. * (zoom to a selected bounding box), enabled by default.
  10409. */
  10410. // @namespace Map
  10411. // @section Interaction Options
  10412. Map.mergeOptions({
  10413. // @option boxZoom: Boolean = true
  10414. // Whether the map can be zoomed to a rectangular area specified by
  10415. // dragging the mouse while pressing the shift key.
  10416. boxZoom: true
  10417. });
  10418. var BoxZoom = Handler.extend({
  10419. initialize: function (map) {
  10420. this._map = map;
  10421. this._container = map._container;
  10422. this._pane = map._panes.overlayPane;
  10423. this._resetStateTimeout = 0;
  10424. map.on('unload', this._destroy, this);
  10425. },
  10426. addHooks: function () {
  10427. on(this._container, 'mousedown', this._onMouseDown, this);
  10428. },
  10429. removeHooks: function () {
  10430. off(this._container, 'mousedown', this._onMouseDown, this);
  10431. },
  10432. moved: function () {
  10433. return this._moved;
  10434. },
  10435. _destroy: function () {
  10436. remove(this._pane);
  10437. delete this._pane;
  10438. },
  10439. _resetState: function () {
  10440. this._resetStateTimeout = 0;
  10441. this._moved = false;
  10442. },
  10443. _clearDeferredResetState: function () {
  10444. if (this._resetStateTimeout !== 0) {
  10445. clearTimeout(this._resetStateTimeout);
  10446. this._resetStateTimeout = 0;
  10447. }
  10448. },
  10449. _onMouseDown: function (e) {
  10450. if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
  10451. // Clear the deferred resetState if it hasn't executed yet, otherwise it
  10452. // will interrupt the interaction and orphan a box element in the container.
  10453. this._clearDeferredResetState();
  10454. this._resetState();
  10455. disableTextSelection();
  10456. disableImageDrag();
  10457. this._startPoint = this._map.mouseEventToContainerPoint(e);
  10458. on(document, {
  10459. contextmenu: stop,
  10460. mousemove: this._onMouseMove,
  10461. mouseup: this._onMouseUp,
  10462. keydown: this._onKeyDown
  10463. }, this);
  10464. },
  10465. _onMouseMove: function (e) {
  10466. if (!this._moved) {
  10467. this._moved = true;
  10468. this._box = create$1('div', 'leaflet-zoom-box', this._container);
  10469. addClass(this._container, 'leaflet-crosshair');
  10470. this._map.fire('boxzoomstart');
  10471. }
  10472. this._point = this._map.mouseEventToContainerPoint(e);
  10473. var bounds = new Bounds(this._point, this._startPoint),
  10474. size = bounds.getSize();
  10475. setPosition(this._box, bounds.min);
  10476. this._box.style.width = size.x + 'px';
  10477. this._box.style.height = size.y + 'px';
  10478. },
  10479. _finish: function () {
  10480. if (this._moved) {
  10481. remove(this._box);
  10482. removeClass(this._container, 'leaflet-crosshair');
  10483. }
  10484. enableTextSelection();
  10485. enableImageDrag();
  10486. off(document, {
  10487. contextmenu: stop,
  10488. mousemove: this._onMouseMove,
  10489. mouseup: this._onMouseUp,
  10490. keydown: this._onKeyDown
  10491. }, this);
  10492. },
  10493. _onMouseUp: function (e) {
  10494. if ((e.which !== 1) && (e.button !== 1)) { return; }
  10495. this._finish();
  10496. if (!this._moved) { return; }
  10497. // Postpone to next JS tick so internal click event handling
  10498. // still see it as "moved".
  10499. this._clearDeferredResetState();
  10500. this._resetStateTimeout = setTimeout(bind(this._resetState, this), 0);
  10501. var bounds = new LatLngBounds(
  10502. this._map.containerPointToLatLng(this._startPoint),
  10503. this._map.containerPointToLatLng(this._point));
  10504. this._map
  10505. .fitBounds(bounds)
  10506. .fire('boxzoomend', {boxZoomBounds: bounds});
  10507. },
  10508. _onKeyDown: function (e) {
  10509. if (e.keyCode === 27) {
  10510. this._finish();
  10511. }
  10512. }
  10513. });
  10514. // @section Handlers
  10515. // @property boxZoom: Handler
  10516. // Box (shift-drag with mouse) zoom handler.
  10517. Map.addInitHook('addHandler', 'boxZoom', BoxZoom);
  10518. /*
  10519. * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
  10520. */
  10521. // @namespace Map
  10522. // @section Interaction Options
  10523. Map.mergeOptions({
  10524. // @option doubleClickZoom: Boolean|String = true
  10525. // Whether the map can be zoomed in by double clicking on it and
  10526. // zoomed out by double clicking while holding shift. If passed
  10527. // `'center'`, double-click zoom will zoom to the center of the
  10528. // view regardless of where the mouse was.
  10529. doubleClickZoom: true
  10530. });
  10531. var DoubleClickZoom = Handler.extend({
  10532. addHooks: function () {
  10533. this._map.on('dblclick', this._onDoubleClick, this);
  10534. },
  10535. removeHooks: function () {
  10536. this._map.off('dblclick', this._onDoubleClick, this);
  10537. },
  10538. _onDoubleClick: function (e) {
  10539. var map = this._map,
  10540. oldZoom = map.getZoom(),
  10541. delta = map.options.zoomDelta,
  10542. zoom = e.originalEvent.shiftKey ? oldZoom - delta : oldZoom + delta;
  10543. if (map.options.doubleClickZoom === 'center') {
  10544. map.setZoom(zoom);
  10545. } else {
  10546. map.setZoomAround(e.containerPoint, zoom);
  10547. }
  10548. }
  10549. });
  10550. // @section Handlers
  10551. //
  10552. // Map properties include interaction handlers that allow you to control
  10553. // interaction behavior in runtime, enabling or disabling certain features such
  10554. // as dragging or touch zoom (see `Handler` methods). For example:
  10555. //
  10556. // ```js
  10557. // map.doubleClickZoom.disable();
  10558. // ```
  10559. //
  10560. // @property doubleClickZoom: Handler
  10561. // Double click zoom handler.
  10562. Map.addInitHook('addHandler', 'doubleClickZoom', DoubleClickZoom);
  10563. /*
  10564. * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
  10565. */
  10566. // @namespace Map
  10567. // @section Interaction Options
  10568. Map.mergeOptions({
  10569. // @option dragging: Boolean = true
  10570. // Whether the map be draggable with mouse/touch or not.
  10571. dragging: true,
  10572. // @section Panning Inertia Options
  10573. // @option inertia: Boolean = *
  10574. // If enabled, panning of the map will have an inertia effect where
  10575. // the map builds momentum while dragging and continues moving in
  10576. // the same direction for some time. Feels especially nice on touch
  10577. // devices. Enabled by default unless running on old Android devices.
  10578. inertia: !android23,
  10579. // @option inertiaDeceleration: Number = 3000
  10580. // The rate with which the inertial movement slows down, in pixels/second².
  10581. inertiaDeceleration: 3400, // px/s^2
  10582. // @option inertiaMaxSpeed: Number = Infinity
  10583. // Max speed of the inertial movement, in pixels/second.
  10584. inertiaMaxSpeed: Infinity, // px/s
  10585. // @option easeLinearity: Number = 0.2
  10586. easeLinearity: 0.2,
  10587. // TODO refactor, move to CRS
  10588. // @option worldCopyJump: Boolean = false
  10589. // With this option enabled, the map tracks when you pan to another "copy"
  10590. // of the world and seamlessly jumps to the original one so that all overlays
  10591. // like markers and vector layers are still visible.
  10592. worldCopyJump: false,
  10593. // @option maxBoundsViscosity: Number = 0.0
  10594. // If `maxBounds` is set, this option will control how solid the bounds
  10595. // are when dragging the map around. The default value of `0.0` allows the
  10596. // user to drag outside the bounds at normal speed, higher values will
  10597. // slow down map dragging outside bounds, and `1.0` makes the bounds fully
  10598. // solid, preventing the user from dragging outside the bounds.
  10599. maxBoundsViscosity: 0.0
  10600. });
  10601. var Drag = Handler.extend({
  10602. addHooks: function () {
  10603. if (!this._draggable) {
  10604. var map = this._map;
  10605. this._draggable = new Draggable(map._mapPane, map._container);
  10606. this._draggable.on({
  10607. dragstart: this._onDragStart,
  10608. drag: this._onDrag,
  10609. dragend: this._onDragEnd
  10610. }, this);
  10611. this._draggable.on('predrag', this._onPreDragLimit, this);
  10612. if (map.options.worldCopyJump) {
  10613. this._draggable.on('predrag', this._onPreDragWrap, this);
  10614. map.on('zoomend', this._onZoomEnd, this);
  10615. map.whenReady(this._onZoomEnd, this);
  10616. }
  10617. }
  10618. addClass(this._map._container, 'leaflet-grab leaflet-touch-drag');
  10619. this._draggable.enable();
  10620. this._positions = [];
  10621. this._times = [];
  10622. },
  10623. removeHooks: function () {
  10624. removeClass(this._map._container, 'leaflet-grab');
  10625. removeClass(this._map._container, 'leaflet-touch-drag');
  10626. this._draggable.disable();
  10627. },
  10628. moved: function () {
  10629. return this._draggable && this._draggable._moved;
  10630. },
  10631. moving: function () {
  10632. return this._draggable && this._draggable._moving;
  10633. },
  10634. _onDragStart: function () {
  10635. var map = this._map;
  10636. map._stop();
  10637. if (this._map.options.maxBounds && this._map.options.maxBoundsViscosity) {
  10638. var bounds = toLatLngBounds(this._map.options.maxBounds);
  10639. this._offsetLimit = toBounds(
  10640. this._map.latLngToContainerPoint(bounds.getNorthWest()).multiplyBy(-1),
  10641. this._map.latLngToContainerPoint(bounds.getSouthEast()).multiplyBy(-1)
  10642. .add(this._map.getSize()));
  10643. this._viscosity = Math.min(1.0, Math.max(0.0, this._map.options.maxBoundsViscosity));
  10644. } else {
  10645. this._offsetLimit = null;
  10646. }
  10647. map
  10648. .fire('movestart')
  10649. .fire('dragstart');
  10650. if (map.options.inertia) {
  10651. this._positions = [];
  10652. this._times = [];
  10653. }
  10654. },
  10655. _onDrag: function (e) {
  10656. if (this._map.options.inertia) {
  10657. var time = this._lastTime = +new Date(),
  10658. pos = this._lastPos = this._draggable._absPos || this._draggable._newPos;
  10659. this._positions.push(pos);
  10660. this._times.push(time);
  10661. this._prunePositions(time);
  10662. }
  10663. this._map
  10664. .fire('move', e)
  10665. .fire('drag', e);
  10666. },
  10667. _prunePositions: function (time) {
  10668. while (this._positions.length > 1 && time - this._times[0] > 50) {
  10669. this._positions.shift();
  10670. this._times.shift();
  10671. }
  10672. },
  10673. _onZoomEnd: function () {
  10674. var pxCenter = this._map.getSize().divideBy(2),
  10675. pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
  10676. this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
  10677. this._worldWidth = this._map.getPixelWorldBounds().getSize().x;
  10678. },
  10679. _viscousLimit: function (value, threshold) {
  10680. return value - (value - threshold) * this._viscosity;
  10681. },
  10682. _onPreDragLimit: function () {
  10683. if (!this._viscosity || !this._offsetLimit) { return; }
  10684. var offset = this._draggable._newPos.subtract(this._draggable._startPos);
  10685. var limit = this._offsetLimit;
  10686. if (offset.x < limit.min.x) { offset.x = this._viscousLimit(offset.x, limit.min.x); }
  10687. if (offset.y < limit.min.y) { offset.y = this._viscousLimit(offset.y, limit.min.y); }
  10688. if (offset.x > limit.max.x) { offset.x = this._viscousLimit(offset.x, limit.max.x); }
  10689. if (offset.y > limit.max.y) { offset.y = this._viscousLimit(offset.y, limit.max.y); }
  10690. this._draggable._newPos = this._draggable._startPos.add(offset);
  10691. },
  10692. _onPreDragWrap: function () {
  10693. // TODO refactor to be able to adjust map pane position after zoom
  10694. var worldWidth = this._worldWidth,
  10695. halfWidth = Math.round(worldWidth / 2),
  10696. dx = this._initialWorldOffset,
  10697. x = this._draggable._newPos.x,
  10698. newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
  10699. newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
  10700. newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
  10701. this._draggable._absPos = this._draggable._newPos.clone();
  10702. this._draggable._newPos.x = newX;
  10703. },
  10704. _onDragEnd: function (e) {
  10705. var map = this._map,
  10706. options = map.options,
  10707. noInertia = !options.inertia || this._times.length < 2;
  10708. map.fire('dragend', e);
  10709. if (noInertia) {
  10710. map.fire('moveend');
  10711. } else {
  10712. this._prunePositions(+new Date());
  10713. var direction = this._lastPos.subtract(this._positions[0]),
  10714. duration = (this._lastTime - this._times[0]) / 1000,
  10715. ease = options.easeLinearity,
  10716. speedVector = direction.multiplyBy(ease / duration),
  10717. speed = speedVector.distanceTo([0, 0]),
  10718. limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
  10719. limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
  10720. decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
  10721. offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
  10722. if (!offset.x && !offset.y) {
  10723. map.fire('moveend');
  10724. } else {
  10725. offset = map._limitOffset(offset, map.options.maxBounds);
  10726. requestAnimFrame(function () {
  10727. map.panBy(offset, {
  10728. duration: decelerationDuration,
  10729. easeLinearity: ease,
  10730. noMoveStart: true,
  10731. animate: true
  10732. });
  10733. });
  10734. }
  10735. }
  10736. }
  10737. });
  10738. // @section Handlers
  10739. // @property dragging: Handler
  10740. // Map dragging handler (by both mouse and touch).
  10741. Map.addInitHook('addHandler', 'dragging', Drag);
  10742. /*
  10743. * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
  10744. */
  10745. // @namespace Map
  10746. // @section Keyboard Navigation Options
  10747. Map.mergeOptions({
  10748. // @option keyboard: Boolean = true
  10749. // Makes the map focusable and allows users to navigate the map with keyboard
  10750. // arrows and `+`/`-` keys.
  10751. keyboard: true,
  10752. // @option keyboardPanDelta: Number = 80
  10753. // Amount of pixels to pan when pressing an arrow key.
  10754. keyboardPanDelta: 80
  10755. });
  10756. var Keyboard = Handler.extend({
  10757. keyCodes: {
  10758. left: [37],
  10759. right: [39],
  10760. down: [40],
  10761. up: [38],
  10762. zoomIn: [187, 107, 61, 171],
  10763. zoomOut: [189, 109, 54, 173]
  10764. },
  10765. initialize: function (map) {
  10766. this._map = map;
  10767. this._setPanDelta(map.options.keyboardPanDelta);
  10768. this._setZoomDelta(map.options.zoomDelta);
  10769. },
  10770. addHooks: function () {
  10771. var container = this._map._container;
  10772. // make the container focusable by tabbing
  10773. if (container.tabIndex <= 0) {
  10774. container.tabIndex = '0';
  10775. }
  10776. on(container, {
  10777. focus: this._onFocus,
  10778. blur: this._onBlur,
  10779. mousedown: this._onMouseDown
  10780. }, this);
  10781. this._map.on({
  10782. focus: this._addHooks,
  10783. blur: this._removeHooks
  10784. }, this);
  10785. },
  10786. removeHooks: function () {
  10787. this._removeHooks();
  10788. off(this._map._container, {
  10789. focus: this._onFocus,
  10790. blur: this._onBlur,
  10791. mousedown: this._onMouseDown
  10792. }, this);
  10793. this._map.off({
  10794. focus: this._addHooks,
  10795. blur: this._removeHooks
  10796. }, this);
  10797. },
  10798. _onMouseDown: function () {
  10799. if (this._focused) { return; }
  10800. var body = document.body,
  10801. docEl = document.documentElement,
  10802. top = body.scrollTop || docEl.scrollTop,
  10803. left = body.scrollLeft || docEl.scrollLeft;
  10804. this._map._container.focus();
  10805. window.scrollTo(left, top);
  10806. },
  10807. _onFocus: function () {
  10808. this._focused = true;
  10809. this._map.fire('focus');
  10810. },
  10811. _onBlur: function () {
  10812. this._focused = false;
  10813. this._map.fire('blur');
  10814. },
  10815. _setPanDelta: function (panDelta) {
  10816. var keys = this._panKeys = {},
  10817. codes = this.keyCodes,
  10818. i, len;
  10819. for (i = 0, len = codes.left.length; i < len; i++) {
  10820. keys[codes.left[i]] = [-1 * panDelta, 0];
  10821. }
  10822. for (i = 0, len = codes.right.length; i < len; i++) {
  10823. keys[codes.right[i]] = [panDelta, 0];
  10824. }
  10825. for (i = 0, len = codes.down.length; i < len; i++) {
  10826. keys[codes.down[i]] = [0, panDelta];
  10827. }
  10828. for (i = 0, len = codes.up.length; i < len; i++) {
  10829. keys[codes.up[i]] = [0, -1 * panDelta];
  10830. }
  10831. },
  10832. _setZoomDelta: function (zoomDelta) {
  10833. var keys = this._zoomKeys = {},
  10834. codes = this.keyCodes,
  10835. i, len;
  10836. for (i = 0, len = codes.zoomIn.length; i < len; i++) {
  10837. keys[codes.zoomIn[i]] = zoomDelta;
  10838. }
  10839. for (i = 0, len = codes.zoomOut.length; i < len; i++) {
  10840. keys[codes.zoomOut[i]] = -zoomDelta;
  10841. }
  10842. },
  10843. _addHooks: function () {
  10844. on(document, 'keydown', this._onKeyDown, this);
  10845. },
  10846. _removeHooks: function () {
  10847. off(document, 'keydown', this._onKeyDown, this);
  10848. },
  10849. _onKeyDown: function (e) {
  10850. if (e.altKey || e.ctrlKey || e.metaKey) { return; }
  10851. var key = e.keyCode,
  10852. map = this._map,
  10853. offset;
  10854. if (key in this._panKeys) {
  10855. if (map._panAnim && map._panAnim._inProgress) { return; }
  10856. offset = this._panKeys[key];
  10857. if (e.shiftKey) {
  10858. offset = toPoint(offset).multiplyBy(3);
  10859. }
  10860. map.panBy(offset);
  10861. if (map.options.maxBounds) {
  10862. map.panInsideBounds(map.options.maxBounds);
  10863. }
  10864. } else if (key in this._zoomKeys) {
  10865. map.setZoom(map.getZoom() + (e.shiftKey ? 3 : 1) * this._zoomKeys[key]);
  10866. } else if (key === 27 && map._popup && map._popup.options.closeOnEscapeKey) {
  10867. map.closePopup();
  10868. } else {
  10869. return;
  10870. }
  10871. stop(e);
  10872. }
  10873. });
  10874. // @section Handlers
  10875. // @section Handlers
  10876. // @property keyboard: Handler
  10877. // Keyboard navigation handler.
  10878. Map.addInitHook('addHandler', 'keyboard', Keyboard);
  10879. /*
  10880. * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
  10881. */
  10882. // @namespace Map
  10883. // @section Interaction Options
  10884. Map.mergeOptions({
  10885. // @section Mousewheel options
  10886. // @option scrollWheelZoom: Boolean|String = true
  10887. // Whether the map can be zoomed by using the mouse wheel. If passed `'center'`,
  10888. // it will zoom to the center of the view regardless of where the mouse was.
  10889. scrollWheelZoom: true,
  10890. // @option wheelDebounceTime: Number = 40
  10891. // Limits the rate at which a wheel can fire (in milliseconds). By default
  10892. // user can't zoom via wheel more often than once per 40 ms.
  10893. wheelDebounceTime: 40,
  10894. // @option wheelPxPerZoomLevel: Number = 60
  10895. // How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta))
  10896. // mean a change of one full zoom level. Smaller values will make wheel-zooming
  10897. // faster (and vice versa).
  10898. wheelPxPerZoomLevel: 60
  10899. });
  10900. var ScrollWheelZoom = Handler.extend({
  10901. addHooks: function () {
  10902. on(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10903. this._delta = 0;
  10904. },
  10905. removeHooks: function () {
  10906. off(this._map._container, 'mousewheel', this._onWheelScroll, this);
  10907. },
  10908. _onWheelScroll: function (e) {
  10909. var delta = getWheelDelta(e);
  10910. var debounce = this._map.options.wheelDebounceTime;
  10911. this._delta += delta;
  10912. this._lastMousePos = this._map.mouseEventToContainerPoint(e);
  10913. if (!this._startTime) {
  10914. this._startTime = +new Date();
  10915. }
  10916. var left = Math.max(debounce - (+new Date() - this._startTime), 0);
  10917. clearTimeout(this._timer);
  10918. this._timer = setTimeout(bind(this._performZoom, this), left);
  10919. stop(e);
  10920. },
  10921. _performZoom: function () {
  10922. var map = this._map,
  10923. zoom = map.getZoom(),
  10924. snap = this._map.options.zoomSnap || 0;
  10925. map._stop(); // stop panning and fly animations if any
  10926. // map the delta with a sigmoid function to -4..4 range leaning on -1..1
  10927. var d2 = this._delta / (this._map.options.wheelPxPerZoomLevel * 4),
  10928. d3 = 4 * Math.log(2 / (1 + Math.exp(-Math.abs(d2)))) / Math.LN2,
  10929. d4 = snap ? Math.ceil(d3 / snap) * snap : d3,
  10930. delta = map._limitZoom(zoom + (this._delta > 0 ? d4 : -d4)) - zoom;
  10931. this._delta = 0;
  10932. this._startTime = null;
  10933. if (!delta) { return; }
  10934. if (map.options.scrollWheelZoom === 'center') {
  10935. map.setZoom(zoom + delta);
  10936. } else {
  10937. map.setZoomAround(this._lastMousePos, zoom + delta);
  10938. }
  10939. }
  10940. });
  10941. // @section Handlers
  10942. // @property scrollWheelZoom: Handler
  10943. // Scroll wheel zoom handler.
  10944. Map.addInitHook('addHandler', 'scrollWheelZoom', ScrollWheelZoom);
  10945. /*
  10946. * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
  10947. */
  10948. // @namespace Map
  10949. // @section Interaction Options
  10950. Map.mergeOptions({
  10951. // @section Touch interaction options
  10952. // @option tap: Boolean = true
  10953. // Enables mobile hacks for supporting instant taps (fixing 200ms click
  10954. // delay on iOS/Android) and touch holds (fired as `contextmenu` events).
  10955. tap: true,
  10956. // @option tapTolerance: Number = 15
  10957. // The max number of pixels a user can shift his finger during touch
  10958. // for it to be considered a valid tap.
  10959. tapTolerance: 15
  10960. });
  10961. var Tap = Handler.extend({
  10962. addHooks: function () {
  10963. on(this._map._container, 'touchstart', this._onDown, this);
  10964. },
  10965. removeHooks: function () {
  10966. off(this._map._container, 'touchstart', this._onDown, this);
  10967. },
  10968. _onDown: function (e) {
  10969. if (!e.touches) { return; }
  10970. preventDefault(e);
  10971. this._fireClick = true;
  10972. // don't simulate click or track longpress if more than 1 touch
  10973. if (e.touches.length > 1) {
  10974. this._fireClick = false;
  10975. clearTimeout(this._holdTimeout);
  10976. return;
  10977. }
  10978. var first = e.touches[0],
  10979. el = first.target;
  10980. this._startPos = this._newPos = new Point(first.clientX, first.clientY);
  10981. // if touching a link, highlight it
  10982. if (el.tagName && el.tagName.toLowerCase() === 'a') {
  10983. addClass(el, 'leaflet-active');
  10984. }
  10985. // simulate long hold but setting a timeout
  10986. this._holdTimeout = setTimeout(bind(function () {
  10987. if (this._isTapValid()) {
  10988. this._fireClick = false;
  10989. this._onUp();
  10990. this._simulateEvent('contextmenu', first);
  10991. }
  10992. }, this), 1000);
  10993. this._simulateEvent('mousedown', first);
  10994. on(document, {
  10995. touchmove: this._onMove,
  10996. touchend: this._onUp
  10997. }, this);
  10998. },
  10999. _onUp: function (e) {
  11000. clearTimeout(this._holdTimeout);
  11001. off(document, {
  11002. touchmove: this._onMove,
  11003. touchend: this._onUp
  11004. }, this);
  11005. if (this._fireClick && e && e.changedTouches) {
  11006. var first = e.changedTouches[0],
  11007. el = first.target;
  11008. if (el && el.tagName && el.tagName.toLowerCase() === 'a') {
  11009. removeClass(el, 'leaflet-active');
  11010. }
  11011. this._simulateEvent('mouseup', first);
  11012. // simulate click if the touch didn't move too much
  11013. if (this._isTapValid()) {
  11014. this._simulateEvent('click', first);
  11015. }
  11016. }
  11017. },
  11018. _isTapValid: function () {
  11019. return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
  11020. },
  11021. _onMove: function (e) {
  11022. var first = e.touches[0];
  11023. this._newPos = new Point(first.clientX, first.clientY);
  11024. this._simulateEvent('mousemove', first);
  11025. },
  11026. _simulateEvent: function (type, e) {
  11027. var simulatedEvent = document.createEvent('MouseEvents');
  11028. simulatedEvent._simulated = true;
  11029. e.target._simulatedClick = true;
  11030. simulatedEvent.initMouseEvent(
  11031. type, true, true, window, 1,
  11032. e.screenX, e.screenY,
  11033. e.clientX, e.clientY,
  11034. false, false, false, false, 0, null);
  11035. e.target.dispatchEvent(simulatedEvent);
  11036. }
  11037. });
  11038. // @section Handlers
  11039. // @property tap: Handler
  11040. // Mobile touch hacks (quick tap and touch hold) handler.
  11041. if (touch && !pointer) {
  11042. Map.addInitHook('addHandler', 'tap', Tap);
  11043. }
  11044. /*
  11045. * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
  11046. */
  11047. // @namespace Map
  11048. // @section Interaction Options
  11049. Map.mergeOptions({
  11050. // @section Touch interaction options
  11051. // @option touchZoom: Boolean|String = *
  11052. // Whether the map can be zoomed by touch-dragging with two fingers. If
  11053. // passed `'center'`, it will zoom to the center of the view regardless of
  11054. // where the touch events (fingers) were. Enabled for touch-capable web
  11055. // browsers except for old Androids.
  11056. touchZoom: touch && !android23,
  11057. // @option bounceAtZoomLimits: Boolean = true
  11058. // Set it to false if you don't want the map to zoom beyond min/max zoom
  11059. // and then bounce back when pinch-zooming.
  11060. bounceAtZoomLimits: true
  11061. });
  11062. var TouchZoom = Handler.extend({
  11063. addHooks: function () {
  11064. addClass(this._map._container, 'leaflet-touch-zoom');
  11065. on(this._map._container, 'touchstart', this._onTouchStart, this);
  11066. },
  11067. removeHooks: function () {
  11068. removeClass(this._map._container, 'leaflet-touch-zoom');
  11069. off(this._map._container, 'touchstart', this._onTouchStart, this);
  11070. },
  11071. _onTouchStart: function (e) {
  11072. var map = this._map;
  11073. if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
  11074. var p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11075. p2 = map.mouseEventToContainerPoint(e.touches[1]);
  11076. this._centerPoint = map.getSize()._divideBy(2);
  11077. this._startLatLng = map.containerPointToLatLng(this._centerPoint);
  11078. if (map.options.touchZoom !== 'center') {
  11079. this._pinchStartLatLng = map.containerPointToLatLng(p1.add(p2)._divideBy(2));
  11080. }
  11081. this._startDist = p1.distanceTo(p2);
  11082. this._startZoom = map.getZoom();
  11083. this._moved = false;
  11084. this._zooming = true;
  11085. map._stop();
  11086. on(document, 'touchmove', this._onTouchMove, this);
  11087. on(document, 'touchend', this._onTouchEnd, this);
  11088. preventDefault(e);
  11089. },
  11090. _onTouchMove: function (e) {
  11091. if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
  11092. var map = this._map,
  11093. p1 = map.mouseEventToContainerPoint(e.touches[0]),
  11094. p2 = map.mouseEventToContainerPoint(e.touches[1]),
  11095. scale = p1.distanceTo(p2) / this._startDist;
  11096. this._zoom = map.getScaleZoom(scale, this._startZoom);
  11097. if (!map.options.bounceAtZoomLimits && (
  11098. (this._zoom < map.getMinZoom() && scale < 1) ||
  11099. (this._zoom > map.getMaxZoom() && scale > 1))) {
  11100. this._zoom = map._limitZoom(this._zoom);
  11101. }
  11102. if (map.options.touchZoom === 'center') {
  11103. this._center = this._startLatLng;
  11104. if (scale === 1) { return; }
  11105. } else {
  11106. // Get delta from pinch to center, so centerLatLng is delta applied to initial pinchLatLng
  11107. var delta = p1._add(p2)._divideBy(2)._subtract(this._centerPoint);
  11108. if (scale === 1 && delta.x === 0 && delta.y === 0) { return; }
  11109. this._center = map.unproject(map.project(this._pinchStartLatLng, this._zoom).subtract(delta), this._zoom);
  11110. }
  11111. if (!this._moved) {
  11112. map._moveStart(true, false);
  11113. this._moved = true;
  11114. }
  11115. cancelAnimFrame(this._animRequest);
  11116. var moveFn = bind(map._move, map, this._center, this._zoom, {pinch: true, round: false});
  11117. this._animRequest = requestAnimFrame(moveFn, this, true);
  11118. preventDefault(e);
  11119. },
  11120. _onTouchEnd: function () {
  11121. if (!this._moved || !this._zooming) {
  11122. this._zooming = false;
  11123. return;
  11124. }
  11125. this._zooming = false;
  11126. cancelAnimFrame(this._animRequest);
  11127. off(document, 'touchmove', this._onTouchMove);
  11128. off(document, 'touchend', this._onTouchEnd);
  11129. // Pinch updates GridLayers' levels only when zoomSnap is off, so zoomSnap becomes noUpdate.
  11130. if (this._map.options.zoomAnimation) {
  11131. this._map._animateZoom(this._center, this._map._limitZoom(this._zoom), true, this._map.options.zoomSnap);
  11132. } else {
  11133. this._map._resetView(this._center, this._map._limitZoom(this._zoom));
  11134. }
  11135. }
  11136. });
  11137. // @section Handlers
  11138. // @property touchZoom: Handler
  11139. // Touch zoom handler.
  11140. Map.addInitHook('addHandler', 'touchZoom', TouchZoom);
  11141. Map.BoxZoom = BoxZoom;
  11142. Map.DoubleClickZoom = DoubleClickZoom;
  11143. Map.Drag = Drag;
  11144. Map.Keyboard = Keyboard;
  11145. Map.ScrollWheelZoom = ScrollWheelZoom;
  11146. Map.Tap = Tap;
  11147. Map.TouchZoom = TouchZoom;
  11148. // misc
  11149. var oldL = window.L;
  11150. function noConflict() {
  11151. window.L = oldL;
  11152. return this;
  11153. }
  11154. // Always export us to window global (see #2364)
  11155. window.L = exports;
  11156. Object.freeze = freeze;
  11157. exports.version = version;
  11158. exports.noConflict = noConflict;
  11159. exports.Control = Control;
  11160. exports.control = control;
  11161. exports.Browser = Browser;
  11162. exports.Evented = Evented;
  11163. exports.Mixin = Mixin;
  11164. exports.Util = Util;
  11165. exports.Class = Class;
  11166. exports.Handler = Handler;
  11167. exports.extend = extend;
  11168. exports.bind = bind;
  11169. exports.stamp = stamp;
  11170. exports.setOptions = setOptions;
  11171. exports.DomEvent = DomEvent;
  11172. exports.DomUtil = DomUtil;
  11173. exports.PosAnimation = PosAnimation;
  11174. exports.Draggable = Draggable;
  11175. exports.LineUtil = LineUtil;
  11176. exports.PolyUtil = PolyUtil;
  11177. exports.Point = Point;
  11178. exports.point = toPoint;
  11179. exports.Bounds = Bounds;
  11180. exports.bounds = toBounds;
  11181. exports.Transformation = Transformation;
  11182. exports.transformation = toTransformation;
  11183. exports.Projection = index;
  11184. exports.LatLng = LatLng;
  11185. exports.latLng = toLatLng;
  11186. exports.LatLngBounds = LatLngBounds;
  11187. exports.latLngBounds = toLatLngBounds;
  11188. exports.CRS = CRS;
  11189. exports.GeoJSON = GeoJSON;
  11190. exports.geoJSON = geoJSON;
  11191. exports.geoJson = geoJson;
  11192. exports.Layer = Layer;
  11193. exports.LayerGroup = LayerGroup;
  11194. exports.layerGroup = layerGroup;
  11195. exports.FeatureGroup = FeatureGroup;
  11196. exports.featureGroup = featureGroup;
  11197. exports.ImageOverlay = ImageOverlay;
  11198. exports.imageOverlay = imageOverlay;
  11199. exports.VideoOverlay = VideoOverlay;
  11200. exports.videoOverlay = videoOverlay;
  11201. exports.DivOverlay = DivOverlay;
  11202. exports.Popup = Popup;
  11203. exports.popup = popup;
  11204. exports.Tooltip = Tooltip;
  11205. exports.tooltip = tooltip;
  11206. exports.Icon = Icon;
  11207. exports.icon = icon;
  11208. exports.DivIcon = DivIcon;
  11209. exports.divIcon = divIcon;
  11210. exports.Marker = Marker;
  11211. exports.marker = marker;
  11212. exports.TileLayer = TileLayer;
  11213. exports.tileLayer = tileLayer;
  11214. exports.GridLayer = GridLayer;
  11215. exports.gridLayer = gridLayer;
  11216. exports.SVG = SVG;
  11217. exports.svg = svg$1;
  11218. exports.Renderer = Renderer;
  11219. exports.Canvas = Canvas;
  11220. exports.canvas = canvas$1;
  11221. exports.Path = Path;
  11222. exports.CircleMarker = CircleMarker;
  11223. exports.circleMarker = circleMarker;
  11224. exports.Circle = Circle;
  11225. exports.circle = circle;
  11226. exports.Polyline = Polyline;
  11227. exports.polyline = polyline;
  11228. exports.Polygon = Polygon;
  11229. exports.polygon = polygon;
  11230. exports.Rectangle = Rectangle;
  11231. exports.rectangle = rectangle;
  11232. exports.Map = Map;
  11233. exports.map = createMap;
  11234. })));
  11235. //# sourceMappingURL=leaflet-src.js.map