Skip to content

GeoMapIndicator

roosit edited this page Oct 16, 2026 · 4 revisions

GeoMapIndicator

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 GeoMapIndicator.java: the production code stays clean, and the explanations live in the wiki.

package com.velitask.plugin.official;

import com.velitask.plugin.official.geo.GeoPlaceBoundaryFigure;
import com.velitask.plugin.official.geo.GeoPlaceLabelsFigure;
import com.velitask.plugin.official.geo.GeoPositionFigure;
import com.velitask.plugin.official.geo.GeoTrackFigure;
import com.velitask.sdk.FrameContext;
import com.velitask.sdk.Indicator;
import com.velitask.sdk.IndicatorContext;
import com.velitask.sdk.IndicatorSkin;
import com.velitask.sdk.data.GeoSensorAtom;
import com.velitask.sdk.data.LandBounds;
import com.velitask.sdk.db.DataCacheRule;
import com.velitask.sdk.db.DataParams;
import com.velitask.sdk.figures.IFigure;
import com.velitask.sdk.properties.ArrayProperty;
import com.velitask.sdk.properties.BorderProperty;
import com.velitask.sdk.properties.DisplayConfig;
import com.velitask.sdk.properties.DisplayHint;
import com.velitask.sdk.properties.EnumArrayProperty;
import com.velitask.sdk.properties.FitTrackProperty;
import com.velitask.sdk.properties.GeoSensorProperty;
import com.velitask.sdk.properties.GeoZoomProperty;
import com.velitask.sdk.properties.IProperty;
import com.velitask.sdk.properties.IntegerProperty;
import com.velitask.sdk.properties.MapTilesProperty;
import com.velitask.sdk.properties.PropertyGroup;
import com.velitask.sdk.properties.TransparencyProperty;
import com.velitask.sdk.properties.VisibleProperty;
import com.velitask.units.angle.TrackBearing;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.util.List;
import org.abricos.core.state.maket.HorizontalAlign;
import org.abricos.core.state.maket.Maket;
import org.abricos.core.state.maket.VerticalAlign;
import org.abricos.geo.GeoUtils;
import org.abricos.geo.MapZoom;
import org.abricos.geo.tile.Tile;
import org.abricos.geo.tile.TilePixel;
import org.json.JSONObject;

public class GeoMapIndicator extends Indicator {

    /* The indicator name; it is part of the layer identifier and of JSON. */
    public static final String NAME = "geoMap";

    /* The prefix of the localization keys of the indicator and its figures. */
    public static final String KEY = _KEY + "." + NAME;

    /* Rotation mode: north up, heading up, manual. The index is stored in JSON. */
    public enum RotationMode {
        NORTH_UP, HEADING_UP, MANUAL
    }

    /* Where on the map the current position is: in the center or in the bottom third. The index is stored in JSON. */
    public enum VehicleAnchor {
        CENTER, BOTTOM_THIRD
    }

    /* The choice of the geo sensor. The track query returns the track points for the current zoom, by time. */
    private final GeoSensorProperty mGeoSensor = new GeoSensorProperty();

    {
        mGeoSensor.query("track")
                .where("zoom = {zoom}")
                .orderBy("timeRaw")
                .cache(DataCacheRule.byParams())
                .cacheSize(2)
                .buildList();
    }

    /* Access to the OSM raster tiles; not saved in JSON. */
    private final MapTilesProperty mTiles = new MapTilesProperty();

    /* The map zoom (8..19, 14 by default); locked by "Fit track". */
    private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();

    /* The transparency of the map tiles in percent (0..100). */
    private final TransparencyProperty mMapTransparency = new TransparencyProperty();

    /* The visibility of the map tiles. The track and the other figures do not depend on it. */
    private final VisibleProperty mShowMap = new VisibleProperty();

    /* The border around the map: color, thickness, line style and corner radius. */
    private final BorderProperty mBorder = new BorderProperty();

    /* The tilt angle 0..85, 50 by default; active only when the 3D view is on. */
    private final IntegerProperty mTilt = new IntegerProperty() {
        {
            setRange(0, 85);
        }

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

        @Override
        public Integer getDefault() {
            return 50;
        }

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

    /* The 3D view switch (off by default); it enables and disables the tilt field. */
    private final VisibleProperty mView3D = new VisibleProperty() {
        {
            setDefault(false);
            set(false);
        }

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

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

        @Override
        public IProperty[] dependents() {
            return new IProperty[]{mTilt};
        }

        @Override
        protected void onChanged(Object oldVal, Object newVal) {
            mTilt.setEnabled(Boolean.TRUE.equals(newVal));
        }

        @Override
        public void fromJSON(JSONObject json) {
            super.fromJSON(json);
            mTilt.setEnabled(get());
        }
    };

    /* The bearing for the "Manual" mode, 0..359, 0 by default. */
    private final IntegerProperty mManualBearing = new IntegerProperty() {
        {
            setRange(0, 359);
        }

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

        @Override
        public Integer getDefault() {
            return 0;
        }

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

    /* The minimum speed (km/h, 0..50, 2 by default) at which the bearing is updated in the "Heading up" mode. */
    private final IntegerProperty mMinSpeedKmh = new IntegerProperty() {
        {
            setRange(0, 50);
        }

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

        @Override
        public Integer getDefault() {
            return 2;
        }

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

    /* The vehicle anchor: center (default) or bottom third. */
    private final EnumArrayProperty<VehicleAnchor> mVehicleAnchor
            = new EnumArrayProperty<>(VehicleAnchor.class) {
        @Override
        public String getName() {
            return "vehicleAnchor";
        }

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

        @Override
        protected String[] defineTitles() {
            return new String[]{
                localized(KEY + ".vehicleAnchor.center"),
                localized(KEY + ".vehicleAnchor.bottomThird")
            };
        }
    };

    /* The rotation mode; it enables the manual bearing or the minimum speed depending on the mode. */
    private final EnumArrayProperty<RotationMode> mRotation
            = new EnumArrayProperty<>(RotationMode.class) {
        @Override
        public String getName() {
            return "rotation";
        }

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

        @Override
        protected String[] defineTitles() {
            return new String[]{
                localized(KEY + ".rotation.northUp"),
                localized(KEY + ".rotation.headingUp"),
                localized(KEY + ".rotation.manual")
            };
        }

        @Override
        public IProperty[] dependents() {
            return new IProperty[]{mManualBearing, mMinSpeedKmh};
        }

        @Override
        protected void onChanged(Object oldVal, Object newVal) {
            applyRotationDependents();
        }

        @Override
        public void fromJSON(JSONObject json) {
            super.fromJSON(json);
            applyRotationDependents();
        }
    };

    /* "Fit track": show the whole track instead of following the position; locks the zoom. */
    private final FitTrackProperty mFitTrack = new FitTrackProperty() {
        @Override
        public IProperty[] dependents() {
            return new IProperty[]{mGeoZoom};
        }

        @Override
        protected void onChanged(Object oldVal, Object newVal) {
            mGeoZoom.setEnabled(!Boolean.TRUE.equals(newVal));
        }

        @Override
        public void fromJSON(JSONObject json) {
            super.fromJSON(json);
            mGeoZoom.setEnabled(!get());
        }
    };

    /* The last valid movement bearing: held while the speed is below the threshold. */
    private double mLastValidBearingDeg = 0;

    /* Enables the manual bearing only for the "Manual" mode, and the speed threshold only for "Heading up". */
    private void applyRotationDependents() {
        RotationMode m = mRotation.get();
        mManualBearing.setEnabled(m == RotationMode.MANUAL);
        mMinSpeedKmh.setEnabled(m == RotationMode.HEADING_UP);
    }

    /* Access to the geo property for code outside the indicator. */
    public GeoSensorProperty getGeo() {
        return mGeoSensor;
    }

    public FitTrackProperty getFitTrack() {
        return mFitTrack;
    }

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

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

    @Override
    public String getDescription() {
        return localized(KEY + ".description");
    }

    @Override
    public String getTags() {
        return localized(KEY + ".tags");
    }

    @Override
    /* Default maket: a 700×400 layer pinned to the bottom left corner, margin 50. */
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.BOTTOM);
        maket.setHorizontal(HorizontalAlign.LEFT);
        maket.setLayerMargin(50d, null, null, 50d);
        maket.setLayerSize(700d, 400d);
    }

    @Override
    /* The property order; they are saved by name, except mTiles (not a Property). */
    public IProperty[] defineProperties() {
        return new IProperty[]{
            mGeoSensor, mTiles, mShowMap, mFitTrack, mGeoZoom, mMapTransparency, mBorder,
            mView3D, mTilt, mRotation, mManualBearing, mMinSpeedKmh, mVehicleAnchor
        };
    }

    @Override
    /* All settings are in the appearance group; the tilt and the manual bearing are sliders. */
    public void configureDisplay(DisplayConfig config) {
        config.set(mShowMap, PropertyGroup.APPEARANCE);
        config.set(mFitTrack, PropertyGroup.APPEARANCE);
        config.set(mGeoZoom, PropertyGroup.APPEARANCE);
        config.set(mMapTransparency, PropertyGroup.APPEARANCE);
        config.set(mBorder, PropertyGroup.APPEARANCE);
        config.set(mView3D, PropertyGroup.APPEARANCE);
        config.set(mTilt, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
        config.set(mRotation, PropertyGroup.APPEARANCE);
        config.set(mManualBearing, PropertyGroup.APPEARANCE, DisplayHint.SLIDER);
        config.set(mMinSpeedKmh, PropertyGroup.APPEARANCE);
        config.set(mVehicleAnchor, PropertyGroup.APPEARANCE);
    }

    @Override
    @SuppressWarnings("unchecked")
    /* The figures the user can add to the map. */
    public Class<? extends IFigure>[] supportedFigures() {
        return (Class<? extends IFigure>[]) new Class<?>[]{
            GeoPlaceBoundaryFigure.class,
            GeoTrackFigure.class,
            GeoPositionFigure.class,
            GeoPlaceLabelsFigure.class
        };
    }

    @Override
    @SuppressWarnings("unchecked")
    /* The figures added automatically: the track and the position. */
    public Class<? extends IFigure>[] defaultFigures() {
        return (Class<? extends IFigure>[]) new Class<?>[]{
            GeoTrackFigure.class,
            GeoPositionFigure.class
        };
    }

    @Override
    /* Two skins: "Faded" (the map is visible, transparency 60) and "No map". */
    public IndicatorSkin[] defineSkins() {
        return new IndicatorSkin[]{
            IndicatorSkin.builder("faded", localized(KEY + ".skin.faded"))
            .set(mShowMap.skin(true))
            .set(mMapTransparency.skin(60))
            .build(),
            IndicatorSkin.builder("hidden", localized(KEY + ".skin.hidden"))
            .set(mShowMap.skin(false))
            .build()
        };
    }

    @Override
    /* Draws only the tiles and the border; the track, the position and the labels are drawn by the figures. */
    public void render(IndicatorContext indicatorContext) {
        GeoMapContext ctx = (GeoMapContext) indicatorContext;
        Graphics2D g = ctx.graphics;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        if (!ctx.showMap.value) {
            return;
        }

        renderMap(ctx);
    }

    /* Tile drawing: clip to the rounding, the map through mapTransform, then the border. */
    private void renderMap(GeoMapContext ctx) {
        Graphics2D g = ctx.graphics;
        int w = ctx.width, h = ctx.height;

        MapZoom zoom = ctx.zoom;
        if (zoom == null) {
            return;
        }

        Shape oldClip = g.getClip();
        int radius = (int) (ctx.border.radius * ctx.scale);
        if (radius > 0) {
            g.setClip(new RoundRectangle2D.Double(0, 0, w, h, radius * 2.0, radius * 2.0));
        }

        AffineTransform oldTransform = g.getTransform();
        g.transform(ctx.mapTransform);

        /* Half of the visible area in map pixels, taking into account the "fit track" scale and the tilt. */
        double invExtra = 1.0 / Math.max(0.0001, ctx.extraScale);
        double halfW = w / 2.0 * invExtra;
        double halfH;
        if (ctx.tiltRad > 0) {
            double cosTilt = Math.cos(ctx.tiltRad);
            halfH = (h / 2.0 + ctx.anchorOffsetY) / Math.max(0.05, cosTilt) * invExtra;
        } else {
            halfH = h / 2.0 * invExtra;
        }

        double centerX = ctx.centerPx;
        double centerY = ctx.centerPy;

        int xIndexMin, yIndexMin, xIndexMax, yIndexMax;
        if (ctx.bearingRad == 0 && ctx.tiltRad == 0) {
            xIndexMin = Math.max(
                    (int) Math.floor((centerX - halfW) / GeoUtils.TILE_SIZE) - 1, 0);
            yIndexMin = Math.max(
                    (int) Math.floor((centerY - halfH) / GeoUtils.TILE_SIZE) - 1, 0);
            xIndexMax = (int) Math.floor((centerX + halfW) / GeoUtils.TILE_SIZE) + 1;
            yIndexMax = (int) Math.floor((centerY + halfH) / GeoUtils.TILE_SIZE) + 1;
        } else {
            double radiusPx = Math.hypot(halfW, halfH) + GeoUtils.TILE_SIZE;
            xIndexMin = Math.max(
                    (int) Math.floor((centerX - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
            yIndexMin = Math.max(
                    (int) Math.floor((centerY - radiusPx) / GeoUtils.TILE_SIZE) - 1, 0);
            xIndexMax = (int) Math.floor((centerX + radiusPx) / GeoUtils.TILE_SIZE) + 1;
            yIndexMax = (int) Math.floor((centerY + radiusPx) / GeoUtils.TILE_SIZE) + 1;
        }

        /* Tiles above this line (beyond the "horizon" in 3D) are skipped. */
        double horizonCullY = -halfH * 1.5;

        Composite oldComp = g.getComposite();
        float alpha = Math.max(0, Math.min(1, 1f - ctx.mapTransparency.value / 100f));
        if (alpha < 1f) {
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        }

        /* The tile loop: in preview — from the cache without waiting, on export — waiting up to 5 s. */
        int zoomValue = zoom.getLevel();
        for (int tx = xIndexMin; tx <= xIndexMax; tx++) {
            for (int ty = yIndexMin; ty <= yIndexMax; ty++) {
                double localY = ty * GeoUtils.TILE_SIZE - centerY;
                if (localY + GeoUtils.TILE_SIZE < horizonCullY) {
                    continue;
                }
                Tile tile = ctx.player.isPreview
                        ? mTiles.getTile(zoomValue, tx, ty)
                        : mTiles.getTileBlocking(zoomValue, tx, ty, 5_000);
                if (tile == null || tile.getImage() == null) {
                    continue;
                }
                g.drawImage(tile.getImage(),
                        tx * GeoUtils.TILE_SIZE, ty * GeoUtils.TILE_SIZE, null);
            }
        }

        g.setComposite(oldComp);
        g.setTransform(oldTransform);

        if (radius > 0) {
            g.setClip(oldClip);
        }

        drawBorder(g, ctx, w, h, radius);
    }

    /* The border is drawn over the map in screen coordinates, without rotation. */
    private static void drawBorder(Graphics2D g, GeoMapContext ctx, int w, int h, int radius) {
        int bw = (int) (ctx.border.thickness * ctx.scale);
        if (bw <= 0) {
            return;
        }
        g.setColor(ctx.border.color);
        g.setStroke(new BasicStroke(bw));
        int bx = bw / 2, by = bw / 2;
        int bw2 = Math.max(1, w - bw);
        int bh2 = Math.max(1, h - bw);
        if (radius > 0) {
            g.drawRoundRect(bx, by, bw2, bh2, radius * 2, radius * 2);
        } else {
            g.drawRect(bx, by, bw2, bh2);
        }
    }

    /* The result of the selection: an integer zoom and an extra scale. */
    private record FitZoom(int intZoom, double extraScale) {

    }

    /* The √2 threshold: the zoom is raised until the track goes beyond the area by more than √2 times. */
    private static final double FIT_THRESHOLD = Math.sqrt(2.0);

    /* Picks the zoom and the fractional scale so that the track fits with 5% margins (4..40 px). */
    private static FitZoom computeFitZoom(int baseWidth, int baseHeight, LandBounds b) {
        int padding = Math.max(4, Math.min(40,
                (int) Math.round(Math.min(baseWidth, baseHeight) * 0.05)));
        int innerW = Math.max(1, baseWidth - 2 * padding);
        int innerH = Math.max(1, baseHeight - 2 * padding);

        int intZoom = GeoUtils.ZOOM_MIN;
        double fitW = 0, fitH = 0;
        for (int i = GeoUtils.ZOOM_MIN; i <= GeoUtils.ZOOM_MAX; i++) {
            TilePixel px1 = GeoUtils.getTileX(b.lonMin(), i);
            TilePixel py1 = GeoUtils.getTileY(b.latMin(), i);
            TilePixel px2 = GeoUtils.getTileX(b.lonMax(), i);
            TilePixel py2 = GeoUtils.getTileY(b.latMax(), i);

            double figureWidth = Math.abs(px2.getPixelGlobal() - px1.getPixelGlobal());
            double figureHeight = Math.abs(py2.getPixelGlobal() - py1.getPixelGlobal());

            if (figureWidth > innerW * FIT_THRESHOLD
                    || figureHeight > innerH * FIT_THRESHOLD) {
                if (i == GeoUtils.ZOOM_MIN) {
                    double extra = Math.min(innerW / figureWidth, innerH / figureHeight);
                    return new FitZoom(GeoUtils.ZOOM_MIN, extra);
                }
                break;
            }
            intZoom = i;
            fitW = figureWidth;
            fitH = figureHeight;
        }

        if (fitW <= 0 || fitH <= 0) {
            return new FitZoom(intZoom, 1.0);
        }
        double extra = Math.min(innerW / fitW, innerH / fitH);
        return new FitZoom(intZoom, extra);
    }

    /* The window of track points for computing the movement bearing. */
    private static final int BEARING_WINDOW = 16;

    /* The bearing from the next 16 track points after the current time; NaN if there are too few points. */
    private double computeHeadingBearing(MapZoom zm, GeoSensorProperty.GeoSensorContext position) {
        int actualZoom = position.approximateZoom(zm.getLevel());
        DataParams params = DataParams.of("sensorId", position.sensorId)
                .set("zoom", actualZoom);
        List<GeoSensorAtom> points = position.queryList("track", params);
        if (points == null || points.size() < 2) {
            return Double.NaN;
        }
        int from = lowerBoundByTimeRaw(points, position.rawTime);
        if (from >= points.size() - 1) {
            from = points.size() - 2;
        }
        int to = Math.min(from + BEARING_WINDOW, points.size());
        if (to - from < 2) {
            return Double.NaN;
        }
        double[] lats = new double[to - from];
        double[] lons = new double[to - from];
        for (int i = from; i < to; i++) {
            GeoSensorAtom p = points.get(i);
            lats[i - from] = p.lat;
            lons[i - from] = p.lon;
        }
        return TrackBearing.fromPoints(lats, lons);
    }

    /* Binary search for the last point with a time less than t. */
    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);
    }

    /* Speed estimate from the atom's coordinate increments and its duration. */
    private static double estimateSpeedKmh(GeoSensorAtom atom) {
        if (atom.duration <= 0) {
            return 0.0;
        }
        double latRad = Math.toRadians(atom.lat);
        double dyM = atom.latDelta * 111_320.0;
        double dxM = atom.lonDelta * 111_320.0 * Math.cos(latRad);
        double distM = Math.hypot(dxM, dyM);
        double seconds = atom.duration / 1000.0;
        return distM / seconds * 3.6;
    }

    /* The frame context: property values and the computed map geometry, shared by the indicator and the figures. */
    public class GeoMapContext extends IndicatorContext {

        /* Property values on the current frame. */
        public final GeoSensorProperty.GeoSensorContext position;
        public final IntegerProperty.IntegerContext mapTransparency;
        public final BorderProperty.BorderContext border;
        public final VisibleProperty.BooleanContext showMap;
        public final FitTrackProperty.BooleanContext fitTrack;
        public final VisibleProperty.BooleanContext view3D;
        public final IntegerProperty.IntegerContext tilt;
        public final IntegerProperty.IntegerContext manualBearing;
        public final IntegerProperty.IntegerContext minSpeedKmh;
        public final ArrayProperty<RotationMode>.ArrayContext rotation;
        public final ArrayProperty<VehicleAnchor>.ArrayContext vehicleAnchor;

        /* The computed geometry: zoom, center in map pixels, bearing, tilt, vehicle offset, extra scale, position and matrix. */
        public final MapZoom zoom;
        public final double centerPx;
        public final double centerPy;
        public final double bearingDeg;
        public final double bearingRad;
        public final double tiltRad;
        public final double anchorOffsetY;
        public final double extraScale;
        public final double posLat;
        public final double posLon;
        public final AffineTransform mapTransform;

        /* The constructor reads the frame properties and builds the map matrix. */
        public GeoMapContext(FrameContext frame) {
            super(frame);
            position = mGeoSensor.createContext(frame);
            fitTrack = mFitTrack.createContext(frame);
            mapTransparency = mMapTransparency.createContext(frame);
            border = mBorder.createContext(frame);
            showMap = mShowMap.createContext(frame);
            view3D = mView3D.createContext(frame);
            tilt = mTilt.createContext(frame);
            manualBearing = mManualBearing.createContext(frame);
            minSpeedKmh = mMinSpeedKmh.createContext(frame);
            rotation = mRotation.createContext(frame);
            vehicleAnchor = mVehicleAnchor.createContext(frame);

            MapZoom zm = null;
            double cPx = 0;
            double cPy = 0;
            double br = 0;
            double extra = 1.0;

            /* Without a selected sensor the zoom stays null and nothing is drawn. */
            if (position.sensorId > 0) {
                /* "Fit track" mode: the center is the middle of the track bounds, the zoom is picked. */
                if (fitTrack.value) {
                    LandBounds b = position.queryLandBounds();
                    if (b != null) {
                        FitZoom fz = computeFitZoom(width, height, b);
                        zm = new MapZoom(fz.intZoom());
                        extra = fz.extraScale();
                        double centerLat = (b.latMin() + b.latMax()) / 2.0;
                        double centerLon = (b.lonMin() + b.lonMax()) / 2.0;
                        cPx = zm.pixelX(centerLon);
                        cPy = zm.pixelY(centerLat);
                    }
                } else {
                    /* Follow mode: the center is the interpolated position at the current moment. */
                    GeoSensorAtom atom = position.queryAtom();
                    if (atom != null) {
                        zm = new MapZoom(mGeoZoom.get(frame));
                        double lat = atom.calcLat(position.rawTime);
                        double lon = atom.calcLon(position.rawTime);
                        cPx = zm.pixelX(lon);
                        cPy = zm.pixelY(lat);

                        /* The movement bearing is updated only at a speed not below the threshold. */
                        if (rotation.value == RotationMode.HEADING_UP) {
                            double speedKmh = estimateSpeedKmh(atom);
                            if (speedKmh >= minSpeedKmh.value) {
                                double deg = computeHeadingBearing(zm, position);
                                if (!Double.isNaN(deg)) {
                                    mLastValidBearingDeg = deg;
                                }
                            }
                            br = mLastValidBearingDeg;
                        }
                    }
                }
            }
            /* The position for the figures (settlement boundaries); NaN if there is no data. */
            double pLat = Double.NaN;
            double pLon = Double.NaN;
            if (position.sensorId > 0) {
                GeoSensorAtom posAtom = position.queryAtom();
                if (posAtom != null) {
                    pLat = posAtom.calcLat(position.rawTime);
                    pLon = posAtom.calcLon(position.rawTime);
                }
            }
            posLat = pLat;
            posLon = pLon;

            /* Assigning the computed values. */
            zoom = zm;
            centerPx = cPx;
            centerPy = cPy;
            bearingDeg = br;

            /* In the "Fit track" mode, rotation, tilt and the vehicle offset are disabled. */
            boolean fit = fitTrack.value;
            boolean is3D = !fit && view3D.value;
            double bRad;
            if (fit) {
                bRad = 0;
            } else {
                bRad = switch (rotation.value) {
                    case NORTH_UP ->
                        0.0;
                    case MANUAL ->
                        Math.toRadians(manualBearing.value);
                    case HEADING_UP ->
                        Math.toRadians(br);
                };
            }
            bearingRad = bRad;
            tiltRad = is3D ? Math.toRadians(tilt.value) : 0.0;
            anchorOffsetY = (!fit && vehicleAnchor.value == VehicleAnchor.BOTTOM_THIRD)
                    ? height / 6.0 : 0.0;
            extraScale = extra;

            /* The map matrix: shift to the center, scale, vertical squeeze for the tilt, rotation, shift of the map center to the origin. */
            AffineTransform t = new AffineTransform();
            t.translate(width / 2.0, height / 2.0 + anchorOffsetY);
            if (extraScale != 1.0) {
                t.scale(extraScale, extraScale);
            }
            if (tiltRad > 0) {
                t.scale(1.0, Math.cos(tiltRad));
            }
            if (bearingRad != 0) {
                t.rotate(-bearingRad);
            }
            t.translate(-centerPx, -centerPy);
            mapTransform = t;
        }
    }

    @Override
    /* Creating the frame context. */
    public GeoMapContext createContext(FrameContext frame) {
        return new GeoMapContext(frame);
    }

}

Purpose

GeoMapIndicator is a map on OpenStreetMap tiles that follows the current position from the project's geo sensor (or shows the whole track at once). Figures are drawn on top of the tiles: by default the track and the position marker, and additionally the settlement boundaries and labels. It supports map rotation (north up, heading up, manual), a 3D tilt and shifting the position to the bottom third.

Related pages: indicator JSON, user description, user JSON template. Figures: GeoFigureContext, GeoTrackFigure, GeoPositionFigure, GeoPlaceBoundaryFigure, GeoPlaceLabelsFigure.

How it works

Data. GeoSensorProperty provides a GeoSensorAtom with the lat / lon coordinates and increments. The current point is taken through position.queryAtom() and interpolated to the frame moment by the calcLat(rawTime) / calcLon(rawTime) methods. For the "Fit track" mode, position.queryLandBounds() is used — the bounding rectangle of the whole track (LandBounds). For the movement bearing, the list of track points is requested for the zoom closest to an available one (approximateZoom), and 16 points are taken starting from the current time; the bearing is computed by TrackBearing.fromPoints. The speed for the threshold is estimated from the atom's latDelta / lonDelta and duration. The tiles come through MapTilesProperty (getTile in preview, getTileBlocking waiting for 5 s on export).

Settings. Thirteen properties in defineProperties(): Geo, mapTiles (not saved), visible, fitTrack, geoZoom, transparency, border, view3D, tilt, rotation, manualBearing, minSpeedKmh, vehicleAnchor. Dependencies between them: "Fit track" locks the zoom; the 3D view unlocks the tilt angle; the "Manual" mode unlocks the manual bearing, and the "Heading up" mode unlocks the minimum speed. Skins: "Faded" (visible = true, transparency = 60) and "No map" (visible = false). The figures are set through supportedFigures() (four classes) and defaultFigures() (the track and the position).

Drawing. The GeoMapContext constructor computes the zoom, the map center in pixels (centerPx, centerPy), the bearing, the tilt and the mapTransform matrix: a shift to the vehicle point, the extraScale scale, a vertical squeeze by cos(tilt), a rotation by -bearing, a shift to the map center. render() turns on anti-aliasing, then, if the map is visible, renderMap() limits the area with a rounded rectangle, applies mapTransform, goes over the tiles around the center (with rotation or tilt — a square with a radius equal to the diagonal), draws them taking the transparency into account, and finally draws the border in screen coordinates. The figures are drawn by the runtime after the indicator, and each gets a GeoFigureContext with the same matrix.

Particulars and limitations

  • While no geo sensor is selected (sensorId == 0) or it has no points, the zoom is null: tiles and figures are not drawn.
  • The "Fit track" mode ignores rotation, tilt and the vehicle offset; the map zoom is not used then. The integer zoom is picked from 8 to 19, and the remainder is covered by the fractional extraScale.
  • In the "Heading up" mode the bearing is updated only at a speed not below the threshold, otherwise it stays at the last valid one. It is stored in an indicator field (mLastValidBearingDeg), not in the frame, so on rewinding and re-rendering the result depends on the order of frames.
  • The 3D tilt is an affine vertical squeeze of the map, not a perspective. Tiles above horizonCullY are skipped.
  • Tiles are requested at an integer zoom, the maximum zoom is 19 (GeoUtils.ZOOM_MAX), the minimum is 8 (GeoUtils.ZOOM_MIN).
  • The border is drawn before the figures; the figures themselves are not clipped by the border rounding.
  • Transparency applies only to the tiles; the border and the figures are drawn opaque.

Clone this wiki locally