UNPKG

@goshawk22/leaflet-elevation

Version:

A Leaflet plugin that allows to add elevation profiles using d3js

3 lines (2 loc) 28.2 kB
!function(t){"function"==typeof define&&define.amd?define(t):t()}((function(){"use strict";const t={lightblue:{area:"#3366CC",alpha:.45,stroke:"#3366CC"},magenta:{area:"#FF005E"},yellow:{area:"#FF0"},purple:{area:"#732C7B"},steelblue:{area:"#4682B4"},red:{area:"#F00"},lime:{area:"#9CC222",line:"#566B13"}},e=6e4,i=60*e,a=24*i;function s(t,e){return new URL(t,t.startsWith("../")||t.startsWith("./")?e:void 0).toString()}function o(t,e){let i=u("a","",{href:t,target:"_new",download:e||"",style:"display:none;"}),a=document.body;a.appendChild(i),i.click(),a.removeChild(i)}function r(t,e,i){return t&&(({props:a,point:s,id:o,isMulti:r})=>{if(a)for(const h of t)if(h in a){s.meta[e]=(i||n).call(this,r?a[h][r]:a[h],o);break}})}const n=(t,e)=>parseInt("object"==typeof t?t[e]:t),h=(t,e)=>t&&e.split(" ").every((e=>e&&L.DomUtil.addClass(t,e))),l=(t,e)=>t&&e.split(" ").every((e=>e&&L.DomUtil.removeClass(t,e))),d=(t,e,i)=>(i?h:l)(t,e),_=(t,e,i)=>e&&l(t,e)||i&&h(t,i),c=(t,e,i)=>void 0===i&&L.DomUtil.getStyle(t,e)||t.style.setProperty(e,i),m=(t,e)=>{for(let i in e)t.setAttribute(i,e[i])},p=(t,e,i,a)=>t[a?"on":"off"](e,i),u=(t,e,i,a)=>{let s=L.DomUtil.create(t,e||"");return i&&m(s,i),a&&f(a,s),s},f=(t,e)=>t.appendChild(e),g=(t,e,i)=>t.insertAdjacentElement(i,e),y=(t,e)=>(e||document).querySelector(t),v=(t,e)=>{for(let i in t)e(t[i],i)},k=()=>Math.random().toString(36).substr(2,9),{on:M,off:w}=L.DomEvent,{throttle:S,wrapNum:b}=L.Util,{hasClass:C}=L.DomUtil,x=L.Util.formatNum,E=(t,e)=>e?t<e[0]?e[0]:t>e[1]?e[1]:t:t,D=(t,e,i)=>Math.abs(t-e)>i?e+i*Math.sign(t-e):t;function O(t,e=[],i=[]){switch(!t||typeof t){case"object":const a=i.filter((e=>t===e.original))[0];if(a)return a.copy;const s=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return i.push({original:t,copy:s}),Object.getOwnPropertyNames(t).forEach((function(a){const o=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,a,o.get||o.set?o:{writable:o.writable,configurable:o.configurable,enumerable:o.enumerable,value:e.includes(a)?o.value:O(o.value,e,i)})})),s;case"function":case"symbol":console.warn("cloneDeep: "+typeof t+"s not fully supported:",t);default:return t}}var A={__proto__:null,Colors:t,addClass:h,append:f,clamp:E,cloneDeep:O,coordPropsToMeta:r,create:u,drawCanvas:function(t,e){e.classed("canvas-path",!0),t.beginPath(),t.moveTo(0,0);let i=new Path2D(e.attr("d"));t.strokeStyle=e.__strokeStyle||e.attr("stroke"),t.fillStyle=e.__fillStyle||e.attr("fill"),t.lineWidth=1.25,t.globalCompositeOperation="source-over",t.globalAlpha=e.attr("stroke-opacity")||.3,t.stroke(i),t.globalAlpha=e.attr("fill-opacity")||.45,t.fill(i),t.globalAlpha=1,t.closePath()},each:v,formatDate:function(t){return t?"time"==t?t=>new Date(t).toLocaleTimeString():"date"==t?t=>new Date(t).toLocaleDateString():e=>t(e):t=>new Date(t).toLocaleString().replaceAll("/","-").replaceAll(","," ")},formatTime:function(t){let s=Math.floor(t/a),o=Math.floor((t-s*a)/i),r=Math.floor((t-s*a-o*i)/e),n=Math.round((t-s*a-o*i-r*e)/1e3);return 60===n&&(r++,n=0),60===r&&(o++,r=0),24===o&&(s++,o=0),(s?s+"d ":"")+o.toString().padStart(2,0)+":"+r.toString().padStart(2,0)+"'"+n.toString().padStart(2,0)+'"'},hasClass:C,iAvg:(t,e=0,i=1)=>(t+e*(i-1))/i,iMax:(t,e=-1/0)=>t>e?t:e,iMin:(t,e=1/0)=>t<e?t:e,iSum:(t,e=0)=>t+e,insert:g,off:w,on:M,parseDate:(t,e)=>new Date(Date.parse("object"==typeof t?t[e]:t)),parseNumeric:n,randomId:k,removeClass:l,replaceClass:_,resolveURL:s,round:x,saveFile:o,select:y,setAttributes:m,style:c,throttle:S,toggleClass:d,toggleEvent:p,toggleStyle:(t,e,i,a)=>c(t,e,a?i:""),wrapDelta:D,wrapNum:b},T={autofitBounds:!0,autohide:!1,autohideMarker:!0,almostover:!0,altitude:!0,closeBtn:!0,collapsed:!1,detached:!0,distance:!0,distanceMarkers:{lazy:!0,distance:!0,direction:!0},dragging:!L.Browser.mobile,downloadLink:"link",elevationDiv:"#elevation-div",edgeScale:{bar:!0,icon:!1,coords:!1},followMarker:!0,imperial:!1,legend:!0,handlers:["Distance","Time","Altitude","Slope","Speed","Acceleration"],hotline:"elevation",marker:"elevation-line",markerIcon:L.divIcon({className:"elevation-position-marker",html:'<i class="elevation-position-icon"></i>',iconSize:[32,32],iconAnchor:[16,16]}),position:"topright",polyline:{className:"elevation-polyline",color:"#000",opacity:.75,weight:5,lineCap:"round"},polylineSegments:{className:"elevation-polyline-segments",color:"#F00",interactive:!1},preferCanvas:!1,reverseCoords:!1,ruler:!0,theme:"lightblue-theme",summary:"inline",slope:!1,speed:!1,time:!0,timeFactor:3600,timestamps:!1,trkStart:{className:"start-marker",radius:6,weight:2,color:"#fff",fillColor:"#00d800",fillOpacity:1,interactive:!1},trkEnd:{className:"end-marker",radius:6,weight:2,color:"#fff",fillColor:"#ff0606",fillOpacity:1,interactive:!1},waypoints:!0,wptIcons:{"":L.divIcon({className:"elevation-waypoint-marker",html:'<i class="elevation-waypoint-icon default"></i>',iconSize:[30,30],iconAnchor:[8,30]})},wptLabels:!0,xAttr:"dist",xLabel:"km",yAttr:"z",yLabel:"m",zFollow:!1,zooming:!L.Browser.Mobile,margins:{top:30,right:30,bottom:30,left:40},height:.3*screen.height||200,width:.6*screen.width||600,xTicks:void 0,yTicks:void 0,decimalsX:2,decimalsY:0,forceAxisBounds:!1,interpolation:"curveLinear",yAxisMax:void 0,yAxisMin:void 0,srcFolder:(document.currentScript&&document.currentScript.src||{url:"undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:document.currentScript&&document.currentScript.src||new URL("leaflet-elevation.min.js",document.baseURI).href}&&("undefined"==typeof document&&"undefined"==typeof location?require("url").pathToFileURL(__filename).href:"undefined"==typeof document?location.href:document.currentScript&&document.currentScript.src||new URL("leaflet-elevation.min.js",document.baseURI).href)).split("/").slice(0,-1).join("/")+"/"};L._&&L.i18n||(L._=L.i18n=(t,e)=>t);const N=L.Control.Elevation=L.Control.extend({includes:L.Evented?L.Evented.prototype:L.Mixin.Events,options:T,__mileFactor:.621371,__footFactor:3.28084,__D3:"https://unpkg.com/d3@7.8.4/dist/d3.min.js",__TOGEOJSON:"https://unpkg.com/@tmcw/togeojson@5.6.2/dist/togeojson.umd.js",__LGEOMUTIL:"https://unpkg.com/leaflet-geometryutil@0.10.1/src/leaflet.geometryutil.js",__LALMOSTOVER:"https://unpkg.com/leaflet-almostover@1.0.1/src/leaflet.almostover.js",__LHOTLINE:"../libs/leaflet-hotline.min.js",__LDISTANCEM:"../libs/leaflet-distance-marker.min.js",__LEDGESCALE:"../libs/leaflet-edgescale.min.js",__LCHART:"../src/components/chart.js",__LMARKER:"../src/components/marker.js",__LSUMMARY:"../src/components/summary.js",__modulesFolder:"../src/handlers/",__btnIcon:"../images/elevation.svg",addData(t,e){this.import(this.__D3).then((()=>{this._modulesLoaded?(e=e??(t.on&&t),this._addData(t),this._addLayer(e),this._fireEvt("eledata_added",{data:t,layer:e,track_info:this.track_info})):this.once("modules_loaded",(()=>this.addData(t,e)))}))},addTo(t){if(this.options.detached){let e=y(this.options.elevationDiv),i=this.onAdd(t);e?f(e,i):g(t.getContainer(),i,"afterend")}else L.Control.prototype.addTo.call(this,t);return this},clear(){this._marker&&this._marker.remove(),this._chart&&this._clearChart(),this._layers&&this._clearLayers(this._layers),this._markers&&this._clearLayers(this._markers),this._circleMarkers&&this._circleMarkers.remove(),this._hotline&&this._hotline.eachLayer((t=>t.options.renderer.remove())),this._hotline&&this._clearLayers(this._hotline),this._data=[],this.track_info={},this._fireEvt("eledata_clear"),this._updateChart()},_clearChart(){this._events&&this._events.elechart_updated&&this._events.elechart_updated.forEach((({fn:t,ctx:e})=>this.off("elechart_updated",t,e))),this._chart&&this._chart._container&&(this._chart._container.selectAll("g.point .point").remove(),this._chart.clear())},_clearLayers(t){(t=t||this._layers)&&t.eachLayer&&(t.eachLayer((t=>t.remove())),t.clearLayers())},disableBrush(){this._chart._brushEnabled=!1,this._resetDrag()},enableBrush(){this._chart._brushEnabled=!0},disableZoom(){this._chart._zoomEnabled=!1,this._chart._resetZoom()},enableZoom(){this._chart._zoomEnabled=!0},fitBounds(t){t=t||this.getBounds(),this._map&&t.isValid()&&this._map.fitBounds(t)},getBounds(t){return L.latLngBounds((t||this._data).map((t=>t.latlng)))},getZFollow(){return this.options.zFollow},hide(){c(this._container,"display","none")},initialize(e){e=L.setOptions(this,L.extend({},O(T),e)),this._data=[],this._layers=L.featureGroup(),this._markers=L.featureGroup(),this._hotline=L.featureGroup(),this._circleMarkers=L.featureGroup(),this._markedSegments=L.polyline([]),this._start=L.circleMarker([0,0],e.trkStart||T.trkStart),this._end=L.circleMarker([0,0],e.trkEnd||T.trkEnd),this._chartEnabled=!0,this._yCoordMax=-1/0,this.track_info={},e.followMarker&&(this._setMapView=S(this._setMapView,300,this)),e.legend&&(e.margins.bottom+=30),e.theme&&(e.polylineSegments.className+=" "+e.theme),!0===e.wptIcons&&(e.wptIcons=T.wptIcons),!0===e.distanceMarkers&&(e.distanceMarkers=T.distanceMarkers),e.trkStart&&this._start.addTo(this._circleMarkers),e.trkEnd&&this._end.addTo(this._circleMarkers),this._markedSegments.setStyle(e.polylineSegments),L.extend(t,e.colors||{}),this._fixCanvasPaths(),this._fixTooltipSize()},import(t,e){if(Array.isArray(t))return Promise.all(t.map((t=>this.import(t))));switch(t){case this.__D3:e="object"!=typeof d3;break;case this.__TOGEOJSON:e="object"!=typeof toGeoJSON;break;case this.__LGEOMUTIL:e="object"!=typeof L.GeometryUtil;break;case this.__LALMOSTOVER:e="function"!=typeof L.Handler.AlmostOver;break;case this.__LDISTANCEM:e="function"!=typeof L.DistanceMarkers;break;case this.__LEDGESCALE:e="function"!=typeof L.Control.EdgeScale;break;case this.__LHOTLINE:e="function"!=typeof L.Hotline}return!1!==e?import(s(t,this.options.srcFolder)):Promise.resolve()},load(t){this._parseFromString(t).then((e=>e?this._loadLayer(e):this._loadFile(t)))},onAdd(t){this._map=t;let e=this._container=u("div","elevation-control "+this.options.theme+" "+(this.options.detached?"elevation-detached":"leaflet-control"),this.options.detached?{id:"elevation-"+k()}:{});return this.eleDiv||(this.eleDiv=e),this._loadModules(this.options.handlers).then((()=>{this._initChart(e),this._initButton(e),this._initSummary(e),this._initMarker(t),this._initLayer(t),this._modulesLoaded=!0,this.fire("modules_loaded")})),this.fire("add"),e},onRemove(t){this._container=null,t.off("zoom viewreset zoomanim",this._hideMarker,this).off("resize",this._resetView,this).off("resize",this._resizeChart,this).off("mousedown",this._resetDrag,this),w(t.getContainer(),"mousewheel",this._resetDrag,this),w(t.getContainer(),"touchstart",this._resetDrag,this),w(document,"keydown",this._onKeyDown,this),this.off("eledata_added eledata_loaded",this._updateChart,this).off("eledata_added eledata_loaded",this._updateSummary,this),this.fire("remove")},redraw(){this._resizeChart()},setZFollow(t){this.options.zFollow=t},show(){c(this._container,"display","block")},_addData(t){if(t){if("FeatureCollection"===t.type)return v(t.features,(t=>this._addData(t)));if("Feature"===t.type){let e=t.geometry;if(e)switch(e.type){case"LineString":return this._addGeoJSONData(e.coordinates,t.properties);case"MultiLineString":return v(e.coordinates,((e,i)=>this._addGeoJSONData(e,t.properties,i)));default:return console.warn("Unsopperted GeoJSON feature geometry type:"+e.type)}}return t._latlngs?this._addGeoJSONData(t._latlngs,t.feature&&t.feature.properties):void 0}},_addGeoJSONData(t,e,i){let a=e&&e.coordinateProperties||e;t.forEach(((t,e)=>{t.meta=t.meta??{time:null,ele:null},t.prev=t=>t?this._data[e>0?e-1:0][t]:this._data[e>0?e-1:0],this.fire("elepoint_init",{point:t,props:a,id:e,isMulti:i}),this._addPoint(t.lat??t[1],t.lng??t[0],t.alt??t.meta.ele??t[2]),this.fire("elepoint_added",{point:t,index:this._data.length-1}),this._yCoordMax<this._data[this._data.length-1][this.options.yAttr]&&(this._yCoordMax=this._data[this._data.length-1][this.options.yAttr])})),this.fire("eletrack_added",{coords:t,index:this._data.length-1})},_addPoint(t,e,i){this.options.reverseCoords&&([t,e]=[e,t]),this._data.push({x:t,y:e,z:i,latlng:L.latLng(t,e,i)}),this.fire("eledata_updated",{index:this._data.length-1})},_addLayer(t){return t&&this._layers.addLayer(t),t&&this.options.distanceMarkers&&this.options.distanceMarkers.lazy&&t.on("add remove",(({target:t,type:e})=>L.DistanceMarkers&&t instanceof L.Polyline&&t[e+"DistanceMarkers"]())),t},_addMarker(t){return t&&this._markers.addLayer(t),t},_initAlmostOverHandler(t,e){return t&&this.options.almostOver&&!L.Browser.mobile?this.import([this.__LGEOMUTIL,this.__LALMOSTOVER]).then((()=>{t.addHandler("almostOver",L.Handler.AlmostOver),L.GeometryUtil&&t.almostOver&&t.almostOver.enabled()&&(t.almostOver.addLayer(e),t.on("almost:move",this._onMouseMoveLayer,this).on("almost:out",this._onMouseOut,this),this.once("eledata_clear",(()=>{t.almostOver.removeLayer(e),t.off("almost:move",this._onMouseMoveLayer,this).off("almost:out",this._onMouseOut,this)})))})):Promise.resolve()},_initDistanceMarkers(){return this.options.distanceMarkers?this.import([this.__LGEOMUTIL,this.__LDISTANCEM]):Promise.resolve()},_initEdgeScale(t){return this.options.edgeScale?this.import(this.__LEDGESCALE).then((()=>{t.edgeScaleControl=t.edgeScaleControl||L.control.edgeScale("boolean"!=typeof this.options.edgeScale?this.options.edgeScale:{}).addTo(t)})):Promise.resolve()},_initHotLine(t){let e="string"==typeof this.options.hotline?this.options.hotline:"elevation";return this.options.hotline?this.import(this.__LHOTLINE).then((()=>{t.eachLayer((t=>{if("Point"!=t.feature.geometry.type){let i=L.geoJson(t.toGeoJSON(),{coordsToLatLng:t=>L.latLng(t[0],t[1],t[2]*(this.options.altitudeFactor||1))}),a=L.hotline(i.toGeoJSON().features[0].geometry.coordinates,{renderer:L.Hotline.renderer(),min:isFinite(this.track_info[e+"_min"])?this.track_info[e+"_min"]:0,max:isFinite(this.track_info[e+"_max"])?this.track_info[e+"_max"]:1,palette:{0:"#008800",.5:"#ffff00",1:"#ff0000"},weight:5,outlineColor:"#000000",outlineWidth:1}).addTo(this._hotline),s=t.options.style&&t.options.style.opacity||1;t.on("add remove",(({type:e})=>{t.setStyle({opacity:"add"==e?0:s}),a["add"==e?"addTo":"removeFrom"](t._map),a._renderer&&a._renderer._container.parentElement.insertBefore(a._renderer._container,a._renderer._container.parentElement.firstChild)}))}}))})):Promise.resolve()},_initMapIntegrations(t){let e=this._map;e?(this._data.length&&(this._start.setLatLng(this._data[0].latlng),this._end.setLatLng(this._data[this._data.length-1].latlng)),Promise.all([this._initHotLine(t),this._initAlmostOverHandler(e,t),this._initDistanceMarkers(),this._initEdgeScale(e)]).then((()=>{this.options.polyline&&(this._layers.addLayer(t.addTo(e)),this._circleMarkers.addTo(e)),this.options.autofitBounds&&this.fitBounds(t.getBounds()),e.invalidateSize()}))):this.once("add",(()=>this._initMapIntegrations(t)))},_collapse(){_(this._container,"elevation-expanded","elevation-collapsed"),this._map&&this._map.invalidateSize()},_expand(){_(this._container,"elevation-collapsed","elevation-expanded"),this._map&&this._map.invalidateSize()},_fixCanvasPaths(){let e=L.Canvas.prototype._fillStroke,i=this,a=this.options.theme.split(" ")[0].replace("-theme",""),s=t[a]||{};L.Canvas.include({_fillStroke(t,o){if(i._layers.hasLayer(o)){let i=o.options;if(i.color=s.line||s.area||a,i.stroke=!!i.color,e.call(this,t,o),i.stroke&&0!==i.weight){let e=t.globalCompositeOperation||"source-over";t.globalCompositeOperation="destination-over",t.strokeStyle=s.outline||"#FFF",t.lineWidth=1.75*i.weight,t.stroke(),t.globalCompositeOperation=e}}else e.call(this,t,o)}})},_fixTooltipSize(){this.on("elechart_init",(()=>this.once("elechart_change elechart_hover",(({data:t,xCoord:e})=>{this._chartEnabled&&(this._chart._showDiagramIndicator(t,e),this._chart._showDiagramIndicator(t,e)),this._updateMarker(t)}))))},_findItemForLatLng(t){return this._data[this._chart._findIndexForLatLng(t)]},_findItemForX(t){return this._data[this._chart._findIndexForXCoord(t)]},_fireEvt(t,e,i){this.fire&&this.fire(t,e,i),this._map&&this._map.fire(t,e,i)},_hideMarker(){this.options.autohideMarker&&this._marker.remove()},_initChart(t){let e=this.options,i=this._map;if(e.detached){let{offsetWidth:t,offsetHeight:i}=this.eleDiv;t>0&&(e.width=t),i>20&&(e.height=i-20)}else{let{clientWidth:t}=i.getContainer();e._maxWidth=e._maxWidth>e.width?e._maxWidth:e.width,this._container.style.maxWidth=e._maxWidth+"px",e._maxWidth>t&&(e.width=t-30)}this.import([this.__D3,this.__LCHART]).then((a=>{let s=this._chart=new(a[1]||N).Chart(e,this);this._x=this._chart._x,this._y=this._chart._y,d3.select(t).call(s.render()),s.on("reset_drag",this._hideMarker,this).on("mouse_enter",this._onMouseEnter,this).on("dragged",this._onDragEnd,this).on("mouse_move",this._onMouseMove,this).on("mouse_out",this._onMouseOut,this).on("ruler_filter",this._onRulerFilter,this).on("zoom",this._updateChart,this).on("elepath_toggle",this._onToggleChart,this).on("margins_updated",this._resizeChart,this),this.fire("elechart_init"),i.on("zoom viewreset zoomanim",this._hideMarker,this).on("resize",this._resetView,this).on("resize",this._resizeChart,this).on("rotate",this._rotateMarker,this).on("mousedown",this._resetDrag,this),M(i.getContainer(),"mousewheel",this._resetDrag,this),M(i.getContainer(),"touchstart",this._resetDrag,this),M(document,"keydown",this._onKeyDown,this),this.on("eledata_added eledata_loaded",this._updateChart,this).on("eledata_added eledata_loaded",this._updateSummary,this),this._updateChart(),this._updateSummary()}))},_initLayer(){this._layers.on("layeradd layerremove",(({layer:t,type:e})=>{let i=t.getElement&&t.getElement();d(i,this.options.polyline.className+" "+this.options.theme,"layeradd"==e),p(t,"mousemove",this._onMouseMoveLayer.bind(this),"layeradd"==e),p(t,"mouseout",this._onMouseOut.bind(this),"layeradd"==e)}))},_initMarker(t){let e=t.getPane("elevationPane");e||(e=this._pane=t.createPane("elevationPane",t.getPane("norotatePane")||t.getPane("mapPane")),e.style.zIndex=625,e.style.pointerEvents="none"),this._renderer&&this._renderer.remove(),this._renderer=L.svg({pane:"elevationPane"}).addTo(this._map),this.import([this.__D3,this.__LMARKER]).then((t=>{this._marker=new(t[1]||N).Marker(this.options,this),this.fire("elechart_marker")}))},_initButton(t){if(L.DomEvent.disableClickPropagation(t).disableScrollPropagation(t),this.options.collapsed?this._collapse():this._expand(),this.options.autohide&&(M(t,"mouseover",this._expand,this),M(t,"mouseout",this._collapse,this),this._map.on("click",this._collapse,this)),this.options.closeBtn){let e=this._button=u("a","elevation-toggle-icon",{href:"#",title:L._("Elevation")},t);M(e,"click",L.DomEvent.stop),M(e,"click",this._toggle,this),M(e,"focus",this._toggle,this),fetch(s(this.__btnIcon,this.options.srcFolder)).then((t=>t.ok&&t.text().then((t=>e.innerHTML=t))))}},_initSummary(t){this.import(this.__LSUMMARY).then((e=>{this._summary=new(e||N).Summary({summary:this.options.summary},this),this.on("elechart_init",(()=>{d3.select(t).call(this._summary.render())}))}))},_loadFile(t){fetch(t).then((t=>t.text())).then((e=>{this._downloadURL=t,this._parseFromString(e).then((t=>t&&this._loadLayer(t)))})).catch((t=>console.warn(t)))},_loadModules(t){let e=(t=t.map((t=>"string"==typeof t&&void 0!==N[t]?N[t]:t))).map((t=>"string"==typeof t&&this.import(this.__modulesFolder+t.toLowerCase()+".js")||t instanceof Promise&&t||Promise.resolve()));return Promise.all(e).then((e=>{v(e,((e,i)=>{let a=e&&Object.keys(e)[0];a&&(t[i]=N[a]=N[a]??e[a])})),v(t,(t=>["function","object"].includes(typeof t)&&this._registerHandler(t)))}))},_loadLayer(t){let{polyline:e,theme:i,waypoints:a,wptIcons:s,wptLabels:o,distanceMarkers:r}=this.options,n=L.extend({},e);i&&(n.className+=" "+i),t.name&&(this.track_info.name=t.name);let h=L.geoJson(t,{distanceMarkers:r,style:n,pointToLayer:(t,e)=>{if(a){let{desc:i,name:r,sym:n}=t.properties;if(i=i||"",r=r||"",[!0,"dots"].includes(a)&&this._registerCheckPoint({latlng:e,label:[!0,"dots"].includes(o)?r:""}),[!0,"markers"].includes(a)&&0!=s)return this._registerMarker({latlng:e,sym:(n??r).replace(" ","-").replace('"',"").replace("'","").toLowerCase(),content:[!0,"markers"].includes(o)&&(r||i)&&decodeURI("<b>"+r+"</b>"+(i.length>0?"<br>"+i:""))})}},onEachFeature:(t,e)=>t.geometry&&"Point"!=t.geometry.type&&this.addData(t,e)});return this.import(this.__D3).then((()=>{this._initMapIntegrations(h);const e={data:t,layer:h,name:this.track_info.name,track_info:this.track_info};this._modulesLoaded?this._fireEvt("eledata_loaded",e):this.once("modules_loaded",(()=>this._fireEvt("eledata_loaded",e)))})),h},_onDragEnd({dragstart:t,dragend:e}){this._hideMarker(),this.fitBounds(L.latLngBounds([t.latlng,e.latlng])),this.fire("elechart_dragged")},_onKeyDown({key:t}){this.options.detached||"Escape"!==t||this._collapse()},_onMouseEnter(){this.fire("elechart_enter")},_onMouseMove({xCoord:t}){if(this._chartEnabled&&this._data.length){let e=this._findItemForX(t);e&&(this._chartEnabled&&this._chart._showDiagramIndicator(e,t),this._updateMarker(e),this._setMapView(e),this._map&&h(this._map.getContainer(),"elechart-hover"),this.fire("elechart_change",{data:e,xCoord:t}),this.fire("elechart_hover",{data:e,xCoord:t}))}},_onMouseMoveLayer({latlng:t}){if(this._data.length){let e=this._findItemForLatLng(t);if(e){let t=e.xDiagCoord;this._chartEnabled&&this._chart._showDiagramIndicator(e,t),this._updateMarker(e),this.fire("elechart_change",{data:e,xCoord:t})}}},_onMouseOut(){this.options.detached||(this._hideMarker(),this._chart._hideDiagramIndicator()),this._map&&l(this._map.getContainer(),"elechart-hover"),this.fire("elechart_leave")},_onRulerFilter({coords:t}){this._updateMapSegments(t)},_onToggleChart({name:t,enabled:e}){this._chartEnabled=this._chart._hasActiveLayers(),this._layers.eachLayer((t=>d(t.getElement&&t.getElement(),this.options.polyline.className+" "+this.options.theme,this._chartEnabled))),this.options[t]=e||"disabled"!=this.options[t]?"disabled":"enabled",this._chartEnabled||(this._chart._hideDiagramIndicator(),this._marker.remove())},_parseFromGeoJSONString(t){try{return JSON.parse(t)}catch(t){}},_parseFromString(t){return new Promise((e=>this.import(this.__TOGEOJSON).then((()=>{let i;try{i=this._parseFromXMLString(t.trim())}catch(e){i=this._parseFromGeoJSONString(t.toString())}i&&(i.name=i.name||(this._downloadURL||"").split("/").pop().split("#")[0].split("?")[0]),e(i)}))))},_parseFromXMLString(t){if(0!=t.indexOf("<"))throw"Invalid XML";let e=(new DOMParser).parseFromString(t,"text/xml"),i=e.documentElement.tagName.toLowerCase(),a=e.getElementsByTagName("name");if(e.getElementsByTagName("parsererror").length)throw"Invalid XML";i in toGeoJSON||(i="TrainingCenterDatabase"==e.documentElement.tagName?"tcx":"gpx");let s=toGeoJSON[i](e);return s.name=a.length>0?(Array.from(a).find((t=>"trk"==t.parentElement.tagName))??a[0]).textContent:"",s},_registerAreaPath(t){this.on("elechart_init",(()=>this._chart._registerAreaPath(t)))},_registerAxisGrid(t){this.on("elechart_axis",(()=>this._chart._registerAxisGrid(t)))},_registerAxisScale(t){this.on("elechart_axis",(()=>this._chart._registerAxisScale(t)))},_registerCheckPoint(t){const e=()=>this._chart._registerCheckPoint(t);this.on("elechart_updated",e).once("eledata_clear",(()=>this.off("elechart_updated",e)))},_registerDataAttribute(t){t.coordPropsToMeta&&this.on("elepoint_init",(e=>t.coordPropsToMeta.call(this,e)));let e,i,a,s=t.attr||t.name,o={};this.on("elepoint_added",(({index:r,point:n})=>{if(e=r,a=i??this._data[e],i=this._data[e],i[s]=t.pointToAttr.call(this,n,e),e>0&&isNaN(a[s])&&(isNaN(o[s])||isNaN(i[s])?isNaN(o[s])?isNaN(i[s])||(a[s]=i[s]):a[s]=o[s]:a[s]=(o[s]+i[s])/2,t.meta&&(a[t.meta]=a[s])),!isNaN(i[s])){if(o[s]=i[s],t.deltaMax&&(i[s]=D(i[s],a[s],t.deltaMax)),t.clampRange&&(i[s]=E(i[s],t.clampRange)),isNaN(t.decimals)||(i[s]=x(i[s],t.decimals)),t.stats)for(const e in t.stats){let a=(t.statsName||s)+(""!=e?"_":"");this.track_info[a+e]=t.stats[e].call(this,i[s],this.track_info[a+e],this._data.length)}t.onPointAdded&&t.onPointAdded.call(this,i[s],e,n)}}))},_registerHandler(t){if("function"==typeof t)return this._registerHandler(t.call(this));let{name:e,attr:i,required:a,deltaMax:s,clampRange:o,decimals:n,meta:h,unit:l,coordinateProperties:d,coordPropsToMeta:_,pointToAttr:c,onPointAdded:m,stats:p,statsName:u,grid:f,scale:g,path:y,tooltip:k,summary:M}=t;(this.options[e]||a)&&(this._registerDataAttribute({name:e,attr:i,meta:h,deltaMax:s,clampRange:o,decimals:n,coordPropsToMeta:r(d,h||e,_),pointToAttr:c,onPointAdded:m,stats:p,statsName:u}),f&&this._registerAxisGrid(L.extend({name:e},f)),"summary"!==this.options[e]&&(g&&this._registerAxisScale(L.extend({name:e,label:l},g)),y&&this._registerAreaPath(L.extend({name:e},y))),(k||t.tooltips)&&v([k,...t.tooltips||[]],(t=>t&&this._registerTooltip(L.extend({name:e},t)))),M&&(v(M,((t,e)=>M[e]=L.extend({unit:l},t))),this._registerSummary(M)))},_registerMarker({latlng:t,sym:e,content:i}){let{wptIcons:a}=this.options;a.hasOwnProperty(e)||(a[e]=L.divIcon(L.extend({},a[""].options,{html:'<i class="elevation-waypoint-icon '+e+'"></i>'})));let s=L.marker(t,{icon:a[e]});return i&&(s.bindPopup(i,{className:"elevation-popup",keepInView:!0}).openPopup(),s.bindTooltip(i,{className:"elevation-tooltip",direction:"auto",sticky:!0,opacity:1}).openTooltip()),this._addMarker(s)},_registerTooltip(t){t.chart&&this.on("elechart_init",(()=>this._chart._registerTooltip(L.extend({},t,{value:t.chart})))),t.marker&&this.on("elechart_marker",(()=>this._marker._registerTooltip(L.extend({},t,{value:t.marker}))))},_registerSummary(t){this.on("elechart_summary",(()=>this._summary._registerSummary(t)))},_resetDrag(){this._chart._resetDrag(),this._hideMarker()},_resetView(){this._map&&this._map._isFullscreen||(this._resetDrag(),this._hideMarker(),this.options.autofitBounds&&this.fitBounds())},_resizeChart(){if(this._container&&"none"!=c(this._container,"display")){let t=this.options,e=t.detached?(this.eleDiv||this._container).offsetWidth:E(t._maxWidth,[0,this._map.getContainer().clientWidth-30]);e&&(t.width=e,this._chart&&this._chart._chart&&(this._chart._chart._resize(t),this._updateChart())),this._updateMapSegments()}},_toggle(){C(this._container,"elevation-expanded")?this._collapse():this._expand()},_setMapView(t){if(this._map&&this.options.followMarker){let e=this._map.getZoom(),i=this.options.zFollow;"number"==typeof i?this._map.setView(t.latlng,e<i?i:e,{animate:!0,duration:.25}):this._map.getBounds().contains(t.latlng)||this._map.setView(t.latlng,e,{animate:!0,duration:.25})}},_updateChart(){this._chart&&this._container&&(this.fire("elechart_axis"),this._chart.update({data:this._data,options:this.options}),this._x=this._chart._x,this._y=this._chart._y,this.fire("elechart_updated"))},_updateMarker(t){this._marker&&this._marker.update({map:this._map,item:t,yCoordMax:this._yCoordMax||0,options:this.options})},_rotateMarker(){this._marker&&this._marker.update()},_updateMapSegments(t){this._markedSegments.setLatLngs(t||[]),t&&this._map&&!this._map.hasLayer(this._markedSegments)&&this._markedSegments.addTo(this._map)},_updateSummary(){this._summary&&(this._summary.reset(),this.options.summary&&(this.fire("elechart_summary"),this._summary.update()),this.options.downloadLink&&this._downloadURL&&(this._summary._container.innerHTML+='<span class="download"><a href="#">'+L._("Download")+"</a></span>",y(".download a",this._summary._container).onclick=t=>{t.preventDefault();let e={downloadLink:this.options.downloadLink,confirm:o.bind(this,this._downloadURL)};"modal"==this.options.downloadLink&&"function"==typeof CustomEvent?document.dispatchEvent(new CustomEvent("eletrack_download",{detail:e})):"link"!=this.options.downloadLink&&!0!==this.options.downloadLink||e.confirm(),this.fire("eletrack_download",e)}))},_width(){if(this._chart)return this._chart._width();const{width:t,margins:e}=this.options;return t-e.left-e.right},_height(){if(this._chart)return this._chart._height();const{height:t,margins:e}=this.options;return t-e.top-e.bottom}});N.Utils=A,L.control.elevation=t=>new N(t)})); //# sourceMappingURL=leaflet-elevation.min.js.map