Skip to content

GeoTrackFigure

roosit edited this page Nov 15, 2026 · 4 revisions

GeoTrackFigure

Up | Previous | Next | Русский

Full source with short explanations

Below is the full source of the class in documentation form. The comments inside the block explain the purpose of the parts of the class, but they are not kept in the working file GeoTrackFigure.java: the production code stays clean, and the explanations live in the wiki.

package com.velitask.plugin.official.geo;

import com.velitask.plugin.official.GeoMapIndicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.data.GeoSensorAtom;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.figures.Figure;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.GeoSensorProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.LineProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.VisibleProperty;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.List;

/* The "Track" figure: the GPS track line on top of the map. */
public class GeoTrackFigure extends Figure<GeoFigureContext> {

    /* Figure name (the type field in the figure JSON). */
    public static final String NAME = "track";

    /* Prefix of the localization keys. */
    private static final String KEY = GeoMapIndicator.KEY + "." + NAME;

    /* Geo sensor of the figure; the track query returns the track points for the zoom. */
    private final GeoSensorProperty mGeoSensor = new GeoSensorProperty();

    {
        mGeoSensor.query("track")
                /* A simplified copy of the track at the selected scale is needed, not only exact atoms. */
                .anyLevel()
                .where("zoom = {zoom}")
                .orderBy("timeRaw")
                .cache(DataCacheRule.byParams())
                .cacheSize(2)
                .buildList();
    }

    /* Track line: color, thickness, style, dash pattern. */
    private final LineProperty mLine = new LineProperty();

    {
        /* The default color is red (200, 0, 0). */
        mLine.getColor().setDefault(new Color(200, 0, 0));
        mLine.getColor().set(new Color(200, 0, 0));
        /* Thickness 1..30, 5 by default. */
        mLine.getThickness().setRange(1, 30);
        mLine.getThickness().setDefault(5);
        mLine.getThickness().set(5);
    }

    /* "Passed only": draw the track only up to the current position. */
    private final VisibleProperty mPassedOnly = new VisibleProperty() {
        {
            setDefault(false);
            set(false);
        }

        @Override
        public String getName() {
            return "passedOnly";
        }

        @Override
        public String getTitle() {
            return localized(KEY + ".passedOnly.title");
        }
    };

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public String getTitle() {
        return localized(KEY + ".title");
    }

    @Override
    /* Three properties are saved: Geo, line, passedOnly. */
    public IProperty[] defineProperties() {
        return new IProperty[]{mGeoSensor, mLine, mPassedOnly};
    }

    @Override
    /* The panel shows the line and "Passed only". */
    public void configureDisplay(DisplayConfig config) {
        config.set(mLine, PropertyGroup.APPEARANCE);
        config.set(mPassedOnly, PropertyGroup.APPEARANCE);
    }

    @Override
    /* Selects the track points and draws a polyline in screen coordinates. */
    public void render(GeoFigureContext baseCtx) {
        TrackContext ctx = (TrackContext) baseCtx;
        if (ctx.indicator.zoom == null || ctx.position.sensorId == 0) {
            return;
        }

        /* The nearest available zoom of the track data is taken. */
        int actualZoom = ctx.position.approximateZoom(ctx.zoom.getLevel());
        DataParams params = DataParams.of("sensorId", ctx.position.sensorId)
                .set("zoom", actualZoom);
        List<GeoSensorAtom> points = ctx.position.queryList("track", params);
        if (points == null || points.size() < 2) {
            return;
        }

        Graphics2D g = ctx.graphics;
        g.setColor(ctx.line.color);

        float strokeWidth = (float) (ctx.line.thickness * ctx.scale);
        g.setStroke(buildStroke(strokeWidth, ctx.line.dashPattern));

        /* With passedOnly the track breaks off at the current position: the last segment extends to the interpolated point. */
        int upTo = points.size();
        Point2D.Double tail = null;
        if (ctx.passedOnly.value) {
            long rawTime = ctx.position.rawTime;
            int idx = lowerBoundByTimeRaw(points, rawTime);
            upTo = Math.min(idx + 1, points.size());
            GeoSensorAtom curr = points.get(Math.min(idx, points.size() - 1));
            /* The tail to the current position only if the next point continues the recording (no pause between them). */
            if (idx + 1 < points.size() && curr.continuesWith(points.get(idx + 1))) {
                tail = ctx.toScreen(curr.calcLat(rawTime), curr.calcLon(rawTime));
            }
        }

        /* A polyline of segments between consecutive points. */
        int prevX = Integer.MIN_VALUE, prevY = Integer.MIN_VALUE;
        for (int i = 0; i < upTo; i++) {
            GeoSensorAtom p = points.get(i);
            Point2D.Double pt = ctx.toScreen(p.lat, p.lon);
            int sx = (int) pt.x;
            int sy = (int) pt.y;
            if (prevX != Integer.MIN_VALUE) {
                g.drawLine(prevX, prevY, sx, sy);
            }
            prevX = sx;
            prevY = sy;
        }
        if (tail != null && prevX != Integer.MIN_VALUE) {
            g.drawLine(prevX, prevY, (int) tail.x, (int) tail.y);
        }
    }

    /* Binary search for the last point not later than the given time. */
    private static int lowerBoundByTimeRaw(List<GeoSensorAtom> points, long t) {
        int lo = 0;
        int hi = points.size();
        while (lo < hi) {
            int mid = (lo + hi) >>> 1;
            if (points.get(mid).timeRaw <= t) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        return Math.max(0, lo - 1);
    }

    /* A dash from the pattern "length,gap,..."; with an empty or wrong pattern, a solid line. */
    private static BasicStroke buildStroke(float width, String pattern) {
        if (pattern == null || pattern.isBlank()) {
            return new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        }
        String[] parts = pattern.split(",");
        float[] dash = new float[parts.length];
        try {
            for (int i = 0; i < parts.length; i++) {
                dash[i] = Float.parseFloat(parts[i].trim());
                if (dash[i] <= 0) {
                    throw new NumberFormatException();
                }
            }
        } catch (NumberFormatException ex) {
            return new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        }
        return new BasicStroke(width,
                BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                10f, dash, 0f
        );
    }

    /* Figure context: the property values on the frame. */
    public class TrackContext extends GeoFigureContext {

        public final GeoSensorProperty.GeoSensorContext position;
        public final LineProperty.LineContext line;
        public final VisibleProperty.BooleanContext passedOnly;

        public TrackContext(GeoMapIndicator.GeoMapContext indCtx) {
            super(indCtx);
            position = mGeoSensor.createContext(indCtx);
            line = mLine.createContext(indCtx);
            passedOnly = mPassedOnly.createContext(indCtx);
        }
    }

    @Override
    /* Creating a context from the indicator context. */
    public GeoFigureContext createContext(IndicatorContext indCtx) {
        TrackContext ctx = new TrackContext((GeoMapIndicator.GeoMapContext) indCtx);
        return ctx;
    }

}

Purpose

GeoTrackFigure draws on the map the GPS track line of the selected geo sensor. It is one of the two figures that GeoMapIndicator adds by default. The line is configured as an ordinary line (color, thickness, style, pattern), and the "Passed only" flag leaves visible only the part of the track up to the current moment.

How it works

Data. GeoSensorProperty with the track query (anyLevel(), zoom = {zoom}, sorting by timeRaw, a cache for two parameter sets) returns a list of GeoSensorAtom. The anyLevel() call removes the restriction of the query to exact atoms: the track is read from simplified copies at the needed scale, and the level is chosen by the condition zoom = {zoom}. The query zoom is ctx.position.approximateZoom(ctx.zoom.getLevel()), that is, the nearest available set of points. If there are fewer than two points, sensorId == 0 or the indicator zoom is null, nothing is drawn. The current time is taken from ctx.position.rawTime.

Settings. Three properties saved in the figure JSON: Geo, line and passedOnly. line is a LineProperty (the default color is (200, 0, 0), thickness 1..30 with the default 5, style "Solid"). passedOnly is a VisibleProperty, off by default. The Geo property is not declared in configureDisplay(), so it is not shown as a separate row in the figure settings list.

Drawing. The thickness is multiplied by the scale of the layer. The dash is built from dashPattern with round caps and joins. Each point is converted by the method toScreen(lat, lon) (GeoFigureContext) and reduced to whole pixels, then neighboring points are connected with drawLine. With passedOnly on, the points up to the current one inclusive are taken, and the last segment goes to the interpolated position (calcLat / calcLon), but only if the next point continues the same recording (continuesWith); in a recording pause and at the last point there is no "tail", the line ends at the last point before the pause. The polyline itself is not broken by pauses: neighboring track points are always connected.

Features and limitations

  • The line is drawn by segments over whole coordinates: at very small scales the segments can turn into steps.
  • The whole track is walked on every frame, without clipping by the visible area; for long tracks the cost of a frame grows linearly.
  • The dash pattern accepts numbers separated by commas; any non-numeric or non-positive value gives a solid line.
  • The Geo of the figure and the Geo of the indicator are independent properties; each has its own selected source (in a template the source is selected anew).
  • The order of figures in the list determines the drawing order: figures added later are drawn on top.

Clone this wiki locally