leaflet.draw-src.js 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768
  1. /*
  2. Leaflet.draw 0.4.14, a plugin that adds drawing and editing tools to Leaflet powered maps.
  3. (c) 2012-2017, Jacob Toye, Jon West, Smartrak, Leaflet
  4. https://github.com/Leaflet/Leaflet.draw
  5. http://leafletjs.com
  6. */
  7. (function (window, document, undefined) {
  8. /**
  9. * Leaflet.draw assumes that you have already included the Leaflet library.
  10. */
  11. L.drawVersion = "0.4.14";
  12. /**
  13. * @class L.Draw
  14. * @aka Draw
  15. *
  16. *
  17. * To add the draw toolbar set the option drawControl: true in the map options.
  18. *
  19. * @example
  20. * ```js
  21. * var map = L.map('map', {drawControl: true}).setView([51.505, -0.09], 13);
  22. *
  23. * L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  24. * attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  25. * }).addTo(map);
  26. * ```
  27. *
  28. * ### Adding the edit toolbar
  29. * To use the edit toolbar you must initialise the Leaflet.draw control and manually add it to the map.
  30. *
  31. * ```js
  32. * var map = L.map('map').setView([51.505, -0.09], 13);
  33. *
  34. * L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  35. * attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  36. * }).addTo(map);
  37. *
  38. * // FeatureGroup is to store editable layers
  39. * var drawnItems = new L.FeatureGroup();
  40. * map.addLayer(drawnItems);
  41. *
  42. * var drawControl = new L.Control.Draw({
  43. * edit: {
  44. * featureGroup: drawnItems
  45. * }
  46. * });
  47. * map.addControl(drawControl);
  48. * ```
  49. *
  50. * The key here is the featureGroup option. This tells the plugin which FeatureGroup contains the layers that
  51. * should be editable. The featureGroup can contain 0 or more features with geometry types Point, LineString, and Polygon.
  52. * Leaflet.draw does not work with multigeometry features such as MultiPoint, MultiLineString, MultiPolygon,
  53. * or GeometryCollection. If you need to add multigeometry features to the draw plugin, convert them to a
  54. * FeatureCollection of non-multigeometries (Points, LineStrings, or Polygons).
  55. */
  56. L.Draw = {};
  57. /**
  58. * @class L.drawLocal
  59. * @aka L.drawLocal
  60. *
  61. * The core toolbar class of the API — it is used to create the toolbar ui
  62. *
  63. * @example
  64. * ```js
  65. * var modifiedDraw = L.drawLocal.extend({
  66. * draw: {
  67. * toolbar: {
  68. * buttons: {
  69. * polygon: 'Draw an awesome polygon'
  70. * }
  71. * }
  72. * }
  73. * });
  74. * ```
  75. *
  76. * The default state for the control is the draw toolbar just below the zoom control.
  77. * This will allow map users to draw vectors and markers.
  78. * **Please note the edit toolbar is not enabled by default.**
  79. */
  80. L.drawLocal = {
  81. // format: {
  82. // numeric: {
  83. // delimiters: {
  84. // thousands: ',',
  85. // decimal: '.'
  86. // }
  87. // }
  88. // },
  89. draw: {
  90. toolbar: {
  91. // #TODO: this should be reorganized where actions are nested in actions
  92. // ex: actions.undo or actions.cancel
  93. actions: {
  94. title: 'Cancel drawing',
  95. text: 'Cancel'
  96. },
  97. finish: {
  98. title: 'Finish drawing',
  99. text: 'Finish'
  100. },
  101. undo: {
  102. title: 'Delete last point drawn',
  103. text: 'Delete last point'
  104. },
  105. buttons: {
  106. polyline: 'Draw a polyline',
  107. polygon: 'Draw a polygon',
  108. rectangle: 'Draw a rectangle',
  109. circle: 'Draw a circle',
  110. marker: 'Draw a marker',
  111. circlemarker: 'Draw a circlemarker'
  112. }
  113. },
  114. handlers: {
  115. circle: {
  116. tooltip: {
  117. start: 'Click and drag to draw circle.'
  118. },
  119. radius: 'Radius'
  120. },
  121. circlemarker: {
  122. tooltip: {
  123. start: 'Click map to place circle marker.'
  124. }
  125. },
  126. marker: {
  127. tooltip: {
  128. start: 'Click map to place marker.'
  129. }
  130. },
  131. polygon: {
  132. tooltip: {
  133. start: 'Click to start drawing shape.',
  134. cont: 'Click to continue drawing shape.',
  135. end: 'Click first point to close this shape.'
  136. }
  137. },
  138. polyline: {
  139. error: '<strong>Error:</strong> shape edges cannot cross!',
  140. tooltip: {
  141. start: 'Click to start drawing line.',
  142. cont: 'Click to continue drawing line.',
  143. end: 'Click last point to finish line.'
  144. }
  145. },
  146. rectangle: {
  147. tooltip: {
  148. start: 'Click and drag to draw rectangle.'
  149. }
  150. },
  151. simpleshape: {
  152. tooltip: {
  153. end: 'Release mouse to finish drawing.'
  154. }
  155. }
  156. }
  157. },
  158. edit: {
  159. toolbar: {
  160. actions: {
  161. save: {
  162. title: 'Save changes',
  163. text: 'Save'
  164. },
  165. cancel: {
  166. title: 'Cancel editing, discards all changes',
  167. text: 'Cancel'
  168. },
  169. clearAll: {
  170. title: 'Clear all layers',
  171. text: 'Clear All'
  172. }
  173. },
  174. buttons: {
  175. edit: 'Edit layers',
  176. editDisabled: 'No layers to edit',
  177. remove: 'Delete layers',
  178. removeDisabled: 'No layers to delete'
  179. }
  180. },
  181. handlers: {
  182. edit: {
  183. tooltip: {
  184. text: 'Drag handles or markers to edit features.',
  185. subtext: 'Click cancel to undo changes.'
  186. }
  187. },
  188. remove: {
  189. tooltip: {
  190. text: 'Click on a feature to remove.'
  191. }
  192. }
  193. }
  194. }
  195. };
  196. /**
  197. * ### Events
  198. * Once you have successfully added the Leaflet.draw plugin to your map you will want to respond to the different
  199. * actions users can initiate. The following events will be triggered on the map:
  200. *
  201. * @class L.Draw.Event
  202. * @aka Draw.Event
  203. *
  204. * Use `L.Draw.Event.EVENTNAME` constants to ensure events are correct.
  205. *
  206. * @example
  207. * ```js
  208. * map.on(L.Draw.Event.CREATED; function (e) {
  209. * var type = e.layerType,
  210. * layer = e.layer;
  211. *
  212. * if (type === 'marker') {
  213. * // Do marker specific actions
  214. * }
  215. *
  216. * // Do whatever else you need to. (save to db; add to map etc)
  217. * map.addLayer(layer);
  218. *});
  219. * ```
  220. */
  221. L.Draw.Event = {};
  222. /**
  223. * @event draw:created: PolyLine; Polygon; Rectangle; Circle; Marker | String
  224. *
  225. * Layer that was just created.
  226. * The type of layer this is. One of: `polyline`; `polygon`; `rectangle`; `circle`; `marker`
  227. * Triggered when a new vector or marker has been created.
  228. *
  229. */
  230. L.Draw.Event.CREATED = 'draw:created';
  231. /**
  232. * @event draw:edited: LayerGroup
  233. *
  234. * List of all layers just edited on the map.
  235. *
  236. *
  237. * Triggered when layers in the FeatureGroup; initialised with the plugin; have been edited and saved.
  238. *
  239. * @example
  240. * ```js
  241. * map.on('draw:edited', function (e) {
  242. * var layers = e.layers;
  243. * layers.eachLayer(function (layer) {
  244. * //do whatever you want; most likely save back to db
  245. * });
  246. * });
  247. * ```
  248. */
  249. L.Draw.Event.EDITED = 'draw:edited';
  250. /**
  251. * @event draw:deleted: LayerGroup
  252. *
  253. * List of all layers just removed from the map.
  254. *
  255. * Triggered when layers have been removed (and saved) from the FeatureGroup.
  256. */
  257. L.Draw.Event.DELETED = 'draw:deleted';
  258. /**
  259. * @event draw:drawstart: String
  260. *
  261. * The type of layer this is. One of:`polyline`; `polygon`; `rectangle`; `circle`; `marker`
  262. *
  263. * Triggered when the user has chosen to draw a particular vector or marker.
  264. */
  265. L.Draw.Event.DRAWSTART = 'draw:drawstart';
  266. /**
  267. * @event draw:drawstop: String
  268. *
  269. * The type of layer this is. One of: `polyline`; `polygon`; `rectangle`; `circle`; `marker`
  270. *
  271. * Triggered when the user has finished a particular vector or marker.
  272. */
  273. L.Draw.Event.DRAWSTOP = 'draw:drawstop';
  274. /**
  275. * @event draw:drawvertex: LayerGroup
  276. *
  277. * List of all layers just being added from the map.
  278. *
  279. * Triggered when a vertex is created on a polyline or polygon.
  280. */
  281. L.Draw.Event.DRAWVERTEX = 'draw:drawvertex';
  282. /**
  283. * @event draw:editstart: String
  284. *
  285. * The type of edit this is. One of: `edit`
  286. *
  287. * Triggered when the user starts edit mode by clicking the edit tool button.
  288. */
  289. L.Draw.Event.EDITSTART = 'draw:editstart';
  290. /**
  291. * @event draw:editmove: ILayer
  292. *
  293. * Layer that was just moved.
  294. *
  295. * Triggered as the user moves a rectangle; circle or marker.
  296. */
  297. L.Draw.Event.EDITMOVE = 'draw:editmove';
  298. /**
  299. * @event draw:editresize: ILayer
  300. *
  301. * Layer that was just moved.
  302. *
  303. * Triggered as the user resizes a rectangle or circle.
  304. */
  305. L.Draw.Event.EDITRESIZE = 'draw:editresize';
  306. /**
  307. * @event draw:editvertex: LayerGroup
  308. *
  309. * List of all layers just being edited from the map.
  310. *
  311. * Triggered when a vertex is edited on a polyline or polygon.
  312. */
  313. L.Draw.Event.EDITVERTEX = 'draw:editvertex';
  314. /**
  315. * @event draw:editstop: String
  316. *
  317. * The type of edit this is. One of: `edit`
  318. *
  319. * Triggered when the user has finshed editing (edit mode) and saves edits.
  320. */
  321. L.Draw.Event.EDITSTOP = 'draw:editstop';
  322. /**
  323. * @event draw:deletestart: String
  324. *
  325. * The type of edit this is. One of: `remove`
  326. *
  327. * Triggered when the user starts remove mode by clicking the remove tool button.
  328. */
  329. L.Draw.Event.DELETESTART = 'draw:deletestart';
  330. /**
  331. * @event draw:deletestop: String
  332. *
  333. * The type of edit this is. One of: `remove`
  334. *
  335. * Triggered when the user has finished removing shapes (remove mode) and saves.
  336. */
  337. L.Draw.Event.DELETESTOP = 'draw:deletestop';
  338. /**
  339. * @event draw:toolbaropened: String
  340. *
  341. * Triggered when a toolbar is opened.
  342. */
  343. L.Draw.Event.TOOLBAROPENED = 'draw:toolbaropened';
  344. /**
  345. * @event draw:toolbarclosed: String
  346. *
  347. * Triggered when a toolbar is closed.
  348. */
  349. L.Draw.Event.TOOLBARCLOSED = 'draw:toolbarclosed';
  350. /**
  351. * @event draw:markercontext: String
  352. *
  353. * Triggered when a marker is right clicked.
  354. */
  355. L.Draw.Event.MARKERCONTEXT = 'draw:markercontext';
  356. L.Draw = L.Draw || {};
  357. /**
  358. * @class L.Draw.Feature
  359. * @aka Draw.Feature
  360. */
  361. L.Draw.Feature = L.Handler.extend({
  362. // @method initialize(): void
  363. initialize: function (map, options) {
  364. this._map = map;
  365. this._container = map._container;
  366. this._overlayPane = map._panes.overlayPane;
  367. this._popupPane = map._panes.popupPane;
  368. // Merge default shapeOptions options with custom shapeOptions
  369. if (options && options.shapeOptions) {
  370. options.shapeOptions = L.Util.extend({}, this.options.shapeOptions, options.shapeOptions);
  371. }
  372. L.setOptions(this, options);
  373. var version = L.version.split('.');
  374. //If Version is >= 1.2.0
  375. if (parseInt(version[0], 10) === 1 && parseInt(version[1], 10) >= 2) {
  376. L.Draw.Feature.include(L.Evented.prototype);
  377. } else {
  378. L.Draw.Feature.include(L.Mixin.Events);
  379. }
  380. },
  381. // @method enable(): void
  382. // Enables this handler
  383. enable: function () {
  384. if (this._enabled) {
  385. return;
  386. }
  387. L.Handler.prototype.enable.call(this);
  388. this.fire('enabled', {handler: this.type});
  389. this._map.fire(L.Draw.Event.DRAWSTART, {layerType: this.type});
  390. },
  391. // @method disable(): void
  392. disable: function () {
  393. if (!this._enabled) {
  394. return;
  395. }
  396. L.Handler.prototype.disable.call(this);
  397. this._map.fire(L.Draw.Event.DRAWSTOP, {layerType: this.type});
  398. this.fire('disabled', {handler: this.type});
  399. },
  400. // @method addHooks(): void
  401. // Add's event listeners to this handler
  402. addHooks: function () {
  403. var map = this._map;
  404. if (map) {
  405. L.DomUtil.disableTextSelection();
  406. map.getContainer().focus();
  407. this._tooltip = new L.Draw.Tooltip(this._map);
  408. L.DomEvent.on(this._container, 'keyup', this._cancelDrawing, this);
  409. }
  410. },
  411. // @method removeHooks(): void
  412. // Removes event listeners from this handler
  413. removeHooks: function () {
  414. if (this._map) {
  415. L.DomUtil.enableTextSelection();
  416. this._tooltip.dispose();
  417. this._tooltip = null;
  418. L.DomEvent.off(this._container, 'keyup', this._cancelDrawing, this);
  419. }
  420. },
  421. // @method setOptions(object): void
  422. // Sets new options to this handler
  423. setOptions: function (options) {
  424. L.setOptions(this, options);
  425. },
  426. _fireCreatedEvent: function (layer) {
  427. this._map.fire(L.Draw.Event.CREATED, {layer: layer, layerType: this.type});
  428. },
  429. // Cancel drawing when the escape key is pressed
  430. _cancelDrawing: function (e) {
  431. if (e.keyCode === 27) {
  432. this._map.fire('draw:canceled', {layerType: this.type});
  433. this.disable();
  434. }
  435. }
  436. });
  437. /**
  438. * @class L.Draw.Polyline
  439. * @aka Draw.Polyline
  440. * @inherits L.Draw.Feature
  441. */
  442. L.Draw.Polyline = L.Draw.Feature.extend({
  443. statics: {
  444. TYPE: 'polyline'
  445. },
  446. Poly: L.Polyline,
  447. options: {
  448. allowIntersection: true,
  449. repeatMode: false,
  450. drawError: {
  451. color: '#b00b00',
  452. timeout: 2500
  453. },
  454. icon: new L.DivIcon({
  455. iconSize: new L.Point(8, 8),
  456. className: 'leaflet-div-icon leaflet-editing-icon'
  457. }),
  458. touchIcon: new L.DivIcon({
  459. iconSize: new L.Point(20, 20),
  460. className: 'leaflet-div-icon leaflet-editing-icon leaflet-touch-icon'
  461. }),
  462. guidelineDistance: 20,
  463. maxGuideLineLength: 4000,
  464. shapeOptions: {
  465. stroke: true,
  466. color: '#3388ff',
  467. weight: 4,
  468. opacity: 0.5,
  469. fill: false,
  470. clickable: true
  471. },
  472. metric: true, // Whether to use the metric measurement system or imperial
  473. feet: true, // When not metric, to use feet instead of yards for display.
  474. nautic: false, // When not metric, not feet use nautic mile for display
  475. showLength: true, // Whether to display distance in the tooltip
  476. zIndexOffset: 2000, // This should be > than the highest z-index any map layers
  477. factor: 1, // To change distance calculation
  478. maxPoints: 0 // Once this number of points are placed, finish shape
  479. },
  480. // @method initialize(): void
  481. initialize: function (map, options) {
  482. // if touch, switch to touch icon
  483. if (L.Browser.touch) {
  484. this.options.icon = this.options.touchIcon;
  485. }
  486. // Need to set this here to ensure the correct message is used.
  487. this.options.drawError.message = L.drawLocal.draw.handlers.polyline.error;
  488. // Merge default drawError options with custom options
  489. if (options && options.drawError) {
  490. options.drawError = L.Util.extend({}, this.options.drawError, options.drawError);
  491. }
  492. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  493. this.type = L.Draw.Polyline.TYPE;
  494. L.Draw.Feature.prototype.initialize.call(this, map, options);
  495. },
  496. // @method addHooks(): void
  497. // Add listener hooks to this handler
  498. addHooks: function () {
  499. L.Draw.Feature.prototype.addHooks.call(this);
  500. if (this._map) {
  501. this._markers = [];
  502. this._markerGroup = new L.LayerGroup();
  503. this._map.addLayer(this._markerGroup);
  504. this._poly = new L.Polyline([], this.options.shapeOptions);
  505. this._tooltip.updateContent(this._getTooltipText());
  506. // Make a transparent marker that will used to catch click events. These click
  507. // events will create the vertices. We need to do this so we can ensure that
  508. // we can create vertices over other map layers (markers, vector layers). We
  509. // also do not want to trigger any click handlers of objects we are clicking on
  510. // while drawing.
  511. if (!this._mouseMarker) {
  512. this._mouseMarker = L.marker(this._map.getCenter(), {
  513. icon: L.divIcon({
  514. className: 'leaflet-mouse-marker',
  515. iconAnchor: [20, 20],
  516. iconSize: [40, 40]
  517. }),
  518. opacity: 0,
  519. zIndexOffset: this.options.zIndexOffset
  520. });
  521. }
  522. this._mouseMarker
  523. .on('mouseout', this._onMouseOut, this)
  524. .on('mousemove', this._onMouseMove, this) // Necessary to prevent 0.8 stutter
  525. .on('mousedown', this._onMouseDown, this)
  526. .on('mouseup', this._onMouseUp, this) // Necessary for 0.8 compatibility
  527. .addTo(this._map);
  528. this._map
  529. .on('mouseup', this._onMouseUp, this) // Necessary for 0.7 compatibility
  530. .on('mousemove', this._onMouseMove, this)
  531. .on('zoomlevelschange', this._onZoomEnd, this)
  532. .on('touchstart', this._onTouch, this)
  533. .on('zoomend', this._onZoomEnd, this);
  534. }
  535. },
  536. // @method removeHooks(): void
  537. // Remove listener hooks from this handler.
  538. removeHooks: function () {
  539. L.Draw.Feature.prototype.removeHooks.call(this);
  540. this._clearHideErrorTimeout();
  541. this._cleanUpShape();
  542. // remove markers from map
  543. this._map.removeLayer(this._markerGroup);
  544. delete this._markerGroup;
  545. delete this._markers;
  546. this._map.removeLayer(this._poly);
  547. delete this._poly;
  548. this._mouseMarker
  549. .off('mousedown', this._onMouseDown, this)
  550. .off('mouseout', this._onMouseOut, this)
  551. .off('mouseup', this._onMouseUp, this)
  552. .off('mousemove', this._onMouseMove, this);
  553. this._map.removeLayer(this._mouseMarker);
  554. delete this._mouseMarker;
  555. // clean up DOM
  556. this._clearGuides();
  557. this._map
  558. .off('mouseup', this._onMouseUp, this)
  559. .off('mousemove', this._onMouseMove, this)
  560. .off('zoomlevelschange', this._onZoomEnd, this)
  561. .off('zoomend', this._onZoomEnd, this)
  562. .off('touchstart', this._onTouch, this)
  563. .off('click', this._onTouch, this);
  564. },
  565. // @method deleteLastVertex(): void
  566. // Remove the last vertex from the polyline, removes polyline from map if only one point exists.
  567. deleteLastVertex: function () {
  568. if (this._markers.length <= 1) {
  569. return;
  570. }
  571. var lastMarker = this._markers.pop(),
  572. poly = this._poly,
  573. // Replaces .spliceLatLngs()
  574. latlngs = poly.getLatLngs(),
  575. latlng = latlngs.splice(-1, 1)[0];
  576. this._poly.setLatLngs(latlngs);
  577. this._markerGroup.removeLayer(lastMarker);
  578. if (poly.getLatLngs().length < 2) {
  579. this._map.removeLayer(poly);
  580. }
  581. this._vertexChanged(latlng, false);
  582. },
  583. // @method addVertex(): void
  584. // Add a vertex to the end of the polyline
  585. addVertex: function (latlng) {
  586. var markersLength = this._markers.length;
  587. // markersLength must be greater than or equal to 2 before intersections can occur
  588. if (markersLength >= 2 && !this.options.allowIntersection && this._poly.newLatLngIntersects(latlng)) {
  589. this._showErrorTooltip();
  590. return;
  591. }
  592. else if (this._errorShown) {
  593. this._hideErrorTooltip();
  594. }
  595. this._markers.push(this._createMarker(latlng));
  596. this._poly.addLatLng(latlng);
  597. if (this._poly.getLatLngs().length === 2) {
  598. this._map.addLayer(this._poly);
  599. }
  600. this._vertexChanged(latlng, true);
  601. },
  602. // @method completeShape(): void
  603. // Closes the polyline between the first and last points
  604. completeShape: function () {
  605. if (this._markers.length <= 1) {
  606. return;
  607. }
  608. this._fireCreatedEvent();
  609. this.disable();
  610. if (this.options.repeatMode) {
  611. this.enable();
  612. }
  613. },
  614. _finishShape: function () {
  615. var latlngs = this._poly._defaultShape ? this._poly._defaultShape() : this._poly.getLatLngs();
  616. var intersects = this._poly.newLatLngIntersects(latlngs[latlngs.length - 1]);
  617. if ((!this.options.allowIntersection && intersects) || !this._shapeIsValid()) {
  618. this._showErrorTooltip();
  619. return;
  620. }
  621. this._fireCreatedEvent();
  622. this.disable();
  623. if (this.options.repeatMode) {
  624. this.enable();
  625. }
  626. },
  627. // Called to verify the shape is valid when the user tries to finish it
  628. // Return false if the shape is not valid
  629. _shapeIsValid: function () {
  630. return true;
  631. },
  632. _onZoomEnd: function () {
  633. if (this._markers !== null) {
  634. this._updateGuide();
  635. }
  636. },
  637. _onMouseMove: function (e) {
  638. var newPos = this._map.mouseEventToLayerPoint(e.originalEvent);
  639. var latlng = this._map.layerPointToLatLng(newPos);
  640. // Save latlng
  641. // should this be moved to _updateGuide() ?
  642. this._currentLatLng = latlng;
  643. this._updateTooltip(latlng);
  644. // Update the guide line
  645. this._updateGuide(newPos);
  646. // Update the mouse marker position
  647. this._mouseMarker.setLatLng(latlng);
  648. L.DomEvent.preventDefault(e.originalEvent);
  649. },
  650. _vertexChanged: function (latlng, added) {
  651. this._map.fire(L.Draw.Event.DRAWVERTEX, {layers: this._markerGroup});
  652. this._updateFinishHandler();
  653. this._updateRunningMeasure(latlng, added);
  654. this._clearGuides();
  655. this._updateTooltip();
  656. },
  657. _onMouseDown: function (e) {
  658. if (!this._clickHandled && !this._touchHandled && !this._disableMarkers) {
  659. this._onMouseMove(e);
  660. this._clickHandled = true;
  661. this._disableNewMarkers();
  662. var originalEvent = e.originalEvent;
  663. var clientX = originalEvent.clientX;
  664. var clientY = originalEvent.clientY;
  665. this._startPoint.call(this, clientX, clientY);
  666. }
  667. },
  668. _startPoint: function (clientX, clientY) {
  669. this._mouseDownOrigin = L.point(clientX, clientY);
  670. },
  671. _onMouseUp: function (e) {
  672. var originalEvent = e.originalEvent;
  673. var clientX = originalEvent.clientX;
  674. var clientY = originalEvent.clientY;
  675. this._endPoint.call(this, clientX, clientY, e);
  676. this._clickHandled = null;
  677. },
  678. _endPoint: function (clientX, clientY, e) {
  679. if (this._mouseDownOrigin) {
  680. var dragCheckDistance = L.point(clientX, clientY)
  681. .distanceTo(this._mouseDownOrigin);
  682. var lastPtDistance = this._calculateFinishDistance(e.latlng);
  683. if (this.options.maxPoints > 1 && this.options.maxPoints == this._markers.length + 1) {
  684. this.addVertex(e.latlng);
  685. this._finishShape();
  686. } else if (lastPtDistance < 10 && L.Browser.touch) {
  687. this._finishShape();
  688. } else if (Math.abs(dragCheckDistance) < 9 * (window.devicePixelRatio || 1)) {
  689. this.addVertex(e.latlng);
  690. }
  691. this._enableNewMarkers(); // after a short pause, enable new markers
  692. }
  693. this._mouseDownOrigin = null;
  694. },
  695. // ontouch prevented by clickHandled flag because some browsers fire both click/touch events,
  696. // causing unwanted behavior
  697. _onTouch: function (e) {
  698. var originalEvent = e.originalEvent;
  699. var clientX;
  700. var clientY;
  701. if (originalEvent.touches && originalEvent.touches[0] && !this._clickHandled && !this._touchHandled && !this._disableMarkers) {
  702. clientX = originalEvent.touches[0].clientX;
  703. clientY = originalEvent.touches[0].clientY;
  704. this._disableNewMarkers();
  705. this._touchHandled = true;
  706. this._startPoint.call(this, clientX, clientY);
  707. this._endPoint.call(this, clientX, clientY, e);
  708. this._touchHandled = null;
  709. }
  710. this._clickHandled = null;
  711. },
  712. _onMouseOut: function () {
  713. if (this._tooltip) {
  714. this._tooltip._onMouseOut.call(this._tooltip);
  715. }
  716. },
  717. // calculate if we are currently within close enough distance
  718. // of the closing point (first point for shapes, last point for lines)
  719. // this is semi-ugly code but the only reliable way i found to get the job done
  720. // note: calculating point.distanceTo between mouseDownOrigin and last marker did NOT work
  721. _calculateFinishDistance: function (potentialLatLng) {
  722. var lastPtDistance;
  723. if (this._markers.length > 0) {
  724. var finishMarker;
  725. if (this.type === L.Draw.Polyline.TYPE) {
  726. finishMarker = this._markers[this._markers.length - 1];
  727. } else if (this.type === L.Draw.Polygon.TYPE) {
  728. finishMarker = this._markers[0];
  729. } else {
  730. return Infinity;
  731. }
  732. var lastMarkerPoint = this._map.latLngToContainerPoint(finishMarker.getLatLng()),
  733. potentialMarker = new L.Marker(potentialLatLng, {
  734. icon: this.options.icon,
  735. zIndexOffset: this.options.zIndexOffset * 2
  736. });
  737. var potentialMarkerPint = this._map.latLngToContainerPoint(potentialMarker.getLatLng());
  738. lastPtDistance = lastMarkerPoint.distanceTo(potentialMarkerPint);
  739. } else {
  740. lastPtDistance = Infinity;
  741. }
  742. return lastPtDistance;
  743. },
  744. _updateFinishHandler: function () {
  745. var markerCount = this._markers.length;
  746. // The last marker should have a click handler to close the polyline
  747. if (markerCount > 1) {
  748. this._markers[markerCount - 1].on('click', this._finishShape, this);
  749. }
  750. // Remove the old marker click handler (as only the last point should close the polyline)
  751. if (markerCount > 2) {
  752. this._markers[markerCount - 2].off('click', this._finishShape, this);
  753. }
  754. },
  755. _createMarker: function (latlng) {
  756. var marker = new L.Marker(latlng, {
  757. icon: this.options.icon,
  758. zIndexOffset: this.options.zIndexOffset * 2
  759. });
  760. this._markerGroup.addLayer(marker);
  761. return marker;
  762. },
  763. _updateGuide: function (newPos) {
  764. var markerCount = this._markers ? this._markers.length : 0;
  765. if (markerCount > 0) {
  766. newPos = newPos || this._map.latLngToLayerPoint(this._currentLatLng);
  767. // draw the guide line
  768. this._clearGuides();
  769. this._drawGuide(
  770. this._map.latLngToLayerPoint(this._markers[markerCount - 1].getLatLng()),
  771. newPos
  772. );
  773. }
  774. },
  775. _updateTooltip: function (latLng) {
  776. var text = this._getTooltipText();
  777. if (latLng) {
  778. this._tooltip.updatePosition(latLng);
  779. }
  780. if (!this._errorShown) {
  781. this._tooltip.updateContent(text);
  782. }
  783. },
  784. _drawGuide: function (pointA, pointB) {
  785. var length = Math.floor(Math.sqrt(Math.pow((pointB.x - pointA.x), 2) + Math.pow((pointB.y - pointA.y), 2))),
  786. guidelineDistance = this.options.guidelineDistance,
  787. maxGuideLineLength = this.options.maxGuideLineLength,
  788. // Only draw a guideline with a max length
  789. i = length > maxGuideLineLength ? length - maxGuideLineLength : guidelineDistance,
  790. fraction,
  791. dashPoint,
  792. dash;
  793. //create the guides container if we haven't yet
  794. if (!this._guidesContainer) {
  795. this._guidesContainer = L.DomUtil.create('div', 'leaflet-draw-guides', this._overlayPane);
  796. }
  797. //draw a dash every GuildeLineDistance
  798. for (; i < length; i += this.options.guidelineDistance) {
  799. //work out fraction along line we are
  800. fraction = i / length;
  801. //calculate new x,y point
  802. dashPoint = {
  803. x: Math.floor((pointA.x * (1 - fraction)) + (fraction * pointB.x)),
  804. y: Math.floor((pointA.y * (1 - fraction)) + (fraction * pointB.y))
  805. };
  806. //add guide dash to guide container
  807. dash = L.DomUtil.create('div', 'leaflet-draw-guide-dash', this._guidesContainer);
  808. dash.style.backgroundColor =
  809. !this._errorShown ? this.options.shapeOptions.color : this.options.drawError.color;
  810. L.DomUtil.setPosition(dash, dashPoint);
  811. }
  812. },
  813. _updateGuideColor: function (color) {
  814. if (this._guidesContainer) {
  815. for (var i = 0, l = this._guidesContainer.childNodes.length; i < l; i++) {
  816. this._guidesContainer.childNodes[i].style.backgroundColor = color;
  817. }
  818. }
  819. },
  820. // removes all child elements (guide dashes) from the guides container
  821. _clearGuides: function () {
  822. if (this._guidesContainer) {
  823. while (this._guidesContainer.firstChild) {
  824. this._guidesContainer.removeChild(this._guidesContainer.firstChild);
  825. }
  826. }
  827. },
  828. _getTooltipText: function () {
  829. var showLength = this.options.showLength,
  830. labelText, distanceStr;
  831. if (this._markers.length === 0) {
  832. labelText = {
  833. text: L.drawLocal.draw.handlers.polyline.tooltip.start
  834. };
  835. } else {
  836. distanceStr = showLength ? this._getMeasurementString() : '';
  837. if (this._markers.length === 1) {
  838. labelText = {
  839. text: L.drawLocal.draw.handlers.polyline.tooltip.cont,
  840. subtext: distanceStr
  841. };
  842. } else {
  843. labelText = {
  844. text: L.drawLocal.draw.handlers.polyline.tooltip.end,
  845. subtext: distanceStr
  846. };
  847. }
  848. }
  849. return labelText;
  850. },
  851. _updateRunningMeasure: function (latlng, added) {
  852. var markersLength = this._markers.length,
  853. previousMarkerIndex, distance;
  854. if (this._markers.length === 1) {
  855. this._measurementRunningTotal = 0;
  856. } else {
  857. previousMarkerIndex = markersLength - (added ? 2 : 1);
  858. // Calculate the distance based on the version
  859. if (L.GeometryUtil.isVersion07x()) {
  860. // distance = latlng.distanceTo(this._markers[previousMarkerIndex].getLatLng()) * (this.options.factor || 1);
  861. distance = 1;
  862. } else {
  863. // distance = this._map.distance(latlng, this._markers[previousMarkerIndex].getLatLng()) * (this.options.factor || 1);
  864. distance = 1;
  865. }
  866. this._measurementRunningTotal += distance * (added ? 1 : -1);
  867. }
  868. },
  869. _getMeasurementString: function () {
  870. var currentLatLng = this._currentLatLng,
  871. previousLatLng = this._markers[this._markers.length - 1].getLatLng(),
  872. distance;
  873. // Calculate the distance from the last fixed point to the mouse position based on the version
  874. if (L.GeometryUtil.isVersion07x()) {
  875. // distance = previousLatLng && currentLatLng && currentLatLng.distanceTo ? this._measurementRunningTotal + currentLatLng.distanceTo(previousLatLng) * (this.options.factor || 1) : this._measurementRunningTotal || 0;
  876. distance = 0;
  877. } else {
  878. // distance = previousLatLng && currentLatLng ? this._measurementRunningTotal + this._map.distance(currentLatLng, previousLatLng) * (this.options.factor || 1) : this._measurementRunningTotal || 0;
  879. distance = 0;
  880. }
  881. return L.GeometryUtil.readableDistance(distance, this.options.metric, this.options.feet, this.options.nautic, this.options.precision);
  882. },
  883. _showErrorTooltip: function () {
  884. this._errorShown = true;
  885. // Update tooltip
  886. this._tooltip
  887. .showAsError()
  888. .updateContent({text: this.options.drawError.message});
  889. // Update shape
  890. this._updateGuideColor(this.options.drawError.color);
  891. this._poly.setStyle({color: this.options.drawError.color});
  892. // Hide the error after 2 seconds
  893. this._clearHideErrorTimeout();
  894. this._hideErrorTimeout = setTimeout(L.Util.bind(this._hideErrorTooltip, this), this.options.drawError.timeout);
  895. },
  896. _hideErrorTooltip: function () {
  897. this._errorShown = false;
  898. this._clearHideErrorTimeout();
  899. // Revert tooltip
  900. this._tooltip
  901. .removeError()
  902. .updateContent(this._getTooltipText());
  903. // Revert shape
  904. this._updateGuideColor(this.options.shapeOptions.color);
  905. this._poly.setStyle({color: this.options.shapeOptions.color});
  906. },
  907. _clearHideErrorTimeout: function () {
  908. if (this._hideErrorTimeout) {
  909. clearTimeout(this._hideErrorTimeout);
  910. this._hideErrorTimeout = null;
  911. }
  912. },
  913. // disable new markers temporarily;
  914. // this is to prevent duplicated touch/click events in some browsers
  915. _disableNewMarkers: function () {
  916. this._disableMarkers = true;
  917. },
  918. // see _disableNewMarkers
  919. _enableNewMarkers: function () {
  920. setTimeout(function () {
  921. this._disableMarkers = false;
  922. }.bind(this), 50);
  923. },
  924. _cleanUpShape: function () {
  925. if (this._markers.length > 1) {
  926. this._markers[this._markers.length - 1].off('click', this._finishShape, this);
  927. }
  928. },
  929. _fireCreatedEvent: function () {
  930. var poly = new this.Poly(this._poly.getLatLngs(), this.options.shapeOptions);
  931. L.Draw.Feature.prototype._fireCreatedEvent.call(this, poly);
  932. }
  933. });
  934. /**
  935. * @class L.Draw.Polygon
  936. * @aka Draw.Polygon
  937. * @inherits L.Draw.Polyline
  938. */
  939. L.Draw.Polygon = L.Draw.Polyline.extend({
  940. statics: {
  941. TYPE: 'polygon'
  942. },
  943. Poly: L.Polygon,
  944. options: {
  945. showArea: false,
  946. showLength: false,
  947. shapeOptions: {
  948. stroke: true,
  949. color: '#3388ff',
  950. weight: 4,
  951. opacity: 0.5,
  952. fill: true,
  953. fillColor: null, //same as color by default
  954. fillOpacity: 0.2,
  955. clickable: true
  956. },
  957. // Whether to use the metric measurement system (truthy) or not (falsy).
  958. // Also defines the units to use for the metric system as an array of
  959. // strings (e.g. `['ha', 'm']`).
  960. metric: true,
  961. feet: true, // When not metric, to use feet instead of yards for display.
  962. nautic: false, // When not metric, not feet use nautic mile for display
  963. // Defines the precision for each type of unit (e.g. {km: 2, ft: 0}
  964. precision: {}
  965. },
  966. // @method initialize(): void
  967. initialize: function (map, options) {
  968. L.Draw.Polyline.prototype.initialize.call(this, map, options);
  969. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  970. this.type = L.Draw.Polygon.TYPE;
  971. },
  972. _updateFinishHandler: function () {
  973. var markerCount = this._markers.length;
  974. // The first marker should have a click handler to close the polygon
  975. if (markerCount === 1) {
  976. this._markers[0].on('click', this._finishShape, this);
  977. }
  978. // Add and update the double click handler
  979. if (markerCount > 2) {
  980. this._markers[markerCount - 1].on('dblclick', this._finishShape, this);
  981. // Only need to remove handler if has been added before
  982. if (markerCount > 3) {
  983. this._markers[markerCount - 2].off('dblclick', this._finishShape, this);
  984. }
  985. }
  986. },
  987. _getTooltipText: function () {
  988. var text, subtext;
  989. if (this._markers.length === 0) {
  990. text = L.drawLocal.draw.handlers.polygon.tooltip.start;
  991. } else if (this._markers.length < 3) {
  992. text = L.drawLocal.draw.handlers.polygon.tooltip.cont;
  993. subtext = this._getMeasurementString();
  994. } else {
  995. text = L.drawLocal.draw.handlers.polygon.tooltip.end;
  996. subtext = this._getMeasurementString();
  997. }
  998. return {
  999. text: text,
  1000. subtext: subtext
  1001. };
  1002. },
  1003. _getMeasurementString: function () {
  1004. var area = this._area,
  1005. measurementString = '';
  1006. if (!area && !this.options.showLength) {
  1007. return null;
  1008. }
  1009. if (this.options.showLength) {
  1010. measurementString = L.Draw.Polyline.prototype._getMeasurementString.call(this);
  1011. }
  1012. if (area) {
  1013. measurementString += '<br>' + L.GeometryUtil.readableArea(area, this.options.metric, this.options.precision);
  1014. }
  1015. return measurementString;
  1016. },
  1017. _shapeIsValid: function () {
  1018. return this._markers.length >= 3;
  1019. },
  1020. _vertexChanged: function (latlng, added) {
  1021. var latLngs;
  1022. // Check to see if we should show the area
  1023. if (!this.options.allowIntersection && this.options.showArea) {
  1024. latLngs = this._poly.getLatLngs();
  1025. this._area = L.GeometryUtil.geodesicArea(latLngs);
  1026. }
  1027. L.Draw.Polyline.prototype._vertexChanged.call(this, latlng, added);
  1028. },
  1029. _cleanUpShape: function () {
  1030. var markerCount = this._markers.length;
  1031. if (markerCount > 0) {
  1032. this._markers[0].off('click', this._finishShape, this);
  1033. if (markerCount > 2) {
  1034. this._markers[markerCount - 1].off('dblclick', this._finishShape, this);
  1035. }
  1036. }
  1037. }
  1038. });
  1039. L.SimpleShape = {};
  1040. /**
  1041. * @class L.Draw.SimpleShape
  1042. * @aka Draw.SimpleShape
  1043. * @inherits L.Draw.Feature
  1044. */
  1045. L.Draw.SimpleShape = L.Draw.Feature.extend({
  1046. options: {
  1047. repeatMode: false
  1048. },
  1049. // @method initialize(): void
  1050. initialize: function (map, options) {
  1051. this._endLabelText = L.drawLocal.draw.handlers.simpleshape.tooltip.end;
  1052. L.Draw.Feature.prototype.initialize.call(this, map, options);
  1053. },
  1054. // @method addHooks(): void
  1055. // Add listener hooks to this handler.
  1056. addHooks: function () {
  1057. L.Draw.Feature.prototype.addHooks.call(this);
  1058. if (this._map) {
  1059. this._mapDraggable = this._map.dragging.enabled();
  1060. if (this._mapDraggable) {
  1061. this._map.dragging.disable();
  1062. }
  1063. //TODO refactor: move cursor to styles
  1064. this._container.style.cursor = 'crosshair';
  1065. this._tooltip.updateContent({text: this._initialLabelText});
  1066. this._map
  1067. .on('mousedown', this._onMouseDown, this)
  1068. .on('mousemove', this._onMouseMove, this)
  1069. .on('touchstart', this._onMouseDown, this)
  1070. .on('touchmove', this._onMouseMove, this);
  1071. // we should prevent default, otherwise default behavior (scrolling) will fire,
  1072. // and that will cause document.touchend to fire and will stop the drawing
  1073. // (circle, rectangle) in touch mode.
  1074. // (update): we have to send passive now to prevent scroll, because by default it is {passive: true} now, which means,
  1075. // handler can't event.preventDefault
  1076. // check the news https://developers.google.com/web/updates/2016/06/passive-event-listeners
  1077. document.addEventListener('touchstart', L.DomEvent.preventDefault, {passive: false});
  1078. }
  1079. },
  1080. // @method removeHooks(): void
  1081. // Remove listener hooks from this handler.
  1082. removeHooks: function () {
  1083. L.Draw.Feature.prototype.removeHooks.call(this);
  1084. if (this._map) {
  1085. if (this._mapDraggable) {
  1086. this._map.dragging.enable();
  1087. }
  1088. //TODO refactor: move cursor to styles
  1089. this._container.style.cursor = '';
  1090. this._map
  1091. .off('mousedown', this._onMouseDown, this)
  1092. .off('mousemove', this._onMouseMove, this)
  1093. .off('touchstart', this._onMouseDown, this)
  1094. .off('touchmove', this._onMouseMove, this);
  1095. L.DomEvent.off(document, 'mouseup', this._onMouseUp, this);
  1096. L.DomEvent.off(document, 'touchend', this._onMouseUp, this);
  1097. document.removeEventListener('touchstart', L.DomEvent.preventDefault);
  1098. // If the box element doesn't exist they must not have moved the mouse, so don't need to destroy/return
  1099. if (this._shape) {
  1100. this._map.removeLayer(this._shape);
  1101. delete this._shape;
  1102. }
  1103. }
  1104. this._isDrawing = false;
  1105. },
  1106. _getTooltipText: function () {
  1107. return {
  1108. text: this._endLabelText
  1109. };
  1110. },
  1111. _onMouseDown: function (e) {
  1112. this._isDrawing = true;
  1113. this._startLatLng = e.latlng;
  1114. L.DomEvent
  1115. .on(document, 'mouseup', this._onMouseUp, this)
  1116. .on(document, 'touchend', this._onMouseUp, this)
  1117. .preventDefault(e.originalEvent);
  1118. },
  1119. _onMouseMove: function (e) {
  1120. var latlng = e.latlng;
  1121. this._tooltip.updatePosition(latlng);
  1122. if (this._isDrawing) {
  1123. this._tooltip.updateContent(this._getTooltipText());
  1124. this._drawShape(latlng);
  1125. }
  1126. },
  1127. _onMouseUp: function () {
  1128. if (this._shape) {
  1129. this._fireCreatedEvent();
  1130. }
  1131. this.disable();
  1132. if (this.options.repeatMode) {
  1133. this.enable();
  1134. }
  1135. }
  1136. });
  1137. /**
  1138. * @class L.Draw.Rectangle
  1139. * @aka Draw.Rectangle
  1140. * @inherits L.Draw.SimpleShape
  1141. */
  1142. L.Draw.Rectangle = L.Draw.SimpleShape.extend({
  1143. statics: {
  1144. TYPE: 'rectangle'
  1145. },
  1146. options: {
  1147. shapeOptions: {
  1148. stroke: true,
  1149. color: '#3388ff',
  1150. weight: 4,
  1151. opacity: 0.5,
  1152. fill: true,
  1153. fillColor: null, //same as color by default
  1154. fillOpacity: 0.2,
  1155. showArea: true,
  1156. clickable: true
  1157. },
  1158. metric: true // Whether to use the metric measurement system or imperial
  1159. },
  1160. // @method initialize(): void
  1161. initialize: function (map, options) {
  1162. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  1163. this.type = L.Draw.Rectangle.TYPE;
  1164. this._initialLabelText = L.drawLocal.draw.handlers.rectangle.tooltip.start;
  1165. L.Draw.SimpleShape.prototype.initialize.call(this, map, options);
  1166. },
  1167. // @method disable(): void
  1168. disable: function () {
  1169. if (!this._enabled) {
  1170. return;
  1171. }
  1172. this._isCurrentlyTwoClickDrawing = false;
  1173. L.Draw.SimpleShape.prototype.disable.call(this);
  1174. },
  1175. _onMouseUp: function (e) {
  1176. if (!this._shape && !this._isCurrentlyTwoClickDrawing) {
  1177. this._isCurrentlyTwoClickDrawing = true;
  1178. return;
  1179. }
  1180. // Make sure closing click is on map
  1181. if (this._isCurrentlyTwoClickDrawing && !_hasAncestor(e.target, 'leaflet-pane')) {
  1182. return;
  1183. }
  1184. L.Draw.SimpleShape.prototype._onMouseUp.call(this);
  1185. },
  1186. _drawShape: function (latlng) {
  1187. if (!this._shape) {
  1188. this._shape = new L.Rectangle(new L.LatLngBounds(this._startLatLng, latlng), this.options.shapeOptions);
  1189. this._map.addLayer(this._shape);
  1190. } else {
  1191. this._shape.setBounds(new L.LatLngBounds(this._startLatLng, latlng));
  1192. }
  1193. },
  1194. _fireCreatedEvent: function () {
  1195. var rectangle = new L.Rectangle(this._shape.getBounds(), this.options.shapeOptions);
  1196. L.Draw.SimpleShape.prototype._fireCreatedEvent.call(this, rectangle);
  1197. },
  1198. _getTooltipText: function () {
  1199. var tooltipText = L.Draw.SimpleShape.prototype._getTooltipText.call(this),
  1200. shape = this._shape,
  1201. showArea = this.options.showArea,
  1202. latLngs, area, subtext;
  1203. if (shape) {
  1204. latLngs = this._shape._defaultShape ? this._shape._defaultShape() : this._shape.getLatLngs();
  1205. area = L.GeometryUtil.geodesicArea(latLngs);
  1206. subtext = showArea ? L.GeometryUtil.readableArea(area, this.options.metric) : '';
  1207. }
  1208. return {
  1209. text: tooltipText.text,
  1210. subtext: subtext
  1211. };
  1212. }
  1213. });
  1214. function _hasAncestor(el, cls) {
  1215. while ((el = el.parentElement) && !el.classList.contains(cls)) {
  1216. ;
  1217. }
  1218. return el;
  1219. }
  1220. /**
  1221. * @class L.Draw.Marker
  1222. * @aka Draw.Marker
  1223. * @inherits L.Draw.Feature
  1224. */
  1225. L.Draw.Marker = L.Draw.Feature.extend({
  1226. statics: {
  1227. TYPE: 'marker'
  1228. },
  1229. options: {
  1230. icon: new L.Icon.Default(),
  1231. repeatMode: false,
  1232. zIndexOffset: 2000 // This should be > than the highest z-index any markers
  1233. },
  1234. // @method initialize(): void
  1235. initialize: function (map, options) {
  1236. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  1237. this.type = L.Draw.Marker.TYPE;
  1238. this._initialLabelText = L.drawLocal.draw.handlers.marker.tooltip.start;
  1239. L.Draw.Feature.prototype.initialize.call(this, map, options);
  1240. },
  1241. // @method addHooks(): void
  1242. // Add listener hooks to this handler.
  1243. addHooks: function () {
  1244. L.Draw.Feature.prototype.addHooks.call(this);
  1245. if (this._map) {
  1246. this._tooltip.updateContent({text: this._initialLabelText});
  1247. // Same mouseMarker as in Draw.Polyline
  1248. if (!this._mouseMarker) {
  1249. this._mouseMarker = L.marker(this._map.getCenter(), {
  1250. icon: L.divIcon({
  1251. className: 'leaflet-mouse-marker',
  1252. iconAnchor: [20, 20],
  1253. iconSize: [40, 40]
  1254. }),
  1255. opacity: 0,
  1256. zIndexOffset: this.options.zIndexOffset
  1257. });
  1258. }
  1259. this._mouseMarker
  1260. .on('click', this._onClick, this)
  1261. .addTo(this._map);
  1262. this._map.on('mousemove', this._onMouseMove, this);
  1263. this._map.on('click', this._onTouch, this);
  1264. }
  1265. },
  1266. // @method removeHooks(): void
  1267. // Remove listener hooks from this handler.
  1268. removeHooks: function () {
  1269. L.Draw.Feature.prototype.removeHooks.call(this);
  1270. if (this._map) {
  1271. this._map
  1272. .off('click', this._onClick, this)
  1273. .off('click', this._onTouch, this);
  1274. if (this._marker) {
  1275. this._marker.off('click', this._onClick, this);
  1276. this._map
  1277. .removeLayer(this._marker);
  1278. delete this._marker;
  1279. }
  1280. this._mouseMarker.off('click', this._onClick, this);
  1281. this._map.removeLayer(this._mouseMarker);
  1282. delete this._mouseMarker;
  1283. this._map.off('mousemove', this._onMouseMove, this);
  1284. }
  1285. },
  1286. _onMouseMove: function (e) {
  1287. var latlng = e.latlng;
  1288. this._tooltip.updatePosition(latlng);
  1289. this._mouseMarker.setLatLng(latlng);
  1290. if (!this._marker) {
  1291. this._marker = this._createMarker(latlng);
  1292. // Bind to both marker and map to make sure we get the click event.
  1293. this._marker.on('click', this._onClick, this);
  1294. this._map
  1295. .on('click', this._onClick, this)
  1296. .addLayer(this._marker);
  1297. }
  1298. else {
  1299. latlng = this._mouseMarker.getLatLng();
  1300. this._marker.setLatLng(latlng);
  1301. }
  1302. },
  1303. _createMarker: function (latlng) {
  1304. return new L.Marker(latlng, {
  1305. icon: this.options.icon,
  1306. zIndexOffset: this.options.zIndexOffset
  1307. });
  1308. },
  1309. _onClick: function () {
  1310. this._fireCreatedEvent();
  1311. this.disable();
  1312. if (this.options.repeatMode) {
  1313. this.enable();
  1314. }
  1315. },
  1316. _onTouch: function (e) {
  1317. // called on click & tap, only really does any thing on tap
  1318. this._onMouseMove(e); // creates & places marker
  1319. this._onClick(); // permanently places marker & ends interaction
  1320. },
  1321. _fireCreatedEvent: function () {
  1322. var marker = new L.Marker.Touch(this._marker.getLatLng(), {icon: this.options.icon});
  1323. L.Draw.Feature.prototype._fireCreatedEvent.call(this, marker);
  1324. }
  1325. });
  1326. /**
  1327. * @class L.Draw.CircleMarker
  1328. * @aka Draw.CircleMarker
  1329. * @inherits L.Draw.Marker
  1330. */
  1331. L.Draw.CircleMarker = L.Draw.Marker.extend({
  1332. statics: {
  1333. TYPE: 'circlemarker'
  1334. },
  1335. options: {
  1336. stroke: true,
  1337. color: '#3388ff',
  1338. weight: 4,
  1339. opacity: 0.5,
  1340. fill: true,
  1341. fillColor: null, //same as color by default
  1342. fillOpacity: 0.2,
  1343. clickable: true,
  1344. zIndexOffset: 2000 // This should be > than the highest z-index any markers
  1345. },
  1346. // @method initialize(): void
  1347. initialize: function (map, options) {
  1348. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  1349. this.type = L.Draw.CircleMarker.TYPE;
  1350. this._initialLabelText = L.drawLocal.draw.handlers.circlemarker.tooltip.start;
  1351. L.Draw.Feature.prototype.initialize.call(this, map, options);
  1352. },
  1353. _fireCreatedEvent: function () {
  1354. var circleMarker = new L.CircleMarker(this._marker.getLatLng(), this.options);
  1355. L.Draw.Feature.prototype._fireCreatedEvent.call(this, circleMarker);
  1356. },
  1357. _createMarker: function (latlng) {
  1358. return new L.CircleMarker(latlng, this.options);
  1359. }
  1360. });
  1361. /**
  1362. * @class L.Draw.Circle
  1363. * @aka Draw.Circle
  1364. * @inherits L.Draw.SimpleShape
  1365. */
  1366. L.Draw.Circle = L.Draw.SimpleShape.extend({
  1367. statics: {
  1368. TYPE: 'circle'
  1369. },
  1370. options: {
  1371. shapeOptions: {
  1372. stroke: true,
  1373. color: '#3388ff',
  1374. weight: 4,
  1375. opacity: 0.5,
  1376. fill: true,
  1377. fillColor: null, //same as color by default
  1378. fillOpacity: 0.2,
  1379. clickable: true
  1380. },
  1381. showRadius: true,
  1382. metric: true, // Whether to use the metric measurement system or imperial
  1383. feet: true, // When not metric, use feet instead of yards for display
  1384. nautic: false // When not metric, not feet use nautic mile for display
  1385. },
  1386. // @method initialize(): void
  1387. initialize: function (map, options) {
  1388. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  1389. this.type = L.Draw.Circle.TYPE;
  1390. this._initialLabelText = L.drawLocal.draw.handlers.circle.tooltip.start;
  1391. L.Draw.SimpleShape.prototype.initialize.call(this, map, options);
  1392. },
  1393. _drawShape: function (latlng) {
  1394. // Calculate the distance based on the version
  1395. if (L.GeometryUtil.isVersion07x()) {
  1396. var distance = this._startLatLng.distanceTo(latlng);
  1397. } else {
  1398. var distance = this._map.distance(this._startLatLng, latlng);
  1399. }
  1400. if (!this._shape) {
  1401. this._shape = new L.Circle(this._startLatLng, distance, this.options.shapeOptions);
  1402. this._map.addLayer(this._shape);
  1403. } else {
  1404. this._shape.setRadius(distance);
  1405. }
  1406. },
  1407. _fireCreatedEvent: function () {
  1408. var circle = new L.Circle(this._startLatLng, this._shape.getRadius(), this.options.shapeOptions);
  1409. L.Draw.SimpleShape.prototype._fireCreatedEvent.call(this, circle);
  1410. },
  1411. _onMouseMove: function (e) {
  1412. var latlng = e.latlng,
  1413. showRadius = this.options.showRadius,
  1414. useMetric = this.options.metric,
  1415. radius;
  1416. this._tooltip.updatePosition(latlng);
  1417. if (this._isDrawing) {
  1418. this._drawShape(latlng);
  1419. // Get the new radius (rounded to 1 dp)
  1420. radius = this._shape.getRadius().toFixed(1);
  1421. var subtext = '';
  1422. if (showRadius) {
  1423. subtext = L.drawLocal.draw.handlers.circle.radius + ': ' +
  1424. L.GeometryUtil.readableDistance(radius, useMetric, this.options.feet, this.options.nautic);
  1425. }
  1426. this._tooltip.updateContent({
  1427. text: this._endLabelText,
  1428. subtext: subtext
  1429. });
  1430. }
  1431. }
  1432. });
  1433. L.Edit = L.Edit || {};
  1434. /**
  1435. * @class L.Edit.Marker
  1436. * @aka Edit.Marker
  1437. */
  1438. L.Edit.Marker = L.Handler.extend({
  1439. // @method initialize(): void
  1440. initialize: function (marker, options) {
  1441. this._marker = marker;
  1442. L.setOptions(this, options);
  1443. },
  1444. // @method addHooks(): void
  1445. // Add listener hooks to this handler
  1446. addHooks: function () {
  1447. var marker = this._marker;
  1448. marker.dragging.enable();
  1449. marker.on('dragend', this._onDragEnd, marker);
  1450. this._toggleMarkerHighlight();
  1451. },
  1452. // @method removeHooks(): void
  1453. // Remove listener hooks from this handler
  1454. removeHooks: function () {
  1455. var marker = this._marker;
  1456. marker.dragging.disable();
  1457. marker.off('dragend', this._onDragEnd, marker);
  1458. this._toggleMarkerHighlight();
  1459. },
  1460. _onDragEnd: function (e) {
  1461. var layer = e.target;
  1462. layer.edited = true;
  1463. this._map.fire(L.Draw.Event.EDITMOVE, {layer: layer});
  1464. },
  1465. _toggleMarkerHighlight: function () {
  1466. var icon = this._marker._icon;
  1467. // Don't do anything if this layer is a marker but doesn't have an icon. Markers
  1468. // should usually have icons. If using Leaflet.draw with Leaflet.markercluster there
  1469. // is a chance that a marker doesn't.
  1470. if (!icon) {
  1471. return;
  1472. }
  1473. // This is quite naughty, but I don't see another way of doing it. (short of setting a new icon)
  1474. icon.style.display = 'none';
  1475. if (L.DomUtil.hasClass(icon, 'leaflet-edit-marker-selected')) {
  1476. L.DomUtil.removeClass(icon, 'leaflet-edit-marker-selected');
  1477. // Offset as the border will make the icon move.
  1478. this._offsetMarker(icon, -4);
  1479. } else {
  1480. L.DomUtil.addClass(icon, 'leaflet-edit-marker-selected');
  1481. // Offset as the border will make the icon move.
  1482. this._offsetMarker(icon, 4);
  1483. }
  1484. icon.style.display = '';
  1485. },
  1486. _offsetMarker: function (icon, offset) {
  1487. var iconMarginTop = parseInt(icon.style.marginTop, 10) - offset,
  1488. iconMarginLeft = parseInt(icon.style.marginLeft, 10) - offset;
  1489. icon.style.marginTop = iconMarginTop + 'px';
  1490. icon.style.marginLeft = iconMarginLeft + 'px';
  1491. }
  1492. });
  1493. L.Marker.addInitHook(function () {
  1494. if (L.Edit.Marker) {
  1495. this.editing = new L.Edit.Marker(this);
  1496. if (this.options.editable) {
  1497. this.editing.enable();
  1498. }
  1499. }
  1500. });
  1501. L.Edit = L.Edit || {};
  1502. /**
  1503. * @class L.Edit.Polyline
  1504. * @aka L.Edit.Poly
  1505. * @aka Edit.Poly
  1506. */
  1507. L.Edit.Poly = L.Handler.extend({
  1508. // @method initialize(): void
  1509. initialize: function (poly) {
  1510. this.latlngs = [poly._latlngs];
  1511. if (poly._holes) {
  1512. this.latlngs = this.latlngs.concat(poly._holes);
  1513. }
  1514. this._poly = poly;
  1515. this._poly.on('revert-edited', this._updateLatLngs, this);
  1516. },
  1517. // Compatibility method to normalize Poly* objects
  1518. // between 0.7.x and 1.0+
  1519. _defaultShape: function () {
  1520. if (!L.Polyline._flat) {
  1521. return this._poly._latlngs;
  1522. }
  1523. return L.Polyline._flat(this._poly._latlngs) ? this._poly._latlngs : this._poly._latlngs[0];
  1524. },
  1525. _eachVertexHandler: function (callback) {
  1526. for (var i = 0; i < this._verticesHandlers.length; i++) {
  1527. callback(this._verticesHandlers[i]);
  1528. }
  1529. },
  1530. // @method addHooks(): void
  1531. // Add listener hooks to this handler
  1532. addHooks: function () {
  1533. this._initHandlers();
  1534. this._eachVertexHandler(function (handler) {
  1535. handler.addHooks();
  1536. });
  1537. },
  1538. // @method removeHooks(): void
  1539. // Remove listener hooks from this handler
  1540. removeHooks: function () {
  1541. this._eachVertexHandler(function (handler) {
  1542. handler.removeHooks();
  1543. });
  1544. },
  1545. // @method updateMarkers(): void
  1546. // Fire an update for each vertex handler
  1547. updateMarkers: function () {
  1548. this._eachVertexHandler(function (handler) {
  1549. handler.updateMarkers();
  1550. });
  1551. },
  1552. _initHandlers: function () {
  1553. this._verticesHandlers = [];
  1554. for (var i = 0; i < this.latlngs.length; i++) {
  1555. this._verticesHandlers.push(new L.Edit.PolyVerticesEdit(this._poly, this.latlngs[i], this._poly.options.poly));
  1556. }
  1557. },
  1558. _updateLatLngs: function (e) {
  1559. this.latlngs = [e.layer._latlngs];
  1560. if (e.layer._holes) {
  1561. this.latlngs = this.latlngs.concat(e.layer._holes);
  1562. }
  1563. }
  1564. });
  1565. /**
  1566. * @class L.Edit.PolyVerticesEdit
  1567. * @aka Edit.PolyVerticesEdit
  1568. */
  1569. L.Edit.PolyVerticesEdit = L.Handler.extend({
  1570. options: {
  1571. icon: new L.DivIcon({
  1572. iconSize: new L.Point(8, 8),
  1573. className: 'leaflet-div-icon leaflet-editing-icon'
  1574. }),
  1575. touchIcon: new L.DivIcon({
  1576. iconSize: new L.Point(20, 20),
  1577. className: 'leaflet-div-icon leaflet-editing-icon leaflet-touch-icon'
  1578. }),
  1579. drawError: {
  1580. color: '#b00b00',
  1581. timeout: 1000
  1582. }
  1583. },
  1584. // @method intialize(): void
  1585. initialize: function (poly, latlngs, options) {
  1586. // if touch, switch to touch icon
  1587. if (L.Browser.touch) {
  1588. this.options.icon = this.options.touchIcon;
  1589. }
  1590. this._poly = poly;
  1591. if (options && options.drawError) {
  1592. options.drawError = L.Util.extend({}, this.options.drawError, options.drawError);
  1593. }
  1594. this._latlngs = latlngs;
  1595. L.setOptions(this, options);
  1596. },
  1597. // Compatibility method to normalize Poly* objects
  1598. // between 0.7.x and 1.0+
  1599. _defaultShape: function () {
  1600. if (!L.Polyline._flat) {
  1601. return this._latlngs;
  1602. }
  1603. return L.Polyline._flat(this._latlngs) ? this._latlngs : this._latlngs[0];
  1604. },
  1605. // @method addHooks(): void
  1606. // Add listener hooks to this handler.
  1607. addHooks: function () {
  1608. var poly = this._poly;
  1609. var path = poly._path;
  1610. if (!(poly instanceof L.Polygon)) {
  1611. poly.options.fill = false;
  1612. if (poly.options.editing) {
  1613. poly.options.editing.fill = false;
  1614. }
  1615. }
  1616. if (path) {
  1617. if (poly.options.editing.className) {
  1618. if (poly.options.original.className) {
  1619. poly.options.original.className.split(' ').forEach(function (className) {
  1620. L.DomUtil.removeClass(path, className);
  1621. });
  1622. }
  1623. poly.options.editing.className.split(' ').forEach(function (className) {
  1624. L.DomUtil.addClass(path, className);
  1625. });
  1626. }
  1627. }
  1628. poly.setStyle(poly.options.editing);
  1629. if (this._poly._map) {
  1630. this._map = this._poly._map; // Set map
  1631. if (!this._markerGroup) {
  1632. this._initMarkers();
  1633. }
  1634. this._poly._map.addLayer(this._markerGroup);
  1635. }
  1636. },
  1637. // @method removeHooks(): void
  1638. // Remove listener hooks from this handler.
  1639. removeHooks: function () {
  1640. var poly = this._poly;
  1641. var path = poly._path;
  1642. if (path) {
  1643. if (poly.options.editing.className) {
  1644. poly.options.editing.className.split(' ').forEach(function (className) {
  1645. L.DomUtil.removeClass(path, className);
  1646. });
  1647. if (poly.options.original.className) {
  1648. poly.options.original.className.split(' ').forEach(function (className) {
  1649. L.DomUtil.addClass(path, className);
  1650. });
  1651. }
  1652. }
  1653. }
  1654. poly.setStyle(poly.options.original);
  1655. if (poly._map) {
  1656. poly._map.removeLayer(this._markerGroup);
  1657. delete this._markerGroup;
  1658. delete this._markers;
  1659. }
  1660. },
  1661. // @method updateMarkers(): void
  1662. // Clear markers and update their location
  1663. updateMarkers: function () {
  1664. this._markerGroup.clearLayers();
  1665. this._initMarkers();
  1666. },
  1667. _initMarkers: function () {
  1668. if (!this._markerGroup) {
  1669. this._markerGroup = new L.LayerGroup();
  1670. }
  1671. this._markers = [];
  1672. var latlngs = this._defaultShape(),
  1673. i, j, len, marker;
  1674. for (i = 0, len = latlngs.length; i < len; i++) {
  1675. marker = this._createMarker(latlngs[i], i);
  1676. marker.on('click', this._onMarkerClick, this);
  1677. marker.on('contextmenu', this._onContextMenu, this);
  1678. this._markers.push(marker);
  1679. }
  1680. var markerLeft, markerRight;
  1681. for (i = 0, j = len - 1; i < len; j = i++) {
  1682. if (i === 0 && !(L.Polygon && (this._poly instanceof L.Polygon))) {
  1683. continue;
  1684. }
  1685. markerLeft = this._markers[j];
  1686. markerRight = this._markers[i];
  1687. this._createMiddleMarker(markerLeft, markerRight);
  1688. this._updatePrevNext(markerLeft, markerRight);
  1689. }
  1690. },
  1691. _createMarker: function (latlng, index) {
  1692. // Extending L.Marker in TouchEvents.js to include touch.
  1693. var marker = new L.Marker.Touch(latlng, {
  1694. draggable: true,
  1695. icon: this.options.icon,
  1696. });
  1697. marker._origLatLng = latlng;
  1698. marker._index = index;
  1699. marker
  1700. .on('dragstart', this._onMarkerDragStart, this)
  1701. .on('drag', this._onMarkerDrag, this)
  1702. .on('dragend', this._fireEdit, this)
  1703. .on('touchmove', this._onTouchMove, this)
  1704. .on('touchend', this._fireEdit, this)
  1705. .on('MSPointerMove', this._onTouchMove, this)
  1706. .on('MSPointerUp', this._fireEdit, this);
  1707. this._markerGroup.addLayer(marker);
  1708. return marker;
  1709. },
  1710. _onMarkerDragStart: function () {
  1711. this._poly.fire('editstart');
  1712. },
  1713. _spliceLatLngs: function () {
  1714. var latlngs = this._defaultShape();
  1715. var removed = [].splice.apply(latlngs, arguments);
  1716. this._poly._convertLatLngs(latlngs, true);
  1717. this._poly.redraw();
  1718. return removed;
  1719. },
  1720. _removeMarker: function (marker) {
  1721. var i = marker._index;
  1722. this._markerGroup.removeLayer(marker);
  1723. this._markers.splice(i, 1);
  1724. this._spliceLatLngs(i, 1);
  1725. this._updateIndexes(i, -1);
  1726. marker
  1727. .off('dragstart', this._onMarkerDragStart, this)
  1728. .off('drag', this._onMarkerDrag, this)
  1729. .off('dragend', this._fireEdit, this)
  1730. .off('touchmove', this._onMarkerDrag, this)
  1731. .off('touchend', this._fireEdit, this)
  1732. .off('click', this._onMarkerClick, this)
  1733. .off('MSPointerMove', this._onTouchMove, this)
  1734. .off('MSPointerUp', this._fireEdit, this);
  1735. },
  1736. _fireEdit: function () {
  1737. this._poly.edited = true;
  1738. this._poly.fire('edit');
  1739. this._poly._map.fire(L.Draw.Event.EDITVERTEX, {layers: this._markerGroup, poly: this._poly});
  1740. },
  1741. _onMarkerDrag: function (e) {
  1742. var marker = e.target;
  1743. var poly = this._poly;
  1744. L.extend(marker._origLatLng, marker._latlng);
  1745. if (marker._middleLeft) {
  1746. marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
  1747. }
  1748. if (marker._middleRight) {
  1749. marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
  1750. }
  1751. if (poly.options.poly) {
  1752. var tooltip = poly._map._editTooltip; // Access the tooltip
  1753. // If we don't allow intersections and the polygon intersects
  1754. if (!poly.options.poly.allowIntersection && poly.intersects()) {
  1755. var originalColor = poly.options.color;
  1756. poly.setStyle({color: this.options.drawError.color});
  1757. // Manually trigger 'dragend' behavior on marker we are about to remove
  1758. // WORKAROUND: introduced in 1.0.0-rc2, may be related to #4484
  1759. if (L.version.indexOf('0.7') !== 0) {
  1760. marker.dragging._draggable._onUp(e);
  1761. }
  1762. this._onMarkerClick(e); // Remove violating marker
  1763. // FIXME: Reset the marker to it's original position (instead of remove)
  1764. if (tooltip) {
  1765. tooltip.updateContent({
  1766. text: L.drawLocal.draw.handlers.polyline.error
  1767. });
  1768. }
  1769. // Reset everything back to normal after a second
  1770. setTimeout(function () {
  1771. poly.setStyle({color: originalColor});
  1772. if (tooltip) {
  1773. tooltip.updateContent({
  1774. text: L.drawLocal.edit.handlers.edit.tooltip.text,
  1775. subtext: L.drawLocal.edit.handlers.edit.tooltip.subtext
  1776. });
  1777. }
  1778. }, 1000);
  1779. }
  1780. }
  1781. //refresh the bounds when draging
  1782. this._poly._bounds._southWest = L.latLng(Infinity, Infinity);
  1783. this._poly._bounds._northEast = L.latLng(-Infinity, -Infinity);
  1784. var latlngs = this._poly.getLatLngs();
  1785. this._poly._convertLatLngs(latlngs, true);
  1786. this._poly.redraw();
  1787. this._poly.fire('editdrag');
  1788. },
  1789. _onMarkerClick: function (e) {
  1790. var minPoints = L.Polygon && (this._poly instanceof L.Polygon) ? 4 : 3,
  1791. marker = e.target;
  1792. // If removing this point would create an invalid polyline/polygon don't remove
  1793. if (this._defaultShape().length < minPoints) {
  1794. return;
  1795. }
  1796. // remove the marker
  1797. this._removeMarker(marker);
  1798. // update prev/next links of adjacent markers
  1799. this._updatePrevNext(marker._prev, marker._next);
  1800. // remove ghost markers near the removed marker
  1801. if (marker._middleLeft) {
  1802. this._markerGroup.removeLayer(marker._middleLeft);
  1803. }
  1804. if (marker._middleRight) {
  1805. this._markerGroup.removeLayer(marker._middleRight);
  1806. }
  1807. // create a ghost marker in place of the removed one
  1808. if (marker._prev && marker._next) {
  1809. this._createMiddleMarker(marker._prev, marker._next);
  1810. } else if (!marker._prev) {
  1811. marker._next._middleLeft = null;
  1812. } else if (!marker._next) {
  1813. marker._prev._middleRight = null;
  1814. }
  1815. this._fireEdit();
  1816. },
  1817. _onContextMenu: function (e) {
  1818. var marker = e.target;
  1819. var poly = this._poly;
  1820. this._poly._map.fire(L.Draw.Event.MARKERCONTEXT, {marker: marker, layers: this._markerGroup, poly: this._poly});
  1821. L.DomEvent.stopPropagation;
  1822. },
  1823. _onTouchMove: function (e) {
  1824. var layerPoint = this._map.mouseEventToLayerPoint(e.originalEvent.touches[0]),
  1825. latlng = this._map.layerPointToLatLng(layerPoint),
  1826. marker = e.target;
  1827. L.extend(marker._origLatLng, latlng);
  1828. if (marker._middleLeft) {
  1829. marker._middleLeft.setLatLng(this._getMiddleLatLng(marker._prev, marker));
  1830. }
  1831. if (marker._middleRight) {
  1832. marker._middleRight.setLatLng(this._getMiddleLatLng(marker, marker._next));
  1833. }
  1834. this._poly.redraw();
  1835. this.updateMarkers();
  1836. },
  1837. _updateIndexes: function (index, delta) {
  1838. this._markerGroup.eachLayer(function (marker) {
  1839. if (marker._index > index) {
  1840. marker._index += delta;
  1841. }
  1842. });
  1843. },
  1844. _createMiddleMarker: function (marker1, marker2) {
  1845. var latlng = this._getMiddleLatLng(marker1, marker2),
  1846. marker = this._createMarker(latlng),
  1847. onClick,
  1848. onDragStart,
  1849. onDragEnd;
  1850. marker.setOpacity(0.6);
  1851. marker1._middleRight = marker2._middleLeft = marker;
  1852. onDragStart = function () {
  1853. marker.off('touchmove', onDragStart, this);
  1854. var i = marker2._index;
  1855. marker._index = i;
  1856. marker
  1857. .off('click', onClick, this)
  1858. .on('click', this._onMarkerClick, this);
  1859. latlng.lat = marker.getLatLng().lat;
  1860. latlng.lng = marker.getLatLng().lng;
  1861. this._spliceLatLngs(i, 0, latlng);
  1862. this._markers.splice(i, 0, marker);
  1863. marker.setOpacity(1);
  1864. this._updateIndexes(i, 1);
  1865. marker2._index++;
  1866. this._updatePrevNext(marker1, marker);
  1867. this._updatePrevNext(marker, marker2);
  1868. this._poly.fire('editstart');
  1869. };
  1870. onDragEnd = function () {
  1871. marker.off('dragstart', onDragStart, this);
  1872. marker.off('dragend', onDragEnd, this);
  1873. marker.off('touchmove', onDragStart, this);
  1874. this._createMiddleMarker(marker1, marker);
  1875. this._createMiddleMarker(marker, marker2);
  1876. };
  1877. onClick = function () {
  1878. onDragStart.call(this);
  1879. onDragEnd.call(this);
  1880. this._fireEdit();
  1881. };
  1882. marker
  1883. .on('click', onClick, this)
  1884. .on('dragstart', onDragStart, this)
  1885. .on('dragend', onDragEnd, this)
  1886. .on('touchmove', onDragStart, this);
  1887. this._markerGroup.addLayer(marker);
  1888. },
  1889. _updatePrevNext: function (marker1, marker2) {
  1890. if (marker1) {
  1891. marker1._next = marker2;
  1892. }
  1893. if (marker2) {
  1894. marker2._prev = marker1;
  1895. }
  1896. },
  1897. _getMiddleLatLng: function (marker1, marker2) {
  1898. var map = this._poly._map,
  1899. p1 = map.project(marker1.getLatLng()),
  1900. p2 = map.project(marker2.getLatLng());
  1901. return map.unproject(p1._add(p2)._divideBy(2));
  1902. }
  1903. });
  1904. L.Polyline.addInitHook(function () {
  1905. // Check to see if handler has already been initialized. This is to support versions of Leaflet that still have L.Handler.PolyEdit
  1906. if (this.editing) {
  1907. return;
  1908. }
  1909. if (L.Edit.Poly) {
  1910. this.editing = new L.Edit.Poly(this);
  1911. if (this.options.editable) {
  1912. this.editing.enable();
  1913. }
  1914. }
  1915. this.on('add', function () {
  1916. if (this.editing && this.editing.enabled()) {
  1917. this.editing.addHooks();
  1918. }
  1919. });
  1920. this.on('remove', function () {
  1921. if (this.editing && this.editing.enabled()) {
  1922. this.editing.removeHooks();
  1923. }
  1924. });
  1925. });
  1926. L.Edit = L.Edit || {};
  1927. /**
  1928. * @class L.Edit.SimpleShape
  1929. * @aka Edit.SimpleShape
  1930. */
  1931. L.Edit.SimpleShape = L.Handler.extend({
  1932. options: {
  1933. moveIcon: new L.DivIcon({
  1934. iconSize: new L.Point(8, 8),
  1935. className: 'leaflet-div-icon leaflet-editing-icon leaflet-edit-move'
  1936. }),
  1937. resizeIcon: new L.DivIcon({
  1938. iconSize: new L.Point(8, 8),
  1939. className: 'leaflet-div-icon leaflet-editing-icon leaflet-edit-resize'
  1940. }),
  1941. touchMoveIcon: new L.DivIcon({
  1942. iconSize: new L.Point(20, 20),
  1943. className: 'leaflet-div-icon leaflet-editing-icon leaflet-edit-move leaflet-touch-icon'
  1944. }),
  1945. touchResizeIcon: new L.DivIcon({
  1946. iconSize: new L.Point(20, 20),
  1947. className: 'leaflet-div-icon leaflet-editing-icon leaflet-edit-resize leaflet-touch-icon'
  1948. }),
  1949. },
  1950. // @method intialize(): void
  1951. initialize: function (shape, options) {
  1952. // if touch, switch to touch icon
  1953. if (L.Browser.touch) {
  1954. this.options.moveIcon = this.options.touchMoveIcon;
  1955. this.options.resizeIcon = this.options.touchResizeIcon;
  1956. }
  1957. this._shape = shape;
  1958. L.Util.setOptions(this, options);
  1959. },
  1960. // @method addHooks(): void
  1961. // Add listener hooks to this handler
  1962. addHooks: function () {
  1963. var shape = this._shape;
  1964. if (this._shape._map) {
  1965. this._map = this._shape._map;
  1966. shape.setStyle(shape.options.editing);
  1967. if (shape._map) {
  1968. this._map = shape._map;
  1969. if (!this._markerGroup) {
  1970. this._initMarkers();
  1971. }
  1972. this._map.addLayer(this._markerGroup);
  1973. }
  1974. }
  1975. },
  1976. // @method removeHooks(): void
  1977. // Remove listener hooks from this handler
  1978. removeHooks: function () {
  1979. var shape = this._shape;
  1980. shape.setStyle(shape.options.original);
  1981. if (shape._map) {
  1982. this._unbindMarker(this._moveMarker);
  1983. for (var i = 0, l = this._resizeMarkers.length; i < l; i++) {
  1984. this._unbindMarker(this._resizeMarkers[i]);
  1985. }
  1986. this._resizeMarkers = null;
  1987. this._map.removeLayer(this._markerGroup);
  1988. delete this._markerGroup;
  1989. }
  1990. this._map = null;
  1991. },
  1992. // @method updateMarkers(): void
  1993. // Remove the edit markers from this layer
  1994. updateMarkers: function () {
  1995. this._markerGroup.clearLayers();
  1996. this._initMarkers();
  1997. },
  1998. _initMarkers: function () {
  1999. if (!this._markerGroup) {
  2000. this._markerGroup = new L.LayerGroup();
  2001. }
  2002. // Create center marker
  2003. this._createMoveMarker();
  2004. // Create edge marker
  2005. this._createResizeMarker();
  2006. },
  2007. _createMoveMarker: function () {
  2008. // Children override
  2009. },
  2010. _createResizeMarker: function () {
  2011. // Children override
  2012. },
  2013. _createMarker: function (latlng, icon) {
  2014. // Extending L.Marker in TouchEvents.js to include touch.
  2015. var marker = new L.Marker.Touch(latlng, {
  2016. draggable: true,
  2017. icon: icon,
  2018. zIndexOffset: 10
  2019. });
  2020. this._bindMarker(marker);
  2021. this._markerGroup.addLayer(marker);
  2022. return marker;
  2023. },
  2024. _bindMarker: function (marker) {
  2025. marker
  2026. .on('dragstart', this._onMarkerDragStart, this)
  2027. .on('drag', this._onMarkerDrag, this)
  2028. .on('dragend', this._onMarkerDragEnd, this)
  2029. .on('touchstart', this._onTouchStart, this)
  2030. .on('touchmove', this._onTouchMove, this)
  2031. .on('MSPointerMove', this._onTouchMove, this)
  2032. .on('touchend', this._onTouchEnd, this)
  2033. .on('MSPointerUp', this._onTouchEnd, this);
  2034. },
  2035. _unbindMarker: function (marker) {
  2036. marker
  2037. .off('dragstart', this._onMarkerDragStart, this)
  2038. .off('drag', this._onMarkerDrag, this)
  2039. .off('dragend', this._onMarkerDragEnd, this)
  2040. .off('touchstart', this._onTouchStart, this)
  2041. .off('touchmove', this._onTouchMove, this)
  2042. .off('MSPointerMove', this._onTouchMove, this)
  2043. .off('touchend', this._onTouchEnd, this)
  2044. .off('MSPointerUp', this._onTouchEnd, this);
  2045. },
  2046. _onMarkerDragStart: function (e) {
  2047. var marker = e.target;
  2048. marker.setOpacity(0);
  2049. this._shape.fire('editstart');
  2050. },
  2051. _fireEdit: function () {
  2052. this._shape.edited = true;
  2053. this._shape.fire('edit');
  2054. },
  2055. _onMarkerDrag: function (e) {
  2056. var marker = e.target,
  2057. latlng = marker.getLatLng();
  2058. if (marker === this._moveMarker) {
  2059. this._move(latlng);
  2060. } else {
  2061. this._resize(latlng);
  2062. }
  2063. this._shape.redraw();
  2064. this._shape.fire('editdrag');
  2065. },
  2066. _onMarkerDragEnd: function (e) {
  2067. var marker = e.target;
  2068. marker.setOpacity(1);
  2069. this._fireEdit();
  2070. },
  2071. _onTouchStart: function (e) {
  2072. L.Edit.SimpleShape.prototype._onMarkerDragStart.call(this, e);
  2073. if (typeof(this._getCorners) === 'function') {
  2074. // Save a reference to the opposite point
  2075. var corners = this._getCorners(),
  2076. marker = e.target,
  2077. currentCornerIndex = marker._cornerIndex;
  2078. marker.setOpacity(0);
  2079. // Copyed from Edit.Rectangle.js line 23 _onMarkerDragStart()
  2080. // Latlng is null otherwise.
  2081. this._oppositeCorner = corners[(currentCornerIndex + 2) % 4];
  2082. this._toggleCornerMarkers(0, currentCornerIndex);
  2083. }
  2084. this._shape.fire('editstart');
  2085. },
  2086. _onTouchMove: function (e) {
  2087. var layerPoint = this._map.mouseEventToLayerPoint(e.originalEvent.touches[0]),
  2088. latlng = this._map.layerPointToLatLng(layerPoint),
  2089. marker = e.target;
  2090. if (marker === this._moveMarker) {
  2091. this._move(latlng);
  2092. } else {
  2093. this._resize(latlng);
  2094. }
  2095. this._shape.redraw();
  2096. // prevent touchcancel in IOS
  2097. // e.preventDefault();
  2098. return false;
  2099. },
  2100. _onTouchEnd: function (e) {
  2101. var marker = e.target;
  2102. marker.setOpacity(1);
  2103. this.updateMarkers();
  2104. this._fireEdit();
  2105. },
  2106. _move: function () {
  2107. // Children override
  2108. },
  2109. _resize: function () {
  2110. // Children override
  2111. }
  2112. });
  2113. L.Edit = L.Edit || {};
  2114. /**
  2115. * @class L.Edit.Rectangle
  2116. * @aka Edit.Rectangle
  2117. * @inherits L.Edit.SimpleShape
  2118. */
  2119. L.Edit.Rectangle = L.Edit.SimpleShape.extend({
  2120. _createMoveMarker: function () {
  2121. var bounds = this._shape.getBounds(),
  2122. center = bounds.getCenter();
  2123. this._moveMarker = this._createMarker(center, this.options.moveIcon);
  2124. },
  2125. _createResizeMarker: function () {
  2126. var corners = this._getCorners();
  2127. this._resizeMarkers = [];
  2128. for (var i = 0, l = corners.length; i < l; i++) {
  2129. this._resizeMarkers.push(this._createMarker(corners[i], this.options.resizeIcon));
  2130. // Monkey in the corner index as we will need to know this for dragging
  2131. this._resizeMarkers[i]._cornerIndex = i;
  2132. }
  2133. },
  2134. _onMarkerDragStart: function (e) {
  2135. L.Edit.SimpleShape.prototype._onMarkerDragStart.call(this, e);
  2136. // Save a reference to the opposite point
  2137. var corners = this._getCorners(),
  2138. marker = e.target,
  2139. currentCornerIndex = marker._cornerIndex;
  2140. this._oppositeCorner = corners[(currentCornerIndex + 2) % 4];
  2141. this._toggleCornerMarkers(0, currentCornerIndex);
  2142. },
  2143. _onMarkerDragEnd: function (e) {
  2144. var marker = e.target,
  2145. bounds, center;
  2146. // Reset move marker position to the center
  2147. if (marker === this._moveMarker) {
  2148. bounds = this._shape.getBounds();
  2149. center = bounds.getCenter();
  2150. marker.setLatLng(center);
  2151. }
  2152. this._toggleCornerMarkers(1);
  2153. this._repositionCornerMarkers();
  2154. L.Edit.SimpleShape.prototype._onMarkerDragEnd.call(this, e);
  2155. },
  2156. _move: function (newCenter) {
  2157. var latlngs = this._shape._defaultShape ? this._shape._defaultShape() : this._shape.getLatLngs(),
  2158. bounds = this._shape.getBounds(),
  2159. center = bounds.getCenter(),
  2160. offset, newLatLngs = [];
  2161. // Offset the latlngs to the new center
  2162. for (var i = 0, l = latlngs.length; i < l; i++) {
  2163. offset = [latlngs[i].lat - center.lat, latlngs[i].lng - center.lng];
  2164. newLatLngs.push([newCenter.lat + offset[0], newCenter.lng + offset[1]]);
  2165. }
  2166. this._shape.setLatLngs(newLatLngs);
  2167. // Reposition the resize markers
  2168. this._repositionCornerMarkers();
  2169. this._map.fire(L.Draw.Event.EDITMOVE, {layer: this._shape});
  2170. },
  2171. _resize: function (latlng) {
  2172. var bounds;
  2173. // Update the shape based on the current position of this corner and the opposite point
  2174. this._shape.setBounds(L.latLngBounds(latlng, this._oppositeCorner));
  2175. // Reposition the move marker
  2176. bounds = this._shape.getBounds();
  2177. this._moveMarker.setLatLng(bounds.getCenter());
  2178. this._map.fire(L.Draw.Event.EDITRESIZE, {layer: this._shape});
  2179. },
  2180. _getCorners: function () {
  2181. var bounds = this._shape.getBounds(),
  2182. nw = bounds.getNorthWest(),
  2183. ne = bounds.getNorthEast(),
  2184. se = bounds.getSouthEast(),
  2185. sw = bounds.getSouthWest();
  2186. return [nw, ne, se, sw];
  2187. },
  2188. _toggleCornerMarkers: function (opacity) {
  2189. for (var i = 0, l = this._resizeMarkers.length; i < l; i++) {
  2190. this._resizeMarkers[i].setOpacity(opacity);
  2191. }
  2192. },
  2193. _repositionCornerMarkers: function () {
  2194. var corners = this._getCorners();
  2195. for (var i = 0, l = this._resizeMarkers.length; i < l; i++) {
  2196. this._resizeMarkers[i].setLatLng(corners[i]);
  2197. }
  2198. }
  2199. });
  2200. L.Rectangle.addInitHook(function () {
  2201. if (L.Edit.Rectangle) {
  2202. this.editing = new L.Edit.Rectangle(this);
  2203. if (this.options.editable) {
  2204. this.editing.enable();
  2205. }
  2206. }
  2207. });
  2208. L.Edit = L.Edit || {};
  2209. /**
  2210. * @class L.Edit.CircleMarker
  2211. * @aka Edit.Circle
  2212. * @inherits L.Edit.SimpleShape
  2213. */
  2214. L.Edit.CircleMarker = L.Edit.SimpleShape.extend({
  2215. _createMoveMarker: function () {
  2216. var center = this._shape.getLatLng();
  2217. this._moveMarker = this._createMarker(center, this.options.moveIcon);
  2218. },
  2219. _createResizeMarker: function () {
  2220. // To avoid an undefined check in L.Edit.SimpleShape.removeHooks
  2221. this._resizeMarkers = [];
  2222. },
  2223. _move: function (latlng) {
  2224. if (this._resizeMarkers.length) {
  2225. var resizemarkerPoint = this._getResizeMarkerPoint(latlng);
  2226. // Move the resize marker
  2227. this._resizeMarkers[0].setLatLng(resizemarkerPoint);
  2228. }
  2229. // Move the circle
  2230. this._shape.setLatLng(latlng);
  2231. this._map.fire(L.Draw.Event.EDITMOVE, {layer: this._shape});
  2232. },
  2233. });
  2234. L.CircleMarker.addInitHook(function () {
  2235. if (L.Edit.CircleMarker) {
  2236. this.editing = new L.Edit.CircleMarker(this);
  2237. if (this.options.editable) {
  2238. this.editing.enable();
  2239. }
  2240. }
  2241. this.on('add', function () {
  2242. if (this.editing && this.editing.enabled()) {
  2243. this.editing.addHooks();
  2244. }
  2245. });
  2246. this.on('remove', function () {
  2247. if (this.editing && this.editing.enabled()) {
  2248. this.editing.removeHooks();
  2249. }
  2250. });
  2251. });
  2252. L.Edit = L.Edit || {};
  2253. /**
  2254. * @class L.Edit.Circle
  2255. * @aka Edit.Circle
  2256. * @inherits L.Edit.CircleMarker
  2257. */
  2258. L.Edit.Circle = L.Edit.CircleMarker.extend({
  2259. _createResizeMarker: function () {
  2260. var center = this._shape.getLatLng(),
  2261. resizemarkerPoint = this._getResizeMarkerPoint(center);
  2262. this._resizeMarkers = [];
  2263. this._resizeMarkers.push(this._createMarker(resizemarkerPoint, this.options.resizeIcon));
  2264. },
  2265. _getResizeMarkerPoint: function (latlng) {
  2266. // From L.shape.getBounds()
  2267. var delta = this._shape._radius * Math.cos(Math.PI / 4),
  2268. point = this._map.project(latlng);
  2269. return this._map.unproject([point.x + delta, point.y - delta]);
  2270. },
  2271. _resize: function (latlng) {
  2272. var moveLatLng = this._moveMarker.getLatLng();
  2273. // Calculate the radius based on the version
  2274. if (L.GeometryUtil.isVersion07x()) {
  2275. radius = moveLatLng.distanceTo(latlng);
  2276. } else {
  2277. radius = this._map.distance(moveLatLng, latlng);
  2278. }
  2279. this._shape.setRadius(radius);
  2280. this._map._editTooltip.updateContent({
  2281. text: L.drawLocal.edit.handlers.edit.tooltip.subtext + '<br />' + L.drawLocal.edit.handlers.edit.tooltip.text,
  2282. subtext: L.drawLocal.draw.handlers.circle.radius + ': ' +
  2283. L.GeometryUtil.readableDistance(radius, true, this.options.feet, this.options.nautic)
  2284. });
  2285. this._shape.setRadius(radius);
  2286. this._map.fire(L.Draw.Event.EDITRESIZE, {layer: this._shape});
  2287. }
  2288. });
  2289. L.Circle.addInitHook(function () {
  2290. if (L.Edit.Circle) {
  2291. this.editing = new L.Edit.Circle(this);
  2292. if (this.options.editable) {
  2293. this.editing.enable();
  2294. }
  2295. }
  2296. this.on('add', function () {
  2297. if (this.editing && this.editing.enabled()) {
  2298. this.editing.addHooks();
  2299. }
  2300. });
  2301. this.on('remove', function () {
  2302. if (this.editing && this.editing.enabled()) {
  2303. this.editing.removeHooks();
  2304. }
  2305. });
  2306. });
  2307. L.Map.mergeOptions({
  2308. touchExtend: true
  2309. });
  2310. /**
  2311. * @class L.Map.TouchExtend
  2312. * @aka TouchExtend
  2313. */
  2314. L.Map.TouchExtend = L.Handler.extend({
  2315. // @method initialize(): void
  2316. // Sets TouchExtend private accessor variables
  2317. initialize: function (map) {
  2318. this._map = map;
  2319. this._container = map._container;
  2320. this._pane = map._panes.overlayPane;
  2321. },
  2322. // @method addHooks(): void
  2323. // Adds dom listener events to the map container
  2324. addHooks: function () {
  2325. L.DomEvent.on(this._container, 'touchstart', this._onTouchStart, this);
  2326. L.DomEvent.on(this._container, 'touchend', this._onTouchEnd, this);
  2327. L.DomEvent.on(this._container, 'touchmove', this._onTouchMove, this);
  2328. if (this._detectIE()) {
  2329. L.DomEvent.on(this._container, 'MSPointerDown', this._onTouchStart, this);
  2330. L.DomEvent.on(this._container, 'MSPointerUp', this._onTouchEnd, this);
  2331. L.DomEvent.on(this._container, 'MSPointerMove', this._onTouchMove, this);
  2332. L.DomEvent.on(this._container, 'MSPointerCancel', this._onTouchCancel, this);
  2333. } else {
  2334. L.DomEvent.on(this._container, 'touchcancel', this._onTouchCancel, this);
  2335. L.DomEvent.on(this._container, 'touchleave', this._onTouchLeave, this);
  2336. }
  2337. },
  2338. // @method removeHooks(): void
  2339. // Removes dom listener events from the map container
  2340. removeHooks: function () {
  2341. L.DomEvent.off(this._container, 'touchstart', this._onTouchStart);
  2342. L.DomEvent.off(this._container, 'touchend', this._onTouchEnd);
  2343. L.DomEvent.off(this._container, 'touchmove', this._onTouchMove);
  2344. if (this._detectIE()) {
  2345. L.DomEvent.off(this._container, 'MSPointerDowm', this._onTouchStart);
  2346. L.DomEvent.off(this._container, 'MSPointerUp', this._onTouchEnd);
  2347. L.DomEvent.off(this._container, 'MSPointerMove', this._onTouchMove);
  2348. L.DomEvent.off(this._container, 'MSPointerCancel', this._onTouchCancel);
  2349. } else {
  2350. L.DomEvent.off(this._container, 'touchcancel', this._onTouchCancel);
  2351. L.DomEvent.off(this._container, 'touchleave', this._onTouchLeave);
  2352. }
  2353. },
  2354. _touchEvent: function (e, type) {
  2355. // #TODO: fix the pageX error that is do a bug in Android where a single touch triggers two click events
  2356. // _filterClick is what leaflet uses as a workaround.
  2357. // This is a problem with more things than just android. Another problem is touchEnd has no touches in
  2358. // its touch list.
  2359. var touchEvent = {};
  2360. if (typeof e.touches !== 'undefined') {
  2361. if (!e.touches.length) {
  2362. return;
  2363. }
  2364. touchEvent = e.touches[0];
  2365. } else if (e.pointerType === 'touch') {
  2366. touchEvent = e;
  2367. if (!this._filterClick(e)) {
  2368. return;
  2369. }
  2370. } else {
  2371. return;
  2372. }
  2373. var containerPoint = this._map.mouseEventToContainerPoint(touchEvent),
  2374. layerPoint = this._map.mouseEventToLayerPoint(touchEvent),
  2375. latlng = this._map.layerPointToLatLng(layerPoint);
  2376. this._map.fire(type, {
  2377. latlng: latlng,
  2378. layerPoint: layerPoint,
  2379. containerPoint: containerPoint,
  2380. pageX: touchEvent.pageX,
  2381. pageY: touchEvent.pageY,
  2382. originalEvent: e
  2383. });
  2384. },
  2385. /** Borrowed from Leaflet and modified for bool ops **/
  2386. _filterClick: function (e) {
  2387. var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
  2388. elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
  2389. // are they closer together than 500ms yet more than 100ms?
  2390. // Android typically triggers them ~300ms apart while multiple listeners
  2391. // on the same event should be triggered far faster;
  2392. // or check if click is simulated on the element, and if it is, reject any non-simulated events
  2393. if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) {
  2394. L.DomEvent.stop(e);
  2395. return false;
  2396. }
  2397. L.DomEvent._lastClick = timeStamp;
  2398. return true;
  2399. },
  2400. _onTouchStart: function (e) {
  2401. if (!this._map._loaded) {
  2402. return;
  2403. }
  2404. var type = 'touchstart';
  2405. this._touchEvent(e, type);
  2406. },
  2407. _onTouchEnd: function (e) {
  2408. if (!this._map._loaded) {
  2409. return;
  2410. }
  2411. var type = 'touchend';
  2412. this._touchEvent(e, type);
  2413. },
  2414. _onTouchCancel: function (e) {
  2415. if (!this._map._loaded) {
  2416. return;
  2417. }
  2418. var type = 'touchcancel';
  2419. if (this._detectIE()) {
  2420. type = 'pointercancel';
  2421. }
  2422. this._touchEvent(e, type);
  2423. },
  2424. _onTouchLeave: function (e) {
  2425. if (!this._map._loaded) {
  2426. return;
  2427. }
  2428. var type = 'touchleave';
  2429. this._touchEvent(e, type);
  2430. },
  2431. _onTouchMove: function (e) {
  2432. if (!this._map._loaded) {
  2433. return;
  2434. }
  2435. var type = 'touchmove';
  2436. this._touchEvent(e, type);
  2437. },
  2438. _detectIE: function () {
  2439. var ua = window.navigator.userAgent;
  2440. var msie = ua.indexOf('MSIE ');
  2441. if (msie > 0) {
  2442. // IE 10 or older => return version number
  2443. return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2444. }
  2445. var trident = ua.indexOf('Trident/');
  2446. if (trident > 0) {
  2447. // IE 11 => return version number
  2448. var rv = ua.indexOf('rv:');
  2449. return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2450. }
  2451. var edge = ua.indexOf('Edge/');
  2452. if (edge > 0) {
  2453. // IE 12 => return version number
  2454. return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2455. }
  2456. // other browser
  2457. return false;
  2458. }
  2459. });
  2460. L.Map.addInitHook('addHandler', 'touchExtend', L.Map.TouchExtend);
  2461. /**
  2462. * @class L.Marker.Touch
  2463. * @aka Marker.Touch
  2464. *
  2465. * This isn't full Touch support. This is just to get markers to also support dom touch events after creation
  2466. * #TODO: find a better way of getting markers to support touch.
  2467. */
  2468. L.Marker.Touch = L.Marker.extend({
  2469. _initInteraction: function () {
  2470. if (!this.addInteractiveTarget) {
  2471. // 0.7.x support
  2472. return this._initInteractionLegacy();
  2473. }
  2474. // TODO this may need be updated to re-add touch events for 1.0+
  2475. return L.Marker.prototype._initInteraction.apply(this);
  2476. },
  2477. // This is an exact copy of https://github.com/Leaflet/Leaflet/blob/v0.7/src/layer/marker/Marker.js
  2478. // with the addition of the touch events
  2479. _initInteractionLegacy: function () {
  2480. if (!this.options.clickable) {
  2481. return;
  2482. }
  2483. // TODO refactor into something shared with Map/Path/etc. to DRY it up
  2484. var icon = this._icon,
  2485. events = ['dblclick',
  2486. 'mousedown',
  2487. 'mouseover',
  2488. 'mouseout',
  2489. 'contextmenu',
  2490. 'touchstart',
  2491. 'touchend',
  2492. 'touchmove'];
  2493. if (this._detectIE) {
  2494. events.concat(['MSPointerDown',
  2495. 'MSPointerUp',
  2496. 'MSPointerMove',
  2497. 'MSPointerCancel']);
  2498. } else {
  2499. events.concat(['touchcancel']);
  2500. }
  2501. L.DomUtil.addClass(icon, 'leaflet-clickable');
  2502. L.DomEvent.on(icon, 'click', this._onMouseClick, this);
  2503. L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
  2504. for (var i = 0; i < events.length; i++) {
  2505. L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
  2506. }
  2507. if (L.Handler.MarkerDrag) {
  2508. this.dragging = new L.Handler.MarkerDrag(this);
  2509. if (this.options.draggable) {
  2510. this.dragging.enable();
  2511. }
  2512. }
  2513. },
  2514. _detectIE: function () {
  2515. var ua = window.navigator.userAgent;
  2516. var msie = ua.indexOf('MSIE ');
  2517. if (msie > 0) {
  2518. // IE 10 or older => return version number
  2519. return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2520. }
  2521. var trident = ua.indexOf('Trident/');
  2522. if (trident > 0) {
  2523. // IE 11 => return version number
  2524. var rv = ua.indexOf('rv:');
  2525. return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2526. }
  2527. var edge = ua.indexOf('Edge/');
  2528. if (edge > 0) {
  2529. // IE 12 => return version number
  2530. return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2531. }
  2532. // other browser
  2533. return false;
  2534. }
  2535. });
  2536. /**
  2537. * @class L.LatLngUtil
  2538. * @aka LatLngUtil
  2539. */
  2540. L.LatLngUtil = {
  2541. // Clones a LatLngs[], returns [][]
  2542. // @method cloneLatLngs(LatLngs[]): L.LatLngs[]
  2543. // Clone the latLng point or points or nested points and return an array with those points
  2544. cloneLatLngs: function (latlngs) {
  2545. var clone = [];
  2546. for (var i = 0, l = latlngs.length; i < l; i++) {
  2547. // Check for nested array (Polyline/Polygon)
  2548. if (Array.isArray(latlngs[i])) {
  2549. clone.push(L.LatLngUtil.cloneLatLngs(latlngs[i]));
  2550. } else {
  2551. clone.push(this.cloneLatLng(latlngs[i]));
  2552. }
  2553. }
  2554. return clone;
  2555. },
  2556. // @method cloneLatLng(LatLng): L.LatLng
  2557. // Clone the latLng and return a new LatLng object.
  2558. cloneLatLng: function (latlng) {
  2559. return L.latLng(latlng.lat, latlng.lng);
  2560. }
  2561. };
  2562. (function () {
  2563. var defaultPrecision = {
  2564. km: 2,
  2565. ha: 2,
  2566. m: 0,
  2567. mi: 2,
  2568. ac: 2,
  2569. yd: 0,
  2570. ft: 0,
  2571. nm: 2
  2572. };
  2573. /**
  2574. * @class L.GeometryUtil
  2575. * @aka GeometryUtil
  2576. */
  2577. L.GeometryUtil = L.extend(L.GeometryUtil || {}, {
  2578. // Ported from the OpenLayers implementation. See https://github.com/openlayers/openlayers/blob/master/lib/OpenLayers/Geometry/LinearRing.js#L270
  2579. // @method geodesicArea(): number
  2580. geodesicArea: function (latLngs) {
  2581. var pointsCount = latLngs.length,
  2582. area = 0.0,
  2583. d2r = Math.PI / 180,
  2584. p1, p2;
  2585. if (pointsCount > 2) {
  2586. for (var i = 0; i < pointsCount; i++) {
  2587. p1 = latLngs[i];
  2588. p2 = latLngs[(i + 1) % pointsCount];
  2589. area += ((p2.lng - p1.lng) * d2r) *
  2590. (2 + Math.sin(p1.lat * d2r) + Math.sin(p2.lat * d2r));
  2591. }
  2592. area = area * 6378137.0 * 6378137.0 / 2.0;
  2593. }
  2594. return Math.abs(area);
  2595. },
  2596. // @method formattedNumber(n, precision): string
  2597. // Returns n in specified number format (if defined) and precision
  2598. formattedNumber: function (n, precision) {
  2599. var formatted = parseFloat(n).toFixed(precision),
  2600. format = L.drawLocal.format && L.drawLocal.format.numeric,
  2601. delimiters = format && format.delimiters,
  2602. thousands = delimiters && delimiters.thousands,
  2603. decimal = delimiters && delimiters.decimal;
  2604. if (thousands || decimal) {
  2605. var splitValue = formatted.split('.');
  2606. formatted = thousands ? splitValue[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + thousands) : splitValue[0];
  2607. decimal = decimal || '.';
  2608. if (splitValue.length > 1) {
  2609. formatted = formatted + decimal + splitValue[1];
  2610. }
  2611. }
  2612. return formatted;
  2613. },
  2614. // @method readableArea(area, isMetric, precision): string
  2615. // Returns a readable area string in yards or metric.
  2616. // The value will be rounded as defined by the precision option object.
  2617. readableArea: function (area, isMetric, precision) {
  2618. var areaStr,
  2619. units,
  2620. precision = L.Util.extend({}, defaultPrecision, precision);
  2621. if (isMetric) {
  2622. units = ['ha', 'm'];
  2623. type = typeof isMetric;
  2624. if (type === 'string') {
  2625. units = [isMetric];
  2626. } else if (type !== 'boolean') {
  2627. units = isMetric;
  2628. }
  2629. if (area >= 1000000 && units.indexOf('km') !== -1) {
  2630. areaStr = L.GeometryUtil.formattedNumber(area * 0.000001, precision['km']) + ' km²';
  2631. } else if (area >= 10000 && units.indexOf('ha') !== -1) {
  2632. areaStr = L.GeometryUtil.formattedNumber(area * 0.0001, precision['ha']) + ' ha';
  2633. } else {
  2634. areaStr = L.GeometryUtil.formattedNumber(area, precision['m']) + ' m²';
  2635. }
  2636. } else {
  2637. area /= 0.836127; // Square yards in 1 meter
  2638. if (area >= 3097600) { //3097600 square yards in 1 square mile
  2639. areaStr = L.GeometryUtil.formattedNumber(area / 3097600, precision['mi']) + ' mi²';
  2640. } else if (area >= 4840) { //4840 square yards in 1 acre
  2641. areaStr = L.GeometryUtil.formattedNumber(area / 4840, precision['ac']) + ' acres';
  2642. } else {
  2643. areaStr = L.GeometryUtil.formattedNumber(area, precision['yd']) + ' yd²';
  2644. }
  2645. }
  2646. return areaStr;
  2647. },
  2648. // @method readableDistance(distance, units): string
  2649. // Converts a metric distance to one of [ feet, nauticalMile, metric or yards ] string
  2650. //
  2651. // @alternative
  2652. // @method readableDistance(distance, isMetric, useFeet, isNauticalMile, precision): string
  2653. // Converts metric distance to distance string.
  2654. // The value will be rounded as defined by the precision option object.
  2655. readableDistance: function (distance, isMetric, isFeet, isNauticalMile, precision) {
  2656. var distanceStr,
  2657. units,
  2658. precision = L.Util.extend({}, defaultPrecision, precision);
  2659. if (isMetric) {
  2660. units = typeof isMetric == 'string' ? isMetric : 'metric';
  2661. } else if (isFeet) {
  2662. units = 'feet';
  2663. } else if (isNauticalMile) {
  2664. units = 'nauticalMile';
  2665. } else {
  2666. units = 'yards';
  2667. }
  2668. switch (units) {
  2669. case 'metric':
  2670. // show metres when distance is < 1km, then show km
  2671. if (distance > 1000) {
  2672. distanceStr = L.GeometryUtil.formattedNumber(distance / 1000, precision['km']) + ' km';
  2673. } else {
  2674. distanceStr = L.GeometryUtil.formattedNumber(distance, precision['m']) + ' m';
  2675. }
  2676. break;
  2677. case 'feet':
  2678. distance *= 1.09361 * 3;
  2679. distanceStr = L.GeometryUtil.formattedNumber(distance, precision['ft']) + ' ft';
  2680. break;
  2681. case 'nauticalMile':
  2682. distance *= 0.53996;
  2683. distanceStr = L.GeometryUtil.formattedNumber(distance / 1000, precision['nm']) + ' nm';
  2684. break;
  2685. case 'yards':
  2686. default:
  2687. distance *= 1.09361;
  2688. if (distance > 1760) {
  2689. distanceStr = L.GeometryUtil.formattedNumber(distance / 1760, precision['mi']) + ' miles';
  2690. } else {
  2691. distanceStr = L.GeometryUtil.formattedNumber(distance, precision['yd']) + ' yd';
  2692. }
  2693. break;
  2694. }
  2695. return distanceStr;
  2696. },
  2697. // @method isVersion07x(): boolean
  2698. // Returns true if the Leaflet version is 0.7.x, false otherwise.
  2699. isVersion07x: function () {
  2700. var version = L.version.split('.');
  2701. //If Version is == 0.7.*
  2702. return parseInt(version[0], 10) === 0 && parseInt(version[1], 10) === 7;
  2703. },
  2704. });
  2705. })();
  2706. /**
  2707. * @class L.LineUtil
  2708. * @aka Util
  2709. * @aka L.Utils
  2710. */
  2711. L.Util.extend(L.LineUtil, {
  2712. // @method segmentsIntersect(): boolean
  2713. // Checks to see if two line segments intersect. Does not handle degenerate cases.
  2714. // http://compgeom.cs.uiuc.edu/~jeffe/teaching/373/notes/x06-sweepline.pdf
  2715. segmentsIntersect: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2, /*Point*/ p3) {
  2716. return this._checkCounterclockwise(p, p2, p3) !==
  2717. this._checkCounterclockwise(p1, p2, p3) &&
  2718. this._checkCounterclockwise(p, p1, p2) !==
  2719. this._checkCounterclockwise(p, p1, p3);
  2720. },
  2721. // check to see if points are in counterclockwise order
  2722. _checkCounterclockwise: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
  2723. return (p2.y - p.y) * (p1.x - p.x) > (p1.y - p.y) * (p2.x - p.x);
  2724. }
  2725. });
  2726. /**
  2727. * @class L.Polyline
  2728. * @aka Polyline
  2729. */
  2730. L.Polyline.include({
  2731. // @method intersects(): boolean
  2732. // Check to see if this polyline has any linesegments that intersect.
  2733. // NOTE: does not support detecting intersection for degenerate cases.
  2734. intersects: function () {
  2735. var points = this._getProjectedPoints(),
  2736. len = points ? points.length : 0,
  2737. i, p, p1;
  2738. if (this._tooFewPointsForIntersection()) {
  2739. return false;
  2740. }
  2741. for (i = len - 1; i >= 3; i--) {
  2742. p = points[i - 1];
  2743. p1 = points[i];
  2744. if (this._lineSegmentsIntersectsRange(p, p1, i - 2)) {
  2745. return true;
  2746. }
  2747. }
  2748. return false;
  2749. },
  2750. // @method newLatLngIntersects(): boolean
  2751. // Check for intersection if new latlng was added to this polyline.
  2752. // NOTE: does not support detecting intersection for degenerate cases.
  2753. newLatLngIntersects: function (latlng, skipFirst) {
  2754. // Cannot check a polyline for intersecting lats/lngs when not added to the map
  2755. if (!this._map) {
  2756. return false;
  2757. }
  2758. return this.newPointIntersects(this._map.latLngToLayerPoint(latlng), skipFirst);
  2759. },
  2760. // @method newPointIntersects(): boolean
  2761. // Check for intersection if new point was added to this polyline.
  2762. // newPoint must be a layer point.
  2763. // NOTE: does not support detecting intersection for degenerate cases.
  2764. newPointIntersects: function (newPoint, skipFirst) {
  2765. var points = this._getProjectedPoints(),
  2766. len = points ? points.length : 0,
  2767. lastPoint = points ? points[len - 1] : null,
  2768. // The previous previous line segment. Previous line segment doesn't need testing.
  2769. maxIndex = len - 2;
  2770. if (this._tooFewPointsForIntersection(1)) {
  2771. return false;
  2772. }
  2773. return this._lineSegmentsIntersectsRange(lastPoint, newPoint, maxIndex, skipFirst ? 1 : 0);
  2774. },
  2775. // Polylines with 2 sides can only intersect in cases where points are collinear (we don't support detecting these).
  2776. // Cannot have intersection when < 3 line segments (< 4 points)
  2777. _tooFewPointsForIntersection: function (extraPoints) {
  2778. var points = this._getProjectedPoints(),
  2779. len = points ? points.length : 0;
  2780. // Increment length by extraPoints if present
  2781. len += extraPoints || 0;
  2782. return !points || len <= 3;
  2783. },
  2784. // Checks a line segment intersections with any line segments before its predecessor.
  2785. // Don't need to check the predecessor as will never intersect.
  2786. _lineSegmentsIntersectsRange: function (p, p1, maxIndex, minIndex) {
  2787. var points = this._getProjectedPoints(),
  2788. p2, p3;
  2789. minIndex = minIndex || 0;
  2790. // Check all previous line segments (beside the immediately previous) for intersections
  2791. for (var j = maxIndex; j > minIndex; j--) {
  2792. p2 = points[j - 1];
  2793. p3 = points[j];
  2794. if (L.LineUtil.segmentsIntersect(p, p1, p2, p3)) {
  2795. return true;
  2796. }
  2797. }
  2798. return false;
  2799. },
  2800. _getProjectedPoints: function () {
  2801. if (!this._defaultShape) {
  2802. return this._originalPoints;
  2803. }
  2804. var points = [],
  2805. _shape = this._defaultShape();
  2806. for (var i = 0; i < _shape.length; i++) {
  2807. points.push(this._map.latLngToLayerPoint(_shape[i]));
  2808. }
  2809. return points;
  2810. }
  2811. });
  2812. /**
  2813. * @class L.Polygon
  2814. * @aka Polygon
  2815. */
  2816. L.Polygon.include({
  2817. // @method intersects(): boolean
  2818. // Checks a polygon for any intersecting line segments. Ignores holes.
  2819. intersects: function () {
  2820. var polylineIntersects,
  2821. points = this._getProjectedPoints(),
  2822. len, firstPoint, lastPoint, maxIndex;
  2823. if (this._tooFewPointsForIntersection()) {
  2824. return false;
  2825. }
  2826. polylineIntersects = L.Polyline.prototype.intersects.call(this);
  2827. // If already found an intersection don't need to check for any more.
  2828. if (polylineIntersects) {
  2829. return true;
  2830. }
  2831. len = points.length;
  2832. firstPoint = points[0];
  2833. lastPoint = points[len - 1];
  2834. maxIndex = len - 2;
  2835. // Check the line segment between last and first point. Don't need to check the first line segment (minIndex = 1)
  2836. return this._lineSegmentsIntersectsRange(lastPoint, firstPoint, maxIndex, 1);
  2837. }
  2838. });
  2839. /**
  2840. * @class L.Control.Draw
  2841. * @aka L.Draw
  2842. */
  2843. L.Control.Draw = L.Control.extend({
  2844. // Options
  2845. options: {
  2846. position: 'topleft',
  2847. draw: {},
  2848. edit: false
  2849. },
  2850. // @method initialize(): void
  2851. // Initializes draw control, toolbars from the options
  2852. initialize: function (options) {
  2853. if (L.version < '0.7') {
  2854. throw new Error('Leaflet.draw 0.2.3+ requires Leaflet 0.7.0+. Download latest from https://github.com/Leaflet/Leaflet/');
  2855. }
  2856. L.Control.prototype.initialize.call(this, options);
  2857. var toolbar;
  2858. this._toolbars = {};
  2859. // Initialize toolbars
  2860. if (L.DrawToolbar && this.options.draw) {
  2861. toolbar = new L.DrawToolbar(this.options.draw);
  2862. this._toolbars[L.DrawToolbar.TYPE] = toolbar;
  2863. // Listen for when toolbar is enabled
  2864. this._toolbars[L.DrawToolbar.TYPE].on('enable', this._toolbarEnabled, this);
  2865. }
  2866. if (L.EditToolbar && this.options.edit) {
  2867. toolbar = new L.EditToolbar(this.options.edit);
  2868. this._toolbars[L.EditToolbar.TYPE] = toolbar;
  2869. // Listen for when toolbar is enabled
  2870. this._toolbars[L.EditToolbar.TYPE].on('enable', this._toolbarEnabled, this);
  2871. }
  2872. L.toolbar = this; //set global var for editing the toolbar
  2873. },
  2874. // @method onAdd(): container
  2875. // Adds the toolbar container to the map
  2876. onAdd: function (map) {
  2877. var container = L.DomUtil.create('div', 'leaflet-draw'),
  2878. addedTopClass = false,
  2879. topClassName = 'leaflet-draw-toolbar-top',
  2880. toolbarContainer;
  2881. for (var toolbarId in this._toolbars) {
  2882. if (this._toolbars.hasOwnProperty(toolbarId)) {
  2883. toolbarContainer = this._toolbars[toolbarId].addToolbar(map);
  2884. if (toolbarContainer) {
  2885. // Add class to the first toolbar to remove the margin
  2886. if (!addedTopClass) {
  2887. if (!L.DomUtil.hasClass(toolbarContainer, topClassName)) {
  2888. L.DomUtil.addClass(toolbarContainer.childNodes[0], topClassName);
  2889. }
  2890. addedTopClass = true;
  2891. }
  2892. container.appendChild(toolbarContainer);
  2893. }
  2894. }
  2895. }
  2896. return container;
  2897. },
  2898. // @method onRemove(): void
  2899. // Removes the toolbars from the map toolbar container
  2900. onRemove: function () {
  2901. for (var toolbarId in this._toolbars) {
  2902. if (this._toolbars.hasOwnProperty(toolbarId)) {
  2903. this._toolbars[toolbarId].removeToolbar();
  2904. }
  2905. }
  2906. },
  2907. // @method setDrawingOptions(options): void
  2908. // Sets options to all toolbar instances
  2909. setDrawingOptions: function (options) {
  2910. for (var toolbarId in this._toolbars) {
  2911. if (this._toolbars[toolbarId] instanceof L.DrawToolbar) {
  2912. this._toolbars[toolbarId].setOptions(options);
  2913. }
  2914. }
  2915. },
  2916. _toolbarEnabled: function (e) {
  2917. var enabledToolbar = e.target;
  2918. for (var toolbarId in this._toolbars) {
  2919. if (this._toolbars[toolbarId] !== enabledToolbar) {
  2920. this._toolbars[toolbarId].disable();
  2921. }
  2922. }
  2923. }
  2924. });
  2925. L.Map.mergeOptions({
  2926. drawControlTooltips: true,
  2927. drawControl: false
  2928. });
  2929. L.Map.addInitHook(function () {
  2930. if (this.options.drawControl) {
  2931. this.drawControl = new L.Control.Draw();
  2932. this.addControl(this.drawControl);
  2933. }
  2934. });
  2935. /**
  2936. * @class L.Draw.Toolbar
  2937. * @aka Toolbar
  2938. *
  2939. * The toolbar class of the API — it is used to create the ui
  2940. * This will be depreciated
  2941. *
  2942. * @example
  2943. *
  2944. * ```js
  2945. * var toolbar = L.Toolbar();
  2946. * toolbar.addToolbar(map);
  2947. * ```
  2948. *
  2949. * ### Disabling a toolbar
  2950. *
  2951. * If you do not want a particular toolbar in your app you can turn it off by setting the toolbar to false.
  2952. *
  2953. * ```js
  2954. * var drawControl = new L.Control.Draw({
  2955. * draw: false,
  2956. * edit: {
  2957. * featureGroup: editableLayers
  2958. * }
  2959. * });
  2960. * ```
  2961. *
  2962. * ### Disabling a toolbar item
  2963. *
  2964. * If you want to turn off a particular toolbar item, set it to false. The following disables drawing polygons and
  2965. * markers. It also turns off the ability to edit layers.
  2966. *
  2967. * ```js
  2968. * var drawControl = new L.Control.Draw({
  2969. * draw: {
  2970. * polygon: false,
  2971. * marker: false
  2972. * },
  2973. * edit: {
  2974. * featureGroup: editableLayers,
  2975. * edit: false
  2976. * }
  2977. * });
  2978. * ```
  2979. */
  2980. L.Toolbar = L.Class.extend({
  2981. // @section Methods for modifying the toolbar
  2982. // @method initialize(options): void
  2983. // Toolbar constructor
  2984. initialize: function (options) {
  2985. L.setOptions(this, options);
  2986. this._modes = {};
  2987. this._actionButtons = [];
  2988. this._activeMode = null;
  2989. var version = L.version.split('.');
  2990. //If Version is >= 1.2.0
  2991. if (parseInt(version[0], 10) === 1 && parseInt(version[1], 10) >= 2) {
  2992. L.Toolbar.include(L.Evented.prototype);
  2993. } else {
  2994. L.Toolbar.include(L.Mixin.Events);
  2995. }
  2996. },
  2997. // @method enabled(): boolean
  2998. // Gets a true/false of whether the toolbar is enabled
  2999. enabled: function () {
  3000. return this._activeMode !== null;
  3001. },
  3002. // @method disable(): void
  3003. // Disables the toolbar
  3004. disable: function () {
  3005. if (!this.enabled()) {
  3006. return;
  3007. }
  3008. this._activeMode.handler.disable();
  3009. },
  3010. // @method addToolbar(map): L.DomUtil
  3011. // Adds the toolbar to the map and returns the toolbar dom element
  3012. addToolbar: function (map) {
  3013. var container = L.DomUtil.create('div', 'leaflet-draw-section'),
  3014. buttonIndex = 0,
  3015. buttonClassPrefix = this._toolbarClass || '',
  3016. modeHandlers = this.getModeHandlers(map),
  3017. i;
  3018. this._toolbarContainer = L.DomUtil.create('div', 'leaflet-draw-toolbar leaflet-bar');
  3019. this._map = map;
  3020. for (i = 0; i < modeHandlers.length; i++) {
  3021. if (modeHandlers[i].enabled) {
  3022. this._initModeHandler(
  3023. modeHandlers[i].handler,
  3024. this._toolbarContainer,
  3025. buttonIndex++,
  3026. buttonClassPrefix,
  3027. modeHandlers[i].title
  3028. );
  3029. }
  3030. }
  3031. // if no buttons were added, do not add the toolbar
  3032. if (!buttonIndex) {
  3033. return;
  3034. }
  3035. // Save button index of the last button, -1 as we would have ++ after the last button
  3036. this._lastButtonIndex = --buttonIndex;
  3037. // Create empty actions part of the toolbar
  3038. this._actionsContainer = L.DomUtil.create('ul', 'leaflet-draw-actions');
  3039. // Add draw and cancel containers to the control container
  3040. container.appendChild(this._toolbarContainer);
  3041. container.appendChild(this._actionsContainer);
  3042. return container;
  3043. },
  3044. // @method removeToolbar(): void
  3045. // Removes the toolbar and drops the handler event listeners
  3046. removeToolbar: function () {
  3047. // Dispose each handler
  3048. for (var handlerId in this._modes) {
  3049. if (this._modes.hasOwnProperty(handlerId)) {
  3050. // Unbind handler button
  3051. this._disposeButton(
  3052. this._modes[handlerId].button,
  3053. this._modes[handlerId].handler.enable,
  3054. this._modes[handlerId].handler
  3055. );
  3056. // Make sure is disabled
  3057. this._modes[handlerId].handler.disable();
  3058. // Unbind handler
  3059. this._modes[handlerId].handler
  3060. .off('enabled', this._handlerActivated, this)
  3061. .off('disabled', this._handlerDeactivated, this);
  3062. }
  3063. }
  3064. this._modes = {};
  3065. // Dispose the actions toolbar
  3066. for (var i = 0, l = this._actionButtons.length; i < l; i++) {
  3067. this._disposeButton(
  3068. this._actionButtons[i].button,
  3069. this._actionButtons[i].callback,
  3070. this
  3071. );
  3072. }
  3073. this._actionButtons = [];
  3074. this._actionsContainer = null;
  3075. },
  3076. _initModeHandler: function (handler, container, buttonIndex, classNamePredix, buttonTitle) {
  3077. var type = handler.type;
  3078. this._modes[type] = {};
  3079. this._modes[type].handler = handler;
  3080. this._modes[type].button = this._createButton({
  3081. type: type,
  3082. title: buttonTitle,
  3083. className: classNamePredix + '-' + type,
  3084. container: container,
  3085. callback: this._modes[type].handler.enable,
  3086. context: this._modes[type].handler
  3087. });
  3088. this._modes[type].buttonIndex = buttonIndex;
  3089. this._modes[type].handler
  3090. .on('enabled', this._handlerActivated, this)
  3091. .on('disabled', this._handlerDeactivated, this);
  3092. },
  3093. /* Detect iOS based on browser User Agent, based on:
  3094. * http://stackoverflow.com/a/9039885 */
  3095. _detectIOS: function () {
  3096. var iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream);
  3097. return iOS;
  3098. },
  3099. _createButton: function (options) {
  3100. var link = L.DomUtil.create('a', options.className || '', options.container);
  3101. // Screen reader tag
  3102. var sr = L.DomUtil.create('span', 'sr-only', options.container);
  3103. link.href = '#';
  3104. link.appendChild(sr);
  3105. if (options.title) {
  3106. link.title = options.title;
  3107. sr.innerHTML = options.title;
  3108. }
  3109. if (options.text) {
  3110. link.innerHTML = options.text;
  3111. sr.innerHTML = options.text;
  3112. }
  3113. /* iOS does not use click events */
  3114. var buttonEvent = this._detectIOS() ? 'touchstart' : 'click';
  3115. L.DomEvent
  3116. .on(link, 'click', L.DomEvent.stopPropagation)
  3117. .on(link, 'mousedown', L.DomEvent.stopPropagation)
  3118. .on(link, 'dblclick', L.DomEvent.stopPropagation)
  3119. .on(link, 'touchstart', L.DomEvent.stopPropagation)
  3120. .on(link, 'click', L.DomEvent.preventDefault)
  3121. .on(link, buttonEvent, options.callback, options.context);
  3122. return link;
  3123. },
  3124. _disposeButton: function (button, callback) {
  3125. /* iOS does not use click events */
  3126. var buttonEvent = this._detectIOS() ? 'touchstart' : 'click';
  3127. L.DomEvent
  3128. .off(button, 'click', L.DomEvent.stopPropagation)
  3129. .off(button, 'mousedown', L.DomEvent.stopPropagation)
  3130. .off(button, 'dblclick', L.DomEvent.stopPropagation)
  3131. .off(button, 'touchstart', L.DomEvent.stopPropagation)
  3132. .off(button, 'click', L.DomEvent.preventDefault)
  3133. .off(button, buttonEvent, callback);
  3134. },
  3135. _handlerActivated: function (e) {
  3136. // Disable active mode (if present)
  3137. this.disable();
  3138. // Cache new active feature
  3139. this._activeMode = this._modes[e.handler];
  3140. L.DomUtil.addClass(this._activeMode.button, 'leaflet-draw-toolbar-button-enabled');
  3141. this._showActionsToolbar();
  3142. this.fire('enable');
  3143. },
  3144. _handlerDeactivated: function () {
  3145. this._hideActionsToolbar();
  3146. L.DomUtil.removeClass(this._activeMode.button, 'leaflet-draw-toolbar-button-enabled');
  3147. this._activeMode = null;
  3148. this.fire('disable');
  3149. },
  3150. _createActions: function (handler) {
  3151. var container = this._actionsContainer,
  3152. buttons = this.getActions(handler),
  3153. l = buttons.length,
  3154. li, di, dl, button;
  3155. // Dispose the actions toolbar (todo: dispose only not used buttons)
  3156. for (di = 0, dl = this._actionButtons.length; di < dl; di++) {
  3157. this._disposeButton(this._actionButtons[di].button, this._actionButtons[di].callback);
  3158. }
  3159. this._actionButtons = [];
  3160. // Remove all old buttons
  3161. while (container.firstChild) {
  3162. container.removeChild(container.firstChild);
  3163. }
  3164. for (var i = 0; i < l; i++) {
  3165. if ('enabled' in buttons[i] && !buttons[i].enabled) {
  3166. continue;
  3167. }
  3168. li = L.DomUtil.create('li', '', container);
  3169. button = this._createButton({
  3170. title: buttons[i].title,
  3171. text: buttons[i].text,
  3172. container: li,
  3173. callback: buttons[i].callback,
  3174. context: buttons[i].context
  3175. });
  3176. this._actionButtons.push({
  3177. button: button,
  3178. callback: buttons[i].callback
  3179. });
  3180. }
  3181. },
  3182. _showActionsToolbar: function () {
  3183. var buttonIndex = this._activeMode.buttonIndex,
  3184. lastButtonIndex = this._lastButtonIndex,
  3185. toolbarPosition = this._activeMode.button.offsetTop - 1;
  3186. // Recreate action buttons on every click
  3187. this._createActions(this._activeMode.handler);
  3188. // Correctly position the cancel button
  3189. this._actionsContainer.style.top = toolbarPosition + 'px';
  3190. if (buttonIndex === 0) {
  3191. L.DomUtil.addClass(this._toolbarContainer, 'leaflet-draw-toolbar-notop');
  3192. L.DomUtil.addClass(this._actionsContainer, 'leaflet-draw-actions-top');
  3193. }
  3194. if (buttonIndex === lastButtonIndex) {
  3195. L.DomUtil.addClass(this._toolbarContainer, 'leaflet-draw-toolbar-nobottom');
  3196. L.DomUtil.addClass(this._actionsContainer, 'leaflet-draw-actions-bottom');
  3197. }
  3198. this._actionsContainer.style.display = 'block';
  3199. this._map.fire(L.Draw.Event.TOOLBAROPENED);
  3200. },
  3201. _hideActionsToolbar: function () {
  3202. this._actionsContainer.style.display = 'none';
  3203. L.DomUtil.removeClass(this._toolbarContainer, 'leaflet-draw-toolbar-notop');
  3204. L.DomUtil.removeClass(this._toolbarContainer, 'leaflet-draw-toolbar-nobottom');
  3205. L.DomUtil.removeClass(this._actionsContainer, 'leaflet-draw-actions-top');
  3206. L.DomUtil.removeClass(this._actionsContainer, 'leaflet-draw-actions-bottom');
  3207. this._map.fire(L.Draw.Event.TOOLBARCLOSED);
  3208. }
  3209. });
  3210. L.Draw = L.Draw || {};
  3211. /**
  3212. * @class L.Draw.Tooltip
  3213. * @aka Tooltip
  3214. *
  3215. * The tooltip class — it is used to display the tooltip while drawing
  3216. * This will be depreciated
  3217. *
  3218. * @example
  3219. *
  3220. * ```js
  3221. * var tooltip = L.Draw.Tooltip();
  3222. * ```
  3223. *
  3224. */
  3225. L.Draw.Tooltip = L.Class.extend({
  3226. // @section Methods for modifying draw state
  3227. // @method initialize(map): void
  3228. // Tooltip constructor
  3229. initialize: function (map) {
  3230. this._map = map;
  3231. this._popupPane = map._panes.popupPane;
  3232. this._visible = false;
  3233. this._container = map.options.drawControlTooltips ?
  3234. L.DomUtil.create('div', 'leaflet-draw-tooltip', this._popupPane) : null;
  3235. this._singleLineLabel = false;
  3236. this._map.on('mouseout', this._onMouseOut, this);
  3237. },
  3238. // @method dispose(): void
  3239. // Remove Tooltip DOM and unbind events
  3240. dispose: function () {
  3241. this._map.off('mouseout', this._onMouseOut, this);
  3242. if (this._container) {
  3243. this._popupPane.removeChild(this._container);
  3244. this._container = null;
  3245. }
  3246. },
  3247. // @method updateContent(labelText): this
  3248. // Changes the tooltip text to string in function call
  3249. updateContent: function (labelText) {
  3250. if (!this._container) {
  3251. return this;
  3252. }
  3253. labelText.subtext = labelText.subtext || '';
  3254. // update the vertical position (only if changed)
  3255. if (labelText.subtext.length === 0 && !this._singleLineLabel) {
  3256. L.DomUtil.addClass(this._container, 'leaflet-draw-tooltip-single');
  3257. this._singleLineLabel = true;
  3258. }
  3259. else if (labelText.subtext.length > 0 && this._singleLineLabel) {
  3260. L.DomUtil.removeClass(this._container, 'leaflet-draw-tooltip-single');
  3261. this._singleLineLabel = false;
  3262. }
  3263. this._container.innerHTML =
  3264. (labelText.subtext.length > 0 ?
  3265. '<span class="leaflet-draw-tooltip-subtext">' + labelText.subtext + '</span>' + '<br />' : '') +
  3266. '<span>' + labelText.text + '</span>';
  3267. if (!labelText.text && !labelText.subtext) {
  3268. this._visible = false;
  3269. this._container.style.visibility = 'hidden';
  3270. } else {
  3271. this._visible = true;
  3272. this._container.style.visibility = 'inherit';
  3273. }
  3274. return this;
  3275. },
  3276. // @method updatePosition(latlng): this
  3277. // Changes the location of the tooltip
  3278. updatePosition: function (latlng) {
  3279. var pos = this._map.latLngToLayerPoint(latlng),
  3280. tooltipContainer = this._container;
  3281. if (this._container) {
  3282. if (this._visible) {
  3283. tooltipContainer.style.visibility = 'inherit';
  3284. }
  3285. L.DomUtil.setPosition(tooltipContainer, pos);
  3286. }
  3287. return this;
  3288. },
  3289. // @method showAsError(): this
  3290. // Applies error class to tooltip
  3291. showAsError: function () {
  3292. if (this._container) {
  3293. L.DomUtil.addClass(this._container, 'leaflet-error-draw-tooltip');
  3294. }
  3295. return this;
  3296. },
  3297. // @method removeError(): this
  3298. // Removes the error class from the tooltip
  3299. removeError: function () {
  3300. if (this._container) {
  3301. L.DomUtil.removeClass(this._container, 'leaflet-error-draw-tooltip');
  3302. }
  3303. return this;
  3304. },
  3305. _onMouseOut: function () {
  3306. if (this._container) {
  3307. this._container.style.visibility = 'hidden';
  3308. }
  3309. }
  3310. });
  3311. /**
  3312. * @class L.DrawToolbar
  3313. * @aka Toolbar
  3314. */
  3315. L.DrawToolbar = L.Toolbar.extend({
  3316. statics: {
  3317. TYPE: 'draw'
  3318. },
  3319. options: {
  3320. polyline: {},
  3321. polygon: {},
  3322. rectangle: {},
  3323. circle: {},
  3324. marker: {},
  3325. circlemarker: {}
  3326. },
  3327. // @method initialize(): void
  3328. initialize: function (options) {
  3329. // Ensure that the options are merged correctly since L.extend is only shallow
  3330. for (var type in this.options) {
  3331. if (this.options.hasOwnProperty(type)) {
  3332. if (options[type]) {
  3333. options[type] = L.extend({}, this.options[type], options[type]);
  3334. }
  3335. }
  3336. }
  3337. this._toolbarClass = 'leaflet-draw-draw';
  3338. L.Toolbar.prototype.initialize.call(this, options);
  3339. },
  3340. // @method getModeHandlers(): object
  3341. // Get mode handlers information
  3342. getModeHandlers: function (map) {
  3343. return [
  3344. {
  3345. enabled: this.options.polyline,
  3346. handler: new L.Draw.Polyline(map, this.options.polyline),
  3347. title: L.drawLocal.draw.toolbar.buttons.polyline
  3348. },
  3349. {
  3350. enabled: this.options.polygon,
  3351. handler: new L.Draw.Polygon(map, this.options.polygon),
  3352. title: L.drawLocal.draw.toolbar.buttons.polygon
  3353. },
  3354. {
  3355. enabled: this.options.rectangle,
  3356. handler: new L.Draw.Rectangle(map, this.options.rectangle),
  3357. title: L.drawLocal.draw.toolbar.buttons.rectangle
  3358. },
  3359. {
  3360. enabled: this.options.circle,
  3361. handler: new L.Draw.Circle(map, this.options.circle),
  3362. title: L.drawLocal.draw.toolbar.buttons.circle
  3363. },
  3364. {
  3365. enabled: this.options.marker,
  3366. handler: new L.Draw.Marker(map, this.options.marker),
  3367. title: L.drawLocal.draw.toolbar.buttons.marker
  3368. },
  3369. {
  3370. enabled: this.options.circlemarker,
  3371. handler: new L.Draw.CircleMarker(map, this.options.circlemarker),
  3372. title: L.drawLocal.draw.toolbar.buttons.circlemarker
  3373. }
  3374. ];
  3375. },
  3376. // @method getActions(): object
  3377. // Get action information
  3378. getActions: function (handler) {
  3379. return [
  3380. {
  3381. enabled: handler.completeShape,
  3382. title: L.drawLocal.draw.toolbar.finish.title,
  3383. text: L.drawLocal.draw.toolbar.finish.text,
  3384. callback: handler.completeShape,
  3385. context: handler
  3386. },
  3387. {
  3388. enabled: handler.deleteLastVertex,
  3389. title: L.drawLocal.draw.toolbar.undo.title,
  3390. text: L.drawLocal.draw.toolbar.undo.text,
  3391. callback: handler.deleteLastVertex,
  3392. context: handler
  3393. },
  3394. {
  3395. title: L.drawLocal.draw.toolbar.actions.title,
  3396. text: L.drawLocal.draw.toolbar.actions.text,
  3397. callback: this.disable,
  3398. context: this
  3399. }
  3400. ];
  3401. },
  3402. // @method setOptions(): void
  3403. // Sets the options to the toolbar
  3404. setOptions: function (options) {
  3405. L.setOptions(this, options);
  3406. for (var type in this._modes) {
  3407. if (this._modes.hasOwnProperty(type) && options.hasOwnProperty(type)) {
  3408. this._modes[type].handler.setOptions(options[type]);
  3409. }
  3410. }
  3411. }
  3412. });
  3413. /*L.Map.mergeOptions({
  3414. editControl: true
  3415. });*/
  3416. /**
  3417. * @class L.EditToolbar
  3418. * @aka EditToolbar
  3419. */
  3420. L.EditToolbar = L.Toolbar.extend({
  3421. statics: {
  3422. TYPE: 'edit'
  3423. },
  3424. options: {
  3425. edit: {
  3426. selectedPathOptions: {
  3427. dashArray: '10, 10',
  3428. fill: true,
  3429. fillColor: '#fe57a1',
  3430. fillOpacity: 0.1,
  3431. // Whether to user the existing layers color
  3432. maintainColor: false
  3433. }
  3434. },
  3435. remove: {},
  3436. poly: null,
  3437. featureGroup: null /* REQUIRED! TODO: perhaps if not set then all layers on the map are selectable? */
  3438. },
  3439. // @method intialize(): void
  3440. initialize: function (options) {
  3441. // Need to set this manually since null is an acceptable value here
  3442. if (options.edit) {
  3443. if (typeof options.edit.selectedPathOptions === 'undefined') {
  3444. options.edit.selectedPathOptions = this.options.edit.selectedPathOptions;
  3445. }
  3446. options.edit.selectedPathOptions = L.extend({}, this.options.edit.selectedPathOptions, options.edit.selectedPathOptions);
  3447. }
  3448. if (options.remove) {
  3449. options.remove = L.extend({}, this.options.remove, options.remove);
  3450. }
  3451. if (options.poly) {
  3452. options.poly = L.extend({}, this.options.poly, options.poly);
  3453. }
  3454. this._toolbarClass = 'leaflet-draw-edit';
  3455. L.Toolbar.prototype.initialize.call(this, options);
  3456. this._selectedFeatureCount = 0;
  3457. },
  3458. // @method getModeHandlers(): object
  3459. // Get mode handlers information
  3460. getModeHandlers: function (map) {
  3461. var featureGroup = this.options.featureGroup;
  3462. return [
  3463. {
  3464. enabled: this.options.edit,
  3465. handler: new L.EditToolbar.Edit(map, {
  3466. featureGroup: featureGroup,
  3467. selectedPathOptions: this.options.edit.selectedPathOptions,
  3468. poly: this.options.poly
  3469. }),
  3470. title: L.drawLocal.edit.toolbar.buttons.edit
  3471. },
  3472. {
  3473. enabled: this.options.remove,
  3474. handler: new L.EditToolbar.Delete(map, {
  3475. featureGroup: featureGroup
  3476. }),
  3477. title: L.drawLocal.edit.toolbar.buttons.remove
  3478. }
  3479. ];
  3480. },
  3481. // @method getActions(): object
  3482. // Get actions information
  3483. getActions: function (handler) {
  3484. var actions = [
  3485. {
  3486. title: L.drawLocal.edit.toolbar.actions.save.title,
  3487. text: L.drawLocal.edit.toolbar.actions.save.text,
  3488. callback: this._save,
  3489. context: this
  3490. },
  3491. {
  3492. title: L.drawLocal.edit.toolbar.actions.cancel.title,
  3493. text: L.drawLocal.edit.toolbar.actions.cancel.text,
  3494. callback: this.disable,
  3495. context: this
  3496. }
  3497. ];
  3498. if (handler.removeAllLayers) {
  3499. actions.push({
  3500. title: L.drawLocal.edit.toolbar.actions.clearAll.title,
  3501. text: L.drawLocal.edit.toolbar.actions.clearAll.text,
  3502. callback: this._clearAllLayers,
  3503. context: this
  3504. });
  3505. }
  3506. return actions;
  3507. },
  3508. // @method addToolbar(map): L.DomUtil
  3509. // Adds the toolbar to the map
  3510. addToolbar: function (map) {
  3511. var container = L.Toolbar.prototype.addToolbar.call(this, map);
  3512. this._checkDisabled();
  3513. this.options.featureGroup.on('layeradd layerremove', this._checkDisabled, this);
  3514. return container;
  3515. },
  3516. // @method removeToolbar(): void
  3517. // Removes the toolbar from the map
  3518. removeToolbar: function () {
  3519. this.options.featureGroup.off('layeradd layerremove', this._checkDisabled, this);
  3520. L.Toolbar.prototype.removeToolbar.call(this);
  3521. },
  3522. // @method disable(): void
  3523. // Disables the toolbar
  3524. disable: function () {
  3525. if (!this.enabled()) {
  3526. return;
  3527. }
  3528. this._activeMode.handler.revertLayers();
  3529. L.Toolbar.prototype.disable.call(this);
  3530. },
  3531. _save: function () {
  3532. this._activeMode.handler.save();
  3533. if (this._activeMode) {
  3534. this._activeMode.handler.disable();
  3535. }
  3536. },
  3537. _clearAllLayers: function () {
  3538. this._activeMode.handler.removeAllLayers();
  3539. if (this._activeMode) {
  3540. this._activeMode.handler.disable();
  3541. }
  3542. },
  3543. _checkDisabled: function () {
  3544. var featureGroup = this.options.featureGroup,
  3545. hasLayers = featureGroup.getLayers().length !== 0,
  3546. button;
  3547. if (this.options.edit) {
  3548. button = this._modes[L.EditToolbar.Edit.TYPE].button;
  3549. if (hasLayers) {
  3550. L.DomUtil.removeClass(button, 'leaflet-disabled');
  3551. } else {
  3552. L.DomUtil.addClass(button, 'leaflet-disabled');
  3553. }
  3554. button.setAttribute(
  3555. 'title',
  3556. hasLayers ?
  3557. L.drawLocal.edit.toolbar.buttons.edit
  3558. : L.drawLocal.edit.toolbar.buttons.editDisabled
  3559. );
  3560. }
  3561. if (this.options.remove) {
  3562. button = this._modes[L.EditToolbar.Delete.TYPE].button;
  3563. if (hasLayers) {
  3564. L.DomUtil.removeClass(button, 'leaflet-disabled');
  3565. } else {
  3566. L.DomUtil.addClass(button, 'leaflet-disabled');
  3567. }
  3568. button.setAttribute(
  3569. 'title',
  3570. hasLayers ?
  3571. L.drawLocal.edit.toolbar.buttons.remove
  3572. : L.drawLocal.edit.toolbar.buttons.removeDisabled
  3573. );
  3574. }
  3575. }
  3576. });
  3577. /**
  3578. * @class L.EditToolbar.Edit
  3579. * @aka EditToolbar.Edit
  3580. */
  3581. L.EditToolbar.Edit = L.Handler.extend({
  3582. statics: {
  3583. TYPE: 'edit'
  3584. },
  3585. // @method intialize(): void
  3586. initialize: function (map, options) {
  3587. L.Handler.prototype.initialize.call(this, map);
  3588. L.setOptions(this, options);
  3589. // Store the selectable layer group for ease of access
  3590. this._featureGroup = options.featureGroup;
  3591. if (!(this._featureGroup instanceof L.FeatureGroup)) {
  3592. throw new Error('options.featureGroup must be a L.FeatureGroup');
  3593. }
  3594. this._uneditedLayerProps = {};
  3595. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  3596. this.type = L.EditToolbar.Edit.TYPE;
  3597. var version = L.version.split('.');
  3598. //If Version is >= 1.2.0
  3599. if (parseInt(version[0], 10) === 1 && parseInt(version[1], 10) >= 2) {
  3600. L.EditToolbar.Edit.include(L.Evented.prototype);
  3601. } else {
  3602. L.EditToolbar.Edit.include(L.Mixin.Events);
  3603. }
  3604. },
  3605. // @method enable(): void
  3606. // Enable the edit toolbar
  3607. enable: function () {
  3608. if (this._enabled || !this._hasAvailableLayers()) {
  3609. return;
  3610. }
  3611. this.fire('enabled', {handler: this.type});
  3612. //this disable other handlers
  3613. this._map.fire(L.Draw.Event.EDITSTART, {handler: this.type});
  3614. //allow drawLayer to be updated before beginning edition.
  3615. L.Handler.prototype.enable.call(this);
  3616. this._featureGroup
  3617. .on('layeradd', this._enableLayerEdit, this)
  3618. .on('layerremove', this._disableLayerEdit, this);
  3619. },
  3620. // @method disable(): void
  3621. // Disable the edit toolbar
  3622. disable: function () {
  3623. if (!this._enabled) {
  3624. return;
  3625. }
  3626. this._featureGroup
  3627. .off('layeradd', this._enableLayerEdit, this)
  3628. .off('layerremove', this._disableLayerEdit, this);
  3629. L.Handler.prototype.disable.call(this);
  3630. this._map.fire(L.Draw.Event.EDITSTOP, {handler: this.type});
  3631. this.fire('disabled', {handler: this.type});
  3632. },
  3633. // @method addHooks(): void
  3634. // Add listener hooks for this handler
  3635. addHooks: function () {
  3636. var map = this._map;
  3637. if (map) {
  3638. map.getContainer().focus();
  3639. this._featureGroup.eachLayer(this._enableLayerEdit, this);
  3640. this._tooltip = new L.Draw.Tooltip(this._map);
  3641. this._tooltip.updateContent({
  3642. text: L.drawLocal.edit.handlers.edit.tooltip.text,
  3643. subtext: L.drawLocal.edit.handlers.edit.tooltip.subtext
  3644. });
  3645. // Quickly access the tooltip to update for intersection checking
  3646. map._editTooltip = this._tooltip;
  3647. this._updateTooltip();
  3648. this._map
  3649. .on('mousemove', this._onMouseMove, this)
  3650. .on('touchmove', this._onMouseMove, this)
  3651. .on('MSPointerMove', this._onMouseMove, this)
  3652. .on(L.Draw.Event.EDITVERTEX, this._updateTooltip, this);
  3653. }
  3654. },
  3655. // @method removeHooks(): void
  3656. // Remove listener hooks for this handler
  3657. removeHooks: function () {
  3658. if (this._map) {
  3659. // Clean up selected layers.
  3660. this._featureGroup.eachLayer(this._disableLayerEdit, this);
  3661. // Clear the backups of the original layers
  3662. this._uneditedLayerProps = {};
  3663. this._tooltip.dispose();
  3664. this._tooltip = null;
  3665. this._map
  3666. .off('mousemove', this._onMouseMove, this)
  3667. .off('touchmove', this._onMouseMove, this)
  3668. .off('MSPointerMove', this._onMouseMove, this)
  3669. .off(L.Draw.Event.EDITVERTEX, this._updateTooltip, this);
  3670. }
  3671. },
  3672. // @method revertLayers(): void
  3673. // Revert each layer's geometry changes
  3674. revertLayers: function () {
  3675. this._featureGroup.eachLayer(function (layer) {
  3676. this._revertLayer(layer);
  3677. }, this);
  3678. },
  3679. // @method save(): void
  3680. // Save the layer geometries
  3681. save: function () {
  3682. var editedLayers = new L.LayerGroup();
  3683. this._featureGroup.eachLayer(function (layer) {
  3684. if (layer.edited) {
  3685. editedLayers.addLayer(layer);
  3686. layer.edited = false;
  3687. }
  3688. });
  3689. this._map.fire(L.Draw.Event.EDITED, {layers: editedLayers});
  3690. },
  3691. _backupLayer: function (layer) {
  3692. var id = L.Util.stamp(layer);
  3693. if (!this._uneditedLayerProps[id]) {
  3694. // Polyline, Polygon or Rectangle
  3695. if (layer instanceof L.Polyline || layer instanceof L.Polygon || layer instanceof L.Rectangle) {
  3696. this._uneditedLayerProps[id] = {
  3697. latlngs: L.LatLngUtil.cloneLatLngs(layer.getLatLngs())
  3698. };
  3699. } else if (layer instanceof L.Circle) {
  3700. this._uneditedLayerProps[id] = {
  3701. latlng: L.LatLngUtil.cloneLatLng(layer.getLatLng()),
  3702. radius: layer.getRadius()
  3703. };
  3704. } else if (layer instanceof L.Marker || layer instanceof L.CircleMarker) { // Marker
  3705. this._uneditedLayerProps[id] = {
  3706. latlng: L.LatLngUtil.cloneLatLng(layer.getLatLng())
  3707. };
  3708. }
  3709. }
  3710. },
  3711. _getTooltipText: function () {
  3712. return ({
  3713. text: L.drawLocal.edit.handlers.edit.tooltip.text,
  3714. subtext: L.drawLocal.edit.handlers.edit.tooltip.subtext
  3715. });
  3716. },
  3717. _updateTooltip: function () {
  3718. this._tooltip.updateContent(this._getTooltipText());
  3719. },
  3720. _revertLayer: function (layer) {
  3721. var id = L.Util.stamp(layer);
  3722. layer.edited = false;
  3723. if (this._uneditedLayerProps.hasOwnProperty(id)) {
  3724. // Polyline, Polygon or Rectangle
  3725. if (layer instanceof L.Polyline || layer instanceof L.Polygon || layer instanceof L.Rectangle) {
  3726. layer.setLatLngs(this._uneditedLayerProps[id].latlngs);
  3727. } else if (layer instanceof L.Circle) {
  3728. layer.setLatLng(this._uneditedLayerProps[id].latlng);
  3729. layer.setRadius(this._uneditedLayerProps[id].radius);
  3730. } else if (layer instanceof L.Marker || layer instanceof L.CircleMarker) { // Marker or CircleMarker
  3731. layer.setLatLng(this._uneditedLayerProps[id].latlng);
  3732. }
  3733. layer.fire('revert-edited', {layer: layer});
  3734. }
  3735. },
  3736. _enableLayerEdit: function (e) {
  3737. var layer = e.layer || e.target || e,
  3738. pathOptions, poly;
  3739. // Back up this layer (if haven't before)
  3740. this._backupLayer(layer);
  3741. if (this.options.poly) {
  3742. poly = L.Util.extend({}, this.options.poly);
  3743. layer.options.poly = poly;
  3744. }
  3745. // Set different style for editing mode
  3746. if (this.options.selectedPathOptions) {
  3747. pathOptions = L.Util.extend({}, this.options.selectedPathOptions);
  3748. // Use the existing color of the layer
  3749. if (pathOptions.maintainColor) {
  3750. pathOptions.color = layer.options.color;
  3751. pathOptions.fillColor = layer.options.fillColor;
  3752. }
  3753. layer.options.original = L.extend({}, layer.options);
  3754. layer.options.editing = pathOptions;
  3755. }
  3756. if (layer instanceof L.Marker) {
  3757. if (layer.editing) {
  3758. layer.editing.enable();
  3759. }
  3760. layer.dragging.enable();
  3761. layer
  3762. .on('dragend', this._onMarkerDragEnd)
  3763. // #TODO: remove when leaflet finally fixes their draggable so it's touch friendly again.
  3764. .on('touchmove', this._onTouchMove, this)
  3765. .on('MSPointerMove', this._onTouchMove, this)
  3766. .on('touchend', this._onMarkerDragEnd, this)
  3767. .on('MSPointerUp', this._onMarkerDragEnd, this);
  3768. } else {
  3769. layer.editing.enable();
  3770. }
  3771. },
  3772. _disableLayerEdit: function (e) {
  3773. var layer = e.layer || e.target || e;
  3774. layer.edited = false;
  3775. if (layer.editing) {
  3776. layer.editing.disable();
  3777. }
  3778. delete layer.options.editing;
  3779. delete layer.options.original;
  3780. // Reset layer styles to that of before select
  3781. if (this._selectedPathOptions) {
  3782. if (layer instanceof L.Marker) {
  3783. this._toggleMarkerHighlight(layer);
  3784. } else {
  3785. // reset the layer style to what is was before being selected
  3786. layer.setStyle(layer.options.previousOptions);
  3787. // remove the cached options for the layer object
  3788. delete layer.options.previousOptions;
  3789. }
  3790. }
  3791. if (layer instanceof L.Marker) {
  3792. layer.dragging.disable();
  3793. layer
  3794. .off('dragend', this._onMarkerDragEnd, this)
  3795. .off('touchmove', this._onTouchMove, this)
  3796. .off('MSPointerMove', this._onTouchMove, this)
  3797. .off('touchend', this._onMarkerDragEnd, this)
  3798. .off('MSPointerUp', this._onMarkerDragEnd, this);
  3799. } else {
  3800. layer.editing.disable();
  3801. }
  3802. },
  3803. _onMouseMove: function (e) {
  3804. this._tooltip.updatePosition(e.latlng);
  3805. },
  3806. _onMarkerDragEnd: function (e) {
  3807. var layer = e.target;
  3808. layer.edited = true;
  3809. this._map.fire(L.Draw.Event.EDITMOVE, {layer: layer});
  3810. },
  3811. _onTouchMove: function (e) {
  3812. var touchEvent = e.originalEvent.changedTouches[0],
  3813. layerPoint = this._map.mouseEventToLayerPoint(touchEvent),
  3814. latlng = this._map.layerPointToLatLng(layerPoint);
  3815. e.target.setLatLng(latlng);
  3816. },
  3817. _hasAvailableLayers: function () {
  3818. return this._featureGroup.getLayers().length !== 0;
  3819. }
  3820. });
  3821. /**
  3822. * @class L.EditToolbar.Delete
  3823. * @aka EditToolbar.Delete
  3824. */
  3825. L.EditToolbar.Delete = L.Handler.extend({
  3826. statics: {
  3827. TYPE: 'remove' // not delete as delete is reserved in js
  3828. },
  3829. // @method intialize(): void
  3830. initialize: function (map, options) {
  3831. L.Handler.prototype.initialize.call(this, map);
  3832. L.Util.setOptions(this, options);
  3833. // Store the selectable layer group for ease of access
  3834. this._deletableLayers = this.options.featureGroup;
  3835. if (!(this._deletableLayers instanceof L.FeatureGroup)) {
  3836. throw new Error('options.featureGroup must be a L.FeatureGroup');
  3837. }
  3838. // Save the type so super can fire, need to do this as cannot do this.TYPE :(
  3839. this.type = L.EditToolbar.Delete.TYPE;
  3840. var version = L.version.split('.');
  3841. //If Version is >= 1.2.0
  3842. if (parseInt(version[0], 10) === 1 && parseInt(version[1], 10) >= 2) {
  3843. L.EditToolbar.Delete.include(L.Evented.prototype);
  3844. } else {
  3845. L.EditToolbar.Delete.include(L.Mixin.Events);
  3846. }
  3847. },
  3848. // @method enable(): void
  3849. // Enable the delete toolbar
  3850. enable: function () {
  3851. if (this._enabled || !this._hasAvailableLayers()) {
  3852. return;
  3853. }
  3854. this.fire('enabled', {handler: this.type});
  3855. this._map.fire(L.Draw.Event.DELETESTART, {handler: this.type});
  3856. L.Handler.prototype.enable.call(this);
  3857. this._deletableLayers
  3858. .on('layeradd', this._enableLayerDelete, this)
  3859. .on('layerremove', this._disableLayerDelete, this);
  3860. },
  3861. // @method disable(): void
  3862. // Disable the delete toolbar
  3863. disable: function () {
  3864. if (!this._enabled) {
  3865. return;
  3866. }
  3867. this._deletableLayers
  3868. .off('layeradd', this._enableLayerDelete, this)
  3869. .off('layerremove', this._disableLayerDelete, this);
  3870. L.Handler.prototype.disable.call(this);
  3871. this._map.fire(L.Draw.Event.DELETESTOP, {handler: this.type});
  3872. this.fire('disabled', {handler: this.type});
  3873. },
  3874. // @method addHooks(): void
  3875. // Add listener hooks to this handler
  3876. addHooks: function () {
  3877. var map = this._map;
  3878. if (map) {
  3879. map.getContainer().focus();
  3880. this._deletableLayers.eachLayer(this._enableLayerDelete, this);
  3881. this._deletedLayers = new L.LayerGroup();
  3882. this._tooltip = new L.Draw.Tooltip(this._map);
  3883. this._tooltip.updateContent({text: L.drawLocal.edit.handlers.remove.tooltip.text});
  3884. this._map.on('mousemove', this._onMouseMove, this);
  3885. }
  3886. },
  3887. // @method removeHooks(): void
  3888. // Remove listener hooks from this handler
  3889. removeHooks: function () {
  3890. if (this._map) {
  3891. this._deletableLayers.eachLayer(this._disableLayerDelete, this);
  3892. this._deletedLayers = null;
  3893. this._tooltip.dispose();
  3894. this._tooltip = null;
  3895. this._map.off('mousemove', this._onMouseMove, this);
  3896. }
  3897. },
  3898. // @method revertLayers(): void
  3899. // Revert the deleted layers back to their prior state.
  3900. revertLayers: function () {
  3901. // Iterate of the deleted layers and add them back into the featureGroup
  3902. this._deletedLayers.eachLayer(function (layer) {
  3903. this._deletableLayers.addLayer(layer);
  3904. layer.fire('revert-deleted', {layer: layer});
  3905. }, this);
  3906. },
  3907. // @method save(): void
  3908. // Save deleted layers
  3909. save: function () {
  3910. this._map.fire(L.Draw.Event.DELETED, {layers: this._deletedLayers});
  3911. },
  3912. // @method removeAllLayers(): void
  3913. // Remove all delateable layers
  3914. removeAllLayers: function () {
  3915. // Iterate of the delateable layers and add remove them
  3916. this._deletableLayers.eachLayer(function (layer) {
  3917. this._removeLayer({layer: layer});
  3918. }, this);
  3919. this.save();
  3920. },
  3921. _enableLayerDelete: function (e) {
  3922. var layer = e.layer || e.target || e;
  3923. layer.on('click', this._removeLayer, this);
  3924. },
  3925. _disableLayerDelete: function (e) {
  3926. var layer = e.layer || e.target || e;
  3927. layer.off('click', this._removeLayer, this);
  3928. // Remove from the deleted layers so we can't accidentally revert if the user presses cancel
  3929. this._deletedLayers.removeLayer(layer);
  3930. },
  3931. _removeLayer: function (e) {
  3932. var layer = e.layer || e.target || e;
  3933. this._deletableLayers.removeLayer(layer);
  3934. this._deletedLayers.addLayer(layer);
  3935. layer.fire('deleted');
  3936. },
  3937. _onMouseMove: function (e) {
  3938. this._tooltip.updatePosition(e.latlng);
  3939. },
  3940. _hasAvailableLayers: function () {
  3941. return this._deletableLayers.getLayers().length !== 0;
  3942. }
  3943. });
  3944. }(window, document));
  3945. //# sourceMappingURL=leaflet.draw-src.map