Giter Club home page Giter Club logo

Comments (7)

Raruto avatar Raruto commented on May 27, 2024 1

Hi @FabianSchmick, in here you should actually see some gap between in chart area (ref: https://jsfiddle.net/erjqhgc1/1/).


BTW, I recommend you start by doing some testing by implementing a your own custom handler.

In particular, you can start investigating the following:

export function Distance() {
const _ = L.Control.Elevation.Utils;
let opts = this.options;
let distance = {};
opts.distanceFactor = opts.imperial ? this.__mileFactor : (opts.distanceFactor || 1); // 1 km = (1000 m)
distance.label = opts.imperial ? "mi" : opts.xLabel;
return {
name: 'distance',
required: true,
attr: 'dist',
unit: distance.label,
decimals: 5,
pointToAttr: (_, i) => (i > 0 ? this._data[i - 1].dist : 0) + (this._data[i].latlng.distanceTo(this._data[i > 0 ? i - 1 : i].latlng) * opts.distanceFactor) / 1000, // convert back km to meters
// stats: { total: _.iSum },
onPointAdded: (distance, i) => this.track_info.distance = distance,
scale: opts.distance && {
axis : "x",
position: "bottom",
scale : "x", // this._chart._x,
labelY : 25,
labelX : () => this._width() + 6,
ticks : () => _.clamp(this._chart._xTicks() / 2, [4, +Infinity]),
},
grid: opts.distance && {
axis : "x",
position : "bottom",
scale : "x" // this._chart._x,
},
tooltip: opts.distance && {
name: 'x',
chart: (item) => L._("x: ") + _.round(item[opts.xAttr], opts.decimalsX) + " " + distance.label,
order: 20
},
summary: opts.distance && {
"totlen" : {
label: "Total Length: ",
value: (track) => (track.distance || 0).toFixed(2) + ' ' + distance.label,
order: 10
}
}
};
}


Related resources


Currently all additional chart area definitions (altitude, speed, acceleration, ...) are lazy-loaded from the src/handlers.

So I think a good way to achieve this could be to create a custom definition for this type of graph as well.

It sure won't work out of the box, but maybe with a little tweaking of the "loading" logic it might even turn out to be something more useful.

Below some notable functions:

L.Control.Elevation::options.handlers

handlers: [ // <-- A list of: Dynamic imports || "ClassName" || function Name() { return { /* a custom object definition */ } }
'Distance', // <-- same as: import("../src/handlers/distance.js")
'Time', // <-- same as: import("../src/handlers/time.js")
'Altitude', // <-- same as: import("../src/handlers/altitude.js")
'Slope', // <-- same as: import("../src/handlers/slope.js")
'Speed', // <-- same as: import("../src/handlers/speed.js")
'Acceleration', // <-- same as: import("../src/handlers/acceleration.js")
// 'Pace', // <-- same as: import("../src/handlers/pace.js")
// "Heart", // <-- same as: import("../src/handlers/heart.js")
// "Cadence", // <-- same as: import("../src/handlers/cadence.js")
// import('../src/handlers/heart.js'),
import('../src/handlers/cadence.js'),
// import('../src/handlers/pace.js'),
L.Control.Elevation.MyHeart, // <-- see custom functions declared above
// L.Control.Elevation.MyCadence, // <-- see custom functions declared above
L.Control.Elevation.MyPace, // <-- see custom functions declared above
],

L.Control.Elevation::_registerHandler

/**
* Parse a module definition and attach related function listeners
*/
_registerHandler(props) {
// eg. L.Control.Altitude
if (typeof props === "function") {
return this._registerHandler(props.call(this));
}
let {
name,
attr,
required,
deltaMax,
clampRange,
decimals,
meta,
unit,
coordinateProperties,
coordPropsToMeta,
pointToAttr,
onPointAdded,
stats,
statsName,
grid,
scale,
path,
tooltip,
summary
} = props;
// eg. "altitude" == true
if (this.options[name] || required) {
this._registerDataAttribute({
name,
attr,
meta,
deltaMax,
clampRange,
decimals,
coordPropsToMeta: _.coordPropsToMeta(coordinateProperties, meta || name, coordPropsToMeta),
pointToAttr,
onPointAdded,
stats,
statsName,
});
if (grid) {
this._registerAxisGrid(L.extend({ name }, grid));
}
if (this.options[name] !== "summary") {
if (scale) this._registerAxisScale(L.extend({ name, label: unit }, scale));
if (path) this._registerAreaPath(L.extend({ name }, path));
}
if (tooltip || props.tooltips) {
_.each([tooltip, ...(props.tooltips || [])], t => t && this._registerTooltip(L.extend({ name }, t)));
}
if (summary) {
_.each(summary, (s, k) => summary[k] = L.extend({ unit }, s));
this._registerSummary(summary);
}
}
},

L.Control.Elevation::_registerDataAttribute

/**
* Base handler for iterative track statistics (dist, time, z, slope, speed, acceleration, ...)
*/
_registerDataAttribute(props) {
// parse of "coordinateProperties" for later usage
if (props.coordPropsToMeta) {
this.on("elepoint_init", (e) => props.coordPropsToMeta.call(this, e));
}
// prevent excessive variabile instanstations
let i, curr, prev, attr = props.attr || props.name;
// save here a reference to last used point
let lastValid = {};
// iteration
this.on("elepoint_added", ({index, point}) => {
i = index;
prev = curr ?? this._data[i]; // same as: this._data[i > 0 ? i - 1 : i]
curr = this._data[i];
// retrieve point value
curr[attr] = props.pointToAttr.call(this, point, i);
// check and fix missing data on last added point
if (i > 0 && isNaN(prev[attr])) {
if (!isNaN(lastValid[attr]) && !isNaN(curr[attr])) {
prev[attr] = (lastValid[attr] + curr[attr]) / 2;
} else if (!isNaN(lastValid[attr])) {
prev[attr] = lastValid[attr];
} else if (!isNaN(curr[attr])) {
prev[attr] = curr[attr];
}
// update "yAttr" and "xAttr"
if (props.meta) {
prev[props.meta] = prev[attr];
}
}
// skip to next iteration for invalid or missing data (eg. i == 0)
if (isNaN(curr[attr])) {
return;
}
// update reference to last used point
lastValid[attr] = curr[attr];
// Limit "crazy" delta values.
if (props.deltaMax) {
curr[attr] =_.wrapDelta(curr[attr], prev[attr], props.deltaMax);
}
// Range of acceptable values.
if (props.clampRange) {
curr[attr] = _.clamp(curr[attr], props.clampRange);
}
// Limit floating point precision.
if (!isNaN(props.decimals)) {
curr[attr] = _.round(curr[attr], props.decimals);
}
// update "track_info" stats (min, max, avg, ...)
if (props.stats) {
for (const key in props.stats) {
let sname = (props.statsName || attr) + (key != '' ? '_' : '');
this.track_info[sname + key] = props.stats[key].call(this, curr[attr], this.track_info[sname + key], this._data.length);
}
}
// update here some mixins (eg. complex "track_info" stuff)
if (props.onPointAdded) props.onPointAdded.call(this, curr[attr], i, point);
});
},

👋 Raruto

from leaflet-elevation.

Raruto avatar Raruto commented on May 27, 2024 1

I think the pointToAttr code is executed before my flag is added.

Listening to both events (in sequence) you should somehow achieve that goal:

this.fire("elepoint_added", { point: point, index: this._data.length - 1 });

this.fire("eletrack_added", { coords: coords, index: this._data.length - 1 });

I didn't elaborate, maybe you need some other support flag..

👋 Raruto

from leaflet-elevation.

FabianSchmick avatar FabianSchmick commented on May 27, 2024

@Raruto thank you for your reply. The hint with investigating the src/handlers/distance.js handler helped a lot. I understand the project more from day to day.

I also could fix my issue: 🎉

Bildschirmfoto 2023-08-18 um 11 14 44

But I am not 100% happy with my solution:

  1. Override _addGeoJSONData and _addPoint:
L.Control.Elevation.include({

    _addPoint: function (x, y, z, isFirstPoint = false) {
        ...

        this._data.push({
            x: x,
            y: y,
            z: z,
            latlng: L.latLng(x, y, z),
            isFirstPoint: isFirstPoint
        });

        ...
    },

    _addGeoJSONData: function (coords, properties, nestingLevel) {

       ...

        coords.forEach((point, i) => {

            ...

            this._addPoint(
                point.lat ?? point[1],
                point.lng ?? point[0],
                point.alt ?? point.meta.ele ?? point[2],
                i === 0
            );

            ...
        });

        ...
    }

})
  1. Create my own handler:
export function Distance() {

	... // I have copied the full file only to add a few lines of code :/

	return {
		...
                pointToAttr: (point, i) => {
                    let currentPointDistance = (i > 0 ? this._data[i - 1].dist : 0);
        
                    if (this._data[i].isFirstPoint) {
                        return currentPointDistance;
                    }
        
                    return currentPointDistance + (this._data[i].latlng.distanceTo(this._data[i > 0 ? i - 1 : i].latlng) * opts.distanceFactor) / 1000;
                },
		...
	};
}

As you can see, everytime I write ... I copied the lines from the library. I have to admit, that I am not an experienced JS-Developer, but I don't like to copy so much code. Do you think the new information isFirstPoint on the this._dataobject should live in the source code, maybe this can help others, too? Also, I would like to ask if you know a way to extend the existing handler and override only the pointToAttr function-body of it (so I don't have to copy the full content of the src/handlers/distance.js).

from leaflet-elevation.

Raruto avatar Raruto commented on May 27, 2024

maybe this can help others, too?

It's definitely something that others might be interested in as well, perhaps through a dedicated option.

To be carefully evaluated through a reasonable PR.

I don't like to copy so much code

Handlers files are there to allow a certain degree of flexibility (custom extensions or hotfixes) to other developers looking forward to an official release.

Not much has changed in here, but if you don't override the whole handler file in the future it could be a little more difficult to keep your local changes aligned (monkey patching is leaner, but it's also a dangerous technique).

Do you think the new information isFirstPoint on the this._dataobject should live in the source code?

Alternatively, why not consider the following listener?

this.fire("eletrack_added", { coords: coords, index: this._data.length - 1 });

If I'm not mistaken it's used for a similar purpose:

// Handle multi-track segments
this._maskGaps = [];
control.on('eletrack_added', ({index}) => {
this._maskGaps.push(index);
control.once('elepoint_added', ({index}) => this._maskGaps.push(index));
});

👋 Raruto

from leaflet-elevation.

FabianSchmick avatar FabianSchmick commented on May 27, 2024

I assume the eletrack_added event is unfortunately too late.

I tried the following:

controlElevation.on('eletrack_added', ({index}) => {
    controlElevation._data[index]['isLastPoint'] = true;
});

In the handler

pointToAttr: (point, i) => {
    ...

    if (this._data[i].isLastPoint === true) {
        console.log("test");
        return currentPointDistance;
    }

    ...
},

I think the pointToAttr code is executed before my flag is added. So the if-statement never becomes true in the first run.

But if it would work, I could omit the monkey patching.

from leaflet-elevation.

Raruto avatar Raruto commented on May 27, 2024

However, you probably need to try adding all of your event listeners before all the various handlers are registered:

onAdd(map) {
this._map = map;
let container = this._container = _.create("div", "elevation-control " + this.options.theme + " " + (this.options.detached ? 'elevation-detached' : 'leaflet-control'), this.options.detached ? { id: 'elevation-' + _.randomId() } : {});
if (!this.eleDiv) this.eleDiv = container;
this._loadModules(this.options.handlers).then(() => { // Inject here required modules (data handlers)
this._initChart(container);
this._initButton(container);
this._initSummary(container);
this._initMarker(map);
this._initLayer(map);
this._modulesLoaded = true;
this.fire('modules_loaded');
});
this.fire('add');
return container;
},

When monkey pathching, in order to avoid duplicating too much code, if you just want to run some code (before or after) that function, you can invoke oldProto.onAdd.call() on the old function reference.

Here it is a similar situation: https://github.com/Raruto/leaflet-ui/blob/31b300a69f0ae70b1d0c767686ca1c25c541f03a/src/leaflet-ui.js#L572-L592

from leaflet-elevation.

FabianSchmick avatar FabianSchmick commented on May 27, 2024

Ahh, great! I couldn't think straight at the moment

This:

controlElevation
    .on('eletrack_added', ({index}) => {
        controlElevation._data[index]['isLastPoint'] = true;
    })
    .on('elepoint_added', ({index}) => {
        if (controlElevation._data[index ? index -1 : 0]['isLastPoint']) {
            controlElevation._data[index]['isFirstPoint'] = true;
        }
    })
;

And the custom handler from my comment are the solution:

export function Distance() {

	... // I have copied the full file only to add a few lines of code :/

	return {
		...
                pointToAttr: (point, i) => {
                    let currentPointDistance = (i > 0 ? this._data[i - 1].dist : 0);
        
                    if (this._data[i].isFirstPoint) {
                        return currentPointDistance;
                    }
        
                    return currentPointDistance + (this._data[i].latlng.distanceTo(this._data[i > 0 ? i - 1 : i].latlng) * opts.distanceFactor) / 1000;
                },
		...
	};
}

Thanks again for the useful help @Raruto

from leaflet-elevation.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.