Skip to content

GeoMapIndicator

roosit edited this page May 15, 2026 · 4 revisions

GeoMapIndicator

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

Full source code with brief explanations

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

package com.velitask.plugin.official;

import com.velitask.plugin.official.geo.GeoPositionFigure;
import com.velitask.plugin.official.geo.GeoTrackFigure;
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.figures.IFigure;
import com.velitask.sdk.osm.OSMTile;
import com.velitask.sdk.properties.DisplayConfig;
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 java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
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.TilePixel;

/*
 * OSM tile map with support for overlaying figures (track and current position).
 * Centers either on the current position (by geo sensor), or on the bounds of
 * the whole track (fitTrack). Supports map transparency and fully hiding the
 * background (when only figures are needed on an empty canvas).
 */
public class GeoMapIndicator extends Indicator {

    public static final String NAME = "geoMap";

    public static final String KEY = _KEY + "." + NAME;

    /* Geo data source (latitude/longitude). */
    private final GeoSensorProperty mGeoSensor = new GeoSensorProperty();

    /* OSM tile source (URL template, tile cache). */
    private final MapTilesProperty mTiles = new MapTilesProperty();

    /* Map zoom level, used when fitTrack=false. */
    private final GeoZoomProperty mGeoZoom = new GeoZoomProperty();

    /* OSM tile transparency 0..100; does not affect figures. */
    private final TransparencyProperty mMapTransparency = new TransparencyProperty();

    /* Whether to show the OSM background at all. False = empty canvas, figures only. */
    private final VisibleProperty mShowMap = new VisibleProperty();

    /*
     * Auto zoom: when enabled, automatically computes zoom so the whole track
     * fits into the layer. dependents() tells the SDK that mGeoZoom is dependent
     * (UI needs redraw). onChanged disables mGeoZoom when fitTrack=true.
     */
    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(org.json.JSONObject json) {
            super.fromJSON(json);
            mGeoZoom.setEnabled(!get());
        }
    };

    /* Access from figures: GeoPositionFigure / GeoTrackFigure read this sensor. */
    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"); }

    /* Initial layout: bottom-left, 50/50 margins, size 700x400. */
    @Override
    public void defineMaket(Maket maket) {
        maket.setVertical(VerticalAlign.BOTTOM);
        maket.setHorizontal(HorizontalAlign.LEFT);
        maket.setLayerMargin(50d, null, null, 50d);
        maket.setLayerSize(700d, 400d);
    }

    @Override
    public IProperty[] defineProperties() {
        return new IProperty[]{mGeoSensor, mTiles, mShowMap, mFitTrack, mGeoZoom, mMapTransparency};
    }

    @Override
    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);
    }

    /*
     * Supported figures: track and current position point.
     * defaultFigures = supportedFigures — both are created automatically.
     */
    @Override
    @SuppressWarnings("unchecked")
    public Class<? extends IFigure>[] supportedFigures() {
        return (Class<? extends IFigure>[]) new Class<?>[]{
            GeoTrackFigure.class,
            GeoPositionFigure.class
        };
    }

    @Override
    @SuppressWarnings("unchecked")
    public Class<? extends IFigure>[] defaultFigures() {
        return (Class<? extends IFigure>[]) new Class<?>[]{
            GeoTrackFigure.class,
            GeoPositionFigure.class
        };
    }

    /*
     * Two built-in skins:
     *   faded — map is shown, but transparency is 60% (for overlaying on video);
     *   hidden — map is hidden, only figures remain.
     */
    @Override
    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()
        };
    }

    /*
     * Render: draws only OSM tiles. Figures (track, position) are drawn
     * separately on top by the SDK — this class does not touch them in render(),
     * it only declares supportedFigures().
     */
    @Override
    public void render(IndicatorContext indicatorContext) {
        GeoMapContext ctx = (GeoMapContext) indicatorContext;
        Graphics2D g = ctx.graphics;

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

        if (ctx.showMap.value) {
            renderMap(ctx);
        }
    }

    /*
     * Tile render: computes which OSM tiles are needed to cover the layer
     * around the current center, draws each one. With ±2 tile reserve so it
     * does not jitter during movement.
     */
    private void renderMap(GeoMapContext ctx) {
        Graphics2D g = ctx.graphics;
        int w = ctx.width, h = ctx.height;

        MapZoom zoom = ctx.zoom;
        if (zoom == null) {
            return;
        }
        double centerX = ctx.centerPx;
        double centerY = ctx.centerPy;
        double topLeftX = centerX - w / 2.0;
        double topLeftY = centerY - h / 2.0;

        /* Tile indexes: from topLeft minus 1 tile reserve on the left/top. */
        int xIndexMin = Math.max((int) Math.floor(topLeftX / GeoUtils.TILE_SIZE) - 1, 0);
        int yIndexMin = Math.max((int) Math.floor(topLeftY / GeoUtils.TILE_SIZE) - 1, 0);

        /* +2 reserve on the right/bottom — overshoot for smooth panning. */
        int xIndexMax = xIndexMin
                + (int) Math.max(Math.ceil((double) w / GeoUtils.TILE_SIZE), 1) + 2;
        int yIndexMax = yIndexMin
                + (int) Math.max(Math.ceil((double) h / GeoUtils.TILE_SIZE), 1) + 2;

        /* Pixel offset from topLeft to the start of the first tile. */
        double dx = xIndexMin * GeoUtils.TILE_SIZE - topLeftX;
        double dy = yIndexMin * GeoUtils.TILE_SIZE - topLeftY;

        /* Transparency: 100 → fully transparent (alpha=0). */
        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));
        }

        /*
         * In preview (live editor) — getTile (immediate, can return null
         * for a tile not loaded yet; cache is filled async).
         * In final render — getTileBlocking with 5 second timeout:
         * export waits until the tile is loaded.
         */
        int zoomValue = zoom.getLevel();
        for (int tx = xIndexMin; tx <= xIndexMax; tx++) {
            double x = (tx - xIndexMin) * GeoUtils.TILE_SIZE + dx;
            for (int ty = yIndexMin; ty <= yIndexMax; ty++) {
                OSMTile tile = ctx.player.isPreview
                        ? mTiles.getTile(zoomValue, tx, ty)
                        : mTiles.getTileBlocking(zoomValue, tx, ty, 5_000);
                if (tile == null || tile.getImage() == null) {
                    continue;
                }
                double y = (ty - yIndexMin) * GeoUtils.TILE_SIZE + dy;
                g.drawImage(tile.getImage(), (int) x, (int) y, null);
            }
        }

        g.setComposite(oldComp);
    }

    /*
     * Zoom selection for fitTrack: iterate from ZOOM_MIN to ZOOM_MAX,
     * looking for the maximum level at which track bounds still fit
     * entirely into (width, height). On first overflow — break, return
     * the previous level.
     */
    private static int computeFitZoom(int width, int height, LandBounds b) {
        int zoom = GeoUtils.ZOOM_MIN;
        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 > width || figureHeight > height) {
                break;
            }
            zoom = i;
        }
        return zoom;
    }

    /*
     * Context computes center and zoom directly in the constructor.
     * Logic: if fitTrack — track bounds, otherwise — current atom position.
     * If sensor is not bound or there is no data — zoom=null, render exits.
     */
    public class GeoMapContext extends IndicatorContext {

        public final IntegerProperty.IntegerContext mapTransparency;
        public final VisibleProperty.BooleanContext showMap;
        public final FitTrackProperty.BooleanContext fitTrack;

        public final MapZoom zoom;
        public double centerPx;
        public double centerPy;

        public GeoMapContext(Player player, Canvas canvas) {
            super(player, canvas);
            fitTrack = mFitTrack.createContext();
            mapTransparency = mMapTransparency.createContext();
            showMap = mShowMap.createContext();

            MapZoom zm = null;
            double cPx = 0;
            double cPy = 0;

            if (mGeoSensor.getSensorId() > 0) {
                if (fitTrack.value) {
                    /*
                     * fitTrack mode: center on bounds, auto-select zoom
                     * so the whole track fits.
                     */
                    LandBounds b = mGeoSensor.queryLandBounds();
                    if (b != null) {
                        zm = new MapZoom(
                                computeFitZoom(width, height, b)
                        );
                        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 {
                    /* Manual mode: center on current position, zoom from user. */
                    long rawTime = mGeoSensor.convertToRawTime(player.time);
                    if (player.isPreview) {
                        rawTime = mGeoSensor.clampToSensorRange(rawTime);
                    }
                    GeoSensorAtom atom = mGeoSensor.queryAtom(rawTime);
                    if (atom != null) {
                        zm = new MapZoom(mGeoZoom.createContext().value);
                        cPx = zm.pixelX(atom.lon);
                        cPy = zm.pixelY(atom.lat);
                    }
                }
            }
            zoom = zm;
            centerPx = cPx;
            centerPy = cPy;
        }
    }

    @Override
    public GeoMapContext createContext(IndicatorContext.Player player, IndicatorContext.Canvas canvas) {
        return new GeoMapContext(player, canvas);
    }

}

Purpose

GeoMapIndicator is an OSM map layer with support for figures (track and current position). It centers either on the current position by GeoSensorProperty, or on the bounds of the entire track (fitTrack=true — automatically selects zoom). Supports tile transparency (for overlaying the map on video) and fully hiding the OSM background (when only figures are needed on an empty canvas).

How it works

Data. GeoSensorProperty for the current position (GeoSensorAtom with lat/lon) and bounds of the whole track through queryLandBounds(). OSM tiles — through MapTilesProperty (URL template + thread-safe tile cache). The indicator itself draws only tiles — figures (track, position marker) are drawn separately on top by the SDK through supportedFigures()/defaultFigures().

Settings. Six properties: geo source, tile source, VisibleProperty showMap (show OSM background), FitTrackProperty (auto zoom by bounds; when enabled, disables manual geoZoom through dependents()+onChanged), GeoZoomProperty (manual zoom), TransparencyProperty (0..100%).

Drawing. In the context, center+zoom is computed first (if fitTrack — computeFitZoom selects the maximum level at which track bounds still fit into (width, height); otherwise — center by current atom, zoom from setting). In render(), it calculates which OSM tiles are needed to cover the layer (with ±2 tile reserve for smoothness), each rendered through g.drawImage. Tile transparency through AlphaComposite.SRC_OVER. In preview — getTile (fast, can return null for an async-loading tile), in final render — getTileBlocking with 5 second timeout (export waits for loading).

Features and limitations

  • The map draws only tiles. Track and position marker are separate IFigure classes (GeoTrackFigure, GeoPositionFigure), managed by the SDK through the context's figures array. If showMap=false and figures are removed, the indicator is completely empty.
  • computeFitZoom uses world pixel coordinates of tiles through TilePixel.getPixelGlobal(). Suitable only for tracks that fit within one zoom level; for very large-scale tracks (continental), the approach works, but zoom = ZOOM_MIN.
  • fitTrack blocks manual zoom — mGeoZoom.setEnabled(false) in onChanged. UI listens to dependents() and redraws the property panel on toggle.
  • Preview vs final tile rendering is different: preview draws placeholder tiles while the cache fills, final render waits for real ones. This is critical for export quality.
  • ±2 tile overshoot in xIndexMax/yIndexMax — intentional reserve so there are no empty edges for 1 frame during map movement while a new tile loads.

Clone this wiki locally