#2681 JavaFX Map Redesign

#2681 Map tab as a JavaFX component

Replaces the Swing JXMapViewer map with a pure JavaFX canvas tile map in gui/map:
OpenStreetMap tiles with a memory and disk cache, track, Radio Reference site and
user location layers, the site hover card and context menu, and the map controls.
Removes the bundled SwingX map viewer copy and moves GeoPosition to the map package.

Co-authored-by: denny <dennis.sheirer@gmail.com>
This commit is contained in:
Denny Sheirer
2026-11-18 02:29:58 -05:00
committed by GitHub
parent bc7dd201ab
commit f47479b8d4
92 changed files with 4248 additions and 10417 deletions

View File

@@ -0,0 +1,35 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import javafx.scene.canvas.GraphicsContext;
/**
* Overlay drawn over the map tiles, in the order the layers were added to the {@link TileMapView}.
*/
public interface MapLayer
{
/**
* Draws the layer. Called on the JavaFX thread.
* @param gc of the map canvas, in screen pixels
* @param map for converting positions to screen pixels
*/
void draw(GraphicsContext gc, TileMapView map);
}

View File

@@ -0,0 +1,59 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.gui.playlist.radioreference.RadioReferencePlaylistActions;
import io.github.dsheirer.gui.theme.ThemeManager;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.MapService;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.service.radioreference.RadioReferenceFrequencyIndex;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
/**
* Swing panel that holds the JavaFX map view for the main application window. The JavaFX view is created on the
* JavaFX application thread after construction.
*/
public class MapPanel extends JFXPanel
{
/**
* Constructs an instance
* @param mapService for the entities to plot
* @param iconModel for alias icons
* @param userPreferences for the map view and the user's location
* @param frequencyIndex of the radio reference frequencies near the user, for the trunked system sites, or null
* @param playlistActions to add sites to the playlist or enable their channels, or null
*/
public MapPanel(MapService mapService, IconModel iconModel, UserPreferences userPreferences,
RadioReferenceFrequencyIndex frequencyIndex, RadioReferencePlaylistActions playlistActions)
{
Platform.setImplicitExit(false);
ThemeManager.getInstance().registerSwing(this);
Platform.runLater(() -> {
MapView view = new MapView(mapService, iconModel, userPreferences, frequencyIndex, playlistActions, true);
Scene scene = new Scene(view);
ThemeManager.getInstance().register(scene);
setScene(scene);
});
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,203 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import io.github.dsheirer.preference.map.MapPreference;
/**
* Part of the world in view: the center point, the tile zoom level and the size of the view in pixels, with the
* conversions between positions and screen pixels. The map repeats east and west, so it can be panned around the
* world, and it stops at the top and bottom of the projection. Not thread safe: use it on the JavaFX thread.
*/
public class MapViewport
{
private double mCenterX = Mercator.x(0);
private double mCenterY = Mercator.y(0);
private int mZoom = 2;
private double mWidth;
private double mHeight;
/**
* Constructs an instance
*/
public MapViewport()
{
}
/**
* Tile zoom level
*/
public int getZoom()
{
return mZoom;
}
/**
* Sets the tile zoom level, keeping the center point
* @param zoom level, clamped to the map preference's range
*/
public void setZoom(int zoom)
{
mZoom = Math.clamp(zoom, MapPreference.MINIMUM_TILE_ZOOM, MapPreference.MAXIMUM_TILE_ZOOM);
clamp();
}
/**
* Changes the zoom level, keeping the position under the screen point in place
* @param zoom level, clamped to the map preference's range
* @param x of the screen point
* @param y of the screen point
*/
public void zoomAt(int zoom, double x, double y)
{
double worldX = (getLeft() + x) / getWorldSize();
double worldY = (getTop() + y) / getWorldSize();
mZoom = Math.clamp(zoom, MapPreference.MINIMUM_TILE_ZOOM, MapPreference.MAXIMUM_TILE_ZOOM);
mCenterX = worldX - (x - mWidth / 2.0) / getWorldSize();
mCenterY = worldY - (y - mHeight / 2.0) / getWorldSize();
clamp();
}
public double getWidth()
{
return mWidth;
}
public double getHeight()
{
return mHeight;
}
/**
* Sets the size of the view, keeping the center point
*/
public void setSize(double width, double height)
{
mWidth = Math.max(0, width);
mHeight = Math.max(0, height);
clamp();
}
/**
* Center point of the view
*/
public GeoPosition getCenter()
{
return new GeoPosition(Mercator.latitude(mCenterY), Mercator.longitude(mCenterX));
}
/**
* Centers the view on the position
*/
public void setCenter(GeoPosition position)
{
mCenterX = Mercator.x(position.getLongitude());
mCenterY = Mercator.y(position.getLatitude());
clamp();
}
/**
* Moves the view by screen pixels, as when the map is dragged by the opposite amount
* @param dx pixels to move the view east
* @param dy pixels to move the view south
*/
public void pan(double dx, double dy)
{
mCenterX += dx / getWorldSize();
mCenterY += dy / getWorldSize();
clamp();
}
/**
* World width and height in pixels at the current zoom level
*/
public double getWorldSize()
{
return Mercator.worldSize(mZoom);
}
/**
* World pixel at the left edge of the view, which is whole so tiles line up with screen pixels. It can be
* negative or past the world width, since the map repeats east and west.
*/
public double getLeft()
{
return Math.round(mCenterX * getWorldSize() - mWidth / 2.0);
}
/**
* World pixel at the top edge of the view, which is whole so tiles line up with screen pixels
*/
public double getTop()
{
return Math.round(mCenterY * getWorldSize() - mHeight / 2.0);
}
/**
* Screen x of the longitude, for the copy of the world nearest the middle of the view
*/
public double getScreenX(double longitude)
{
double worldSize = getWorldSize();
double x = Mercator.x(longitude) * worldSize - getLeft();
double middle = mWidth / 2.0;
return x - Math.round((x - middle) / worldSize) * worldSize;
}
/**
* Screen y of the latitude
*/
public double getScreenY(double latitude)
{
return Mercator.y(latitude) * getWorldSize() - getTop();
}
/**
* Position at the screen point
*/
public GeoPosition getPosition(double x, double y)
{
double worldSize = getWorldSize();
return new GeoPosition(Mercator.latitude((getTop() + y) / worldSize),
Mercator.longitude((getLeft() + x) / worldSize));
}
/**
* Keeps the center within one copy of the world, and the top and bottom of the map at the edges of the view, or
* the map in the middle when it's shorter than the view
*/
private void clamp()
{
mCenterX = mCenterX - Math.floor(mCenterX);
double worldSize = getWorldSize();
double halfHeight = mHeight / 2.0 / worldSize;
if(halfHeight >= 0.5)
{
mCenterY = 0.5;
}
else
{
mCenterY = Math.clamp(mCenterY, halfHeight, 1.0 - halfHeight);
}
}
}

View File

@@ -0,0 +1,100 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
/**
* Web (spherical) Mercator projection used by OpenStreetMap tiles. Positions are expressed as fractions of the world
* width and height (0 to 1), independent of the zoom level: x grows eastward from -180 degrees longitude and y grows
* southward from the top of the map at about 85.05 degrees north latitude.
*/
public final class Mercator
{
/**
* Pixel width and height of a map tile
*/
public static final int TILE_SIZE = 256;
/**
* Northern and southern limit of the projection, where the map is square
*/
public static final double MAX_LATITUDE = 85.05112878;
private Mercator()
{
}
/**
* World width and height in pixels at the zoom level
*/
public static double worldSize(int zoom)
{
return TILE_SIZE * (double)(1L << zoom);
}
/**
* Number of tiles across the world at the zoom level
*/
public static int tileCount(int zoom)
{
return 1 << zoom;
}
/**
* Longitude to a fraction of the world width
*/
public static double x(double longitude)
{
return (longitude + 180.0) / 360.0;
}
/**
* Latitude to a fraction of the world height, clamped to the projection's limits
*/
public static double y(double latitude)
{
double radians = Math.toRadians(Math.clamp(latitude, -MAX_LATITUDE, MAX_LATITUDE));
return (1.0 - Math.log(Math.tan(radians) + 1.0 / Math.cos(radians)) / Math.PI) / 2.0;
}
/**
* Fraction of the world width to a longitude, wrapped into -180 to 180 degrees
*/
public static double longitude(double x)
{
return normalizeLongitude(x * 360.0 - 180.0);
}
/**
* Fraction of the world height to a latitude
*/
public static double latitude(double y)
{
double n = Math.PI * (1.0 - 2.0 * Math.clamp(y, 0.0, 1.0));
return Math.toDegrees(Math.atan(Math.sinh(n)));
}
/**
* Wraps a longitude into -180 to 180 degrees, since the map can be panned past +/-180 degrees
*/
public static double normalizeLongitude(double longitude)
{
return ((longitude + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
}
}

View File

@@ -0,0 +1,220 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.preference.radioreference.RadioReferencePreference;
import io.github.dsheirer.rrapi.type.Coverage;
import io.github.dsheirer.service.radioreference.DistanceFormat;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
/**
* Card with the details of radio reference trunked system sites, shown when the mouse rests over a site's tower on the
* map: the system and protocol, the site, and the site's channels.
*/
public final class SiteCard
{
private static final int MAX_SITES = 3;
private static final int CHANNEL_COLUMNS = 3;
private static final int MAX_CHANNELS = 24;
private static final double MAX_TEXT_WIDTH = 380;
private static final String SEPARATOR = " · ";
private static final String STYLE = "-fx-background-color: -fx-control-inner-background; " +
"-fx-border-color: -fx-box-border; -fx-background-radius: 3; -fx-border-radius: 3; -fx-padding: 6; " +
"-fx-effect: dropshadow(gaussian, rgba(0,0,0,0.35), 6, 0, 1, 2);";
/**
* Channel frequency with a control channel marker: C for control, A for alternate control, or null
*/
public record Channel(String frequency, String marker) {}
/**
* Details of one site
* @param title system name
* @param lines protocol, site, identifiers
* @param channels of the site, up to the card's limit
* @param notes about the channels
*/
public record Entry(String title, List<String> lines, List<Channel> channels, List<String> notes) {}
/**
* Card content
* @param entries for the sites shown, nearest first
* @param moreSites count of the sites under the mouse that aren't shown
*/
public record Content(List<Entry> entries, int moreSites) {}
private SiteCard()
{
}
/**
* Content of the card for the sites
* @param sites under the mouse, nearest first
* @param location of the user, for the distances, or null
*/
public static Content content(List<SiteRecord> sites, RadioReferencePreference.Location location)
{
DecimalFormat frequencyFormat = new DecimalFormat("0.00000");
List<Entry> entries = new ArrayList<>();
int shown = Math.min(sites.size(), MAX_SITES);
for(int index = 0; index < shown; index++)
{
SiteRecord site = sites.get(index);
List<String> lines = new ArrayList<>();
addLine(lines, site.protocol(), site.voice());
String distance = location != null ? DistanceFormat.format(Coverage.distanceKilometers(
location.latitude(), location.longitude(), site.latitude(), site.longitude())) : null;
addLine(lines, "Site " + site.siteNumber(), site.description(), site.county(), distance);
addLine(lines, site.nac() != null ? "NAC " + site.nac() : null,
site.rfss() > 0 ? "RFSS " + site.rfss() : null, site.zone() > 0 ? "Zone " + site.zone() : null);
List<Channel> channels = new ArrayList<>();
List<String> notes = new ArrayList<>();
boolean control = false;
if(site.channels() != null)
{
for(SiteRecord.SiteChannel channel: site.channels().subList(0, Math.min(site.channels().size(),
MAX_CHANNELS)))
{
String marker = "Control".equals(channel.use()) ? "C" :
"Alternate control".equals(channel.use()) ? "A" : null;
control |= marker != null;
channels.add(new Channel(frequencyFormat.format(channel.frequencyHz() / 1E6), marker));
}
if(site.channels().size() > MAX_CHANNELS)
{
notes.add("+ " + (site.channels().size() - MAX_CHANNELS) + " more channels");
}
}
if(control)
{
notes.add("C control, A alternate control");
}
entries.add(new Entry(site.systemName() != null ? site.systemName() : "(unnamed system)", lines,
channels, notes.isEmpty() ? List.of() : List.of(String.join(SEPARATOR, notes))));
}
return new Content(entries, sites.size() - shown);
}
/**
* Card node for the content
*/
public static Region create(Content content)
{
VBox card = new VBox(2);
card.setStyle(STYLE);
card.setMaxWidth(Region.USE_PREF_SIZE);
card.setMaxHeight(Region.USE_PREF_SIZE);
Font font = Font.font(11);
Font bold = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 11);
for(int index = 0; index < content.entries().size(); index++)
{
Entry entry = content.entries().get(index);
if(index > 0)
{
card.getChildren().add(new Separator());
}
card.getChildren().add(label(entry.title(), bold));
entry.lines().forEach(line -> card.getChildren().add(label(line, font)));
if(!entry.channels().isEmpty())
{
GridPane grid = new GridPane();
grid.setHgap(10);
for(int channelIndex = 0; channelIndex < entry.channels().size(); channelIndex++)
{
Channel channel = entry.channels().get(channelIndex);
HBox cell = new HBox(3, label(channel.frequency(), font));
if(channel.marker() != null)
{
cell.getChildren().add(label(channel.marker(), bold));
}
grid.add(cell, channelIndex % CHANNEL_COLUMNS, channelIndex / CHANNEL_COLUMNS);
}
card.getChildren().add(grid);
}
entry.notes().forEach(note -> card.getChildren().add(label(note, font)));
}
if(content.moreSites() > 0)
{
card.getChildren().add(new Separator());
card.getChildren().add(label("+ " + content.moreSites() + " more site" +
(content.moreSites() > 1 ? "s" : "") + " here", font));
}
return card;
}
private static Label label(String text, Font font)
{
Label label = new Label(text);
label.setFont(font);
label.setWrapText(true);
label.setMaxWidth(MAX_TEXT_WIDTH);
return label;
}
/**
* Adds a line with the non-empty values separated by dots, or nothing when all are empty
*/
private static void addLine(List<String> lines, String... values)
{
List<String> parts = new ArrayList<>();
for(String value: values)
{
if(value != null && !value.isBlank())
{
parts.add(value);
}
}
if(!parts.isEmpty())
{
lines.add(String.join(SEPARATOR, parts));
}
}
}

View File

@@ -0,0 +1,156 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.service.radioreference.SiteRecord;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Supplier;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
/**
* Radio reference trunked system sites: a radio tower at each site, with the base of the tower at the site location.
* Use on the JavaFX thread.
*/
public class SiteLayer implements MapLayer
{
private static final Color TOWER = Color.rgb(240, 128, 32);
private static final Color OUTLINE = Color.rgb(40, 40, 40, 200 / 255.0);
private static final double TOWER_WIDTH = 1.6;
private static final double OUTLINE_WIDTH = 3.6;
private static final double HEIGHT = 16;
private static final double HALF_BASE = 5;
//Hit area around the tower, in pixels from the site location
private static final double HIT_LEFT = -10;
private static final double HIT_TOP = -24;
private static final double HIT_WIDTH = 20;
private static final double HIT_HEIGHT = 28;
private final Supplier<List<SiteRecord>> mSites;
private boolean mShowSites = true;
/**
* Constructs an instance
* @param sites to draw, read each time the map is drawn
*/
public SiteLayer(Supplier<List<SiteRecord>> sites)
{
mSites = sites;
}
/**
* Shows or hides the sites
*/
public void setShowSites(boolean show)
{
mShowSites = show;
}
public boolean isShowSites()
{
return mShowSites;
}
/**
* Sites whose tower is under the point, nearest first
* @param viewport of the map
* @param x of the point in the view
* @param y of the point in the view
* @return sites, or an empty list when the sites are hidden or none is under the point
*/
public List<SiteRecord> getSitesAt(MapViewport viewport, double x, double y)
{
if(!mShowSites)
{
return Collections.emptyList();
}
record Hit(SiteRecord site, double distance) {}
List<Hit> hits = new ArrayList<>();
for(SiteRecord site: mSites.get())
{
double dx = x - viewport.getScreenX(site.longitude());
double dy = y - viewport.getScreenY(site.latitude());
if(dx >= HIT_LEFT && dx < HIT_LEFT + HIT_WIDTH && dy >= HIT_TOP && dy < HIT_TOP + HIT_HEIGHT)
{
//Nearest to the middle of the tower first
hits.add(new Hit(site, Math.hypot(dx, dy + (HEIGHT / 2.0))));
}
}
//Stable, so sites at the same spot keep their order
hits.sort(Comparator.comparingDouble(Hit::distance));
return hits.stream().map(Hit::site).toList();
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
if(!mShowSites)
{
return;
}
MapViewport viewport = map.getViewport();
double width = viewport.getWidth();
double height = viewport.getHeight();
gc.setLineCap(StrokeLineCap.ROUND);
gc.setLineJoin(StrokeLineJoin.ROUND);
for(SiteRecord site: mSites.get())
{
double x = viewport.getScreenX(site.longitude());
double y = viewport.getScreenY(site.latitude());
if(x >= -20 && x <= width + 20 && y >= -4 && y <= height + 30)
{
drawTower(gc, x, y, OUTLINE, OUTLINE_WIDTH);
drawTower(gc, x, y, TOWER, TOWER_WIDTH);
gc.setFill(TOWER);
gc.fillOval(x - 2, y - HEIGHT - 2, 4, 4);
}
}
}
/**
* Strokes a tower with its base at the point: an A-frame mast with a cross brace and radio waves at the top
*/
private static void drawTower(GraphicsContext gc, double x, double y, Color color, double lineWidth)
{
double top = y - HEIGHT;
gc.setStroke(color);
gc.setLineWidth(lineWidth);
gc.strokePolyline(new double[]{x - HALF_BASE, x, x + HALF_BASE}, new double[]{y, top, y}, 3);
gc.strokeLine(x - (HALF_BASE * 0.55), y - (HEIGHT * 0.45), x + (HALF_BASE * 0.55), y - (HEIGHT * 0.45));
gc.strokeArc(x - 5, top - 4, 10, 8, 135, 90, ArcType.OPEN);
gc.strokeArc(x - 5, top - 4, 10, 8, -45, 90, ArcType.OPEN);
gc.strokeArc(x - 9, top - 7, 18, 14, 135, 90, ArcType.OPEN);
gc.strokeArc(x - 9, top - 7, 18, 14, -45, 90, ArcType.OPEN);
}
}

View File

@@ -0,0 +1,122 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Entry in the tile server chooser: a server with tiles that follow the theme, or always light or always dark tiles.
* Dark tiles come from the server's dark style, or are recolored light tiles when it has none.
* @param server tile server
* @param style of the tiles
*/
public record TileChoice(TileServer server, Style style)
{
/**
* Tile style. The name is stored in the map preference. Don't change it.
*/
public enum Style
{
THEME(" - Auto"),
LIGHT(" - Light"),
DARK(" - Dark");
private final String mSuffix;
Style(String suffix)
{
mSuffix = suffix;
}
}
/**
* Choices offered to the user, in menu order: each server following the theme, then light, then dark
*/
public static final List<TileChoice> CHOICES;
static
{
List<TileChoice> choices = new ArrayList<>();
for(TileServer server: TileServer.SERVERS)
{
for(Style style: Style.values())
{
choices.add(new TileChoice(server, style));
}
}
CHOICES = Collections.unmodifiableList(choices);
}
/**
* Choice with the server and style
* @param serverId from the map preference, or null
* @param style name from the map preference, or null
* @return choice, following the theme when the style is unknown, see {@link TileServer#get(String)}
*/
public static TileChoice get(String serverId, String style)
{
TileServer server = TileServer.get(serverId);
for(Style candidate: Style.values())
{
if(candidate.name().equals(style))
{
return new TileChoice(server, candidate);
}
}
return new TileChoice(server, Style.THEME);
}
/**
* Indicates if the tiles are dark
* @param darkTheme true when the application uses a dark theme
*/
public boolean isDark(boolean darkTheme)
{
return switch(style)
{
case THEME -> darkTheme;
case LIGHT -> false;
case DARK -> true;
};
}
/**
* Tiles to load
* @param darkTheme true when the application uses a dark theme
* @param key from the user, for a server that needs one, or null
*/
public TileSource getSource(boolean darkTheme, String key)
{
return server.getSource(isDark(darkTheme), key);
}
@Override
public String toString()
{
return server.name() + style.mSuffix;
}
}

View File

@@ -0,0 +1,89 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import javafx.scene.image.Image;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
/**
* Recolors light map tiles for a dark theme: inverts each pixel's lightness while keeping its hue, so a light
* background turns dark, water stays blue and roads keep their colors. The lightness is kept within a range so
* the darkest areas aren't black and the lightest aren't white, and the colors are muted a little.
*/
public final class TileDarkener
{
//Lightness of a white pixel after recoloring, and of a black pixel
static final double DARKEST = 0.10;
static final double LIGHTEST = 0.85;
private static final double SATURATION = 0.80;
private TileDarkener()
{
}
/**
* Recolored copy of the image. Can be called on any thread.
*/
public static Image darken(Image image)
{
int width = (int)image.getWidth();
int height = (int)image.getHeight();
int[] pixels = new int[width * height];
image.getPixelReader().getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
for(int index = 0; index < pixels.length; index++)
{
pixels[index] = darken(pixels[index]);
}
WritableImage darkened = new WritableImage(width, height);
darkened.getPixelWriter().setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
return darkened;
}
/**
* Recolors one ARGB pixel: the HSL lightness L becomes DARKEST + (LIGHTEST - DARKEST) * (1 - L), and the
* saturation is scaled by SATURATION, keeping the hue and alpha
*/
static int darken(int argb)
{
double r = ((argb >> 16) & 0xFF) / 255.0;
double g = ((argb >> 8) & 0xFF) / 255.0;
double b = (argb & 0xFF) / 255.0;
double max = Math.max(r, Math.max(g, b));
double min = Math.min(r, Math.min(g, b));
double lightness = (max + min) / 2.0;
double chroma = max - min;
double target = DARKEST + (LIGHTEST - DARKEST) * (1.0 - lightness);
//Chroma that keeps the saturation at the new lightness: saturation = chroma / (1 - |2L - 1|)
double room = 1.0 - Math.abs(2.0 * lightness - 1.0);
double scale = chroma > 0 && room > 0 ? SATURATION * (1.0 - Math.abs(2.0 * target - 1.0)) / room : 0;
return (argb & 0xFF000000) | (channel(target + (r - lightness) * scale) << 16) |
(channel(target + (g - lightness) * scale) << 8) | channel(target + (b - lightness) * scale);
}
private static int channel(double value)
{
return (int)Math.round(Math.clamp(value, 0.0, 1.0) * 255.0);
}
}

View File

@@ -0,0 +1,39 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
/**
* Map tile address in the OpenStreetMap (slippy map) scheme
* @param zoom level, 0 for the whole world in one tile
* @param x tile column, 0 to 2^zoom - 1, west to east
* @param y tile row, 0 to 2^zoom - 1, north to south
*/
public record TileKey(int zoom, int x, int y)
{
/**
* Tile that covers this tile at a lower (farther) zoom level
* @param levels to go up, 1 or more
* @return covering tile
*/
public TileKey parent(int levels)
{
return new TileKey(zoom - levels, x >> levels, y >> levels);
}
}

View File

@@ -0,0 +1,492 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javafx.scene.image.Image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads map tile images from a {@link TileSource} in the background, with a memory cache of recently drawn tiles and
* a disk cache that follows the tile server's caching headers. Follows the OpenStreetMap tile usage policy, which
* suits the other servers too: an identifying User-Agent, two download threads, and local caching. The newest
* requests load first and requests for tiles that scrolled out of view are dropped. Changing the source drops the
* loaded and requested tiles.
*/
public class TileLoader
{
private static final Logger mLog = LoggerFactory.getLogger(TileLoader.class);
private static final String USER_AGENT = "sdrtrunk (https://github.com/DSheirer/sdrtrunk)";
private static final int DOWNLOAD_THREADS = 2;
//256 tiles of 256x256 pixels is about 64 MB
private static final int MEMORY_CACHE_TILES = 256;
private static final Duration DEFAULT_EXPIRY = Duration.ofDays(7);
private static final Duration MINIMUM_EXPIRY = Duration.ofHours(1);
private static final Duration RETRY_DELAY = Duration.ofSeconds(60);
private static final long DISK_CACHE_LIMIT_BYTES = 512L * 1024 * 1024;
private static final long DISK_CACHE_TRIM_BYTES = 400L * 1024 * 1024;
private static final Pattern MAX_AGE = Pattern.compile("max-age=(\\d+)");
private final Path mCacheDirectory;
private final Consumer<TileKey> mLoadedListener;
private final HttpClient mHttpClient;
private final Map<TileKey,Image> mMemoryCache = new LinkedHashMap<>(MEMORY_CACHE_TILES, 0.75f, true)
{
@Override
protected boolean removeEldestEntry(Map.Entry<TileKey,Image> eldest)
{
return size() > MEMORY_CACHE_TILES;
}
};
private final LinkedBlockingDeque<TileKey> mQueue = new LinkedBlockingDeque<>();
private final Set<TileKey> mPending = ConcurrentHashMap.newKeySet();
private final Map<TileKey,Long> mFailures = new ConcurrentHashMap<>();
private volatile Set<TileKey> mWanted = Collections.emptySet();
private volatile TileSource mSource;
private final AtomicBoolean mTrimmed = new AtomicBoolean();
private final List<Thread> mThreads = new ArrayList<>();
private volatile boolean mRunning = true;
/**
* Constructs an instance and starts the download threads. Nothing loads until a source is set.
* @param cacheDirectory for the disk cache, with a folder for each source, or null for no disk cache
* @param loadedListener notified on a download thread when a requested tile is ready in {@link #get(TileKey)}
*/
public TileLoader(Path cacheDirectory, Consumer<TileKey> loadedListener)
{
mCacheDirectory = cacheDirectory;
mLoadedListener = loadedListener;
mHttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL).build();
for(int index = 0; index < DOWNLOAD_THREADS; index++)
{
Thread thread = Thread.ofPlatform().daemon().name("sdrtrunk map tile loader " + index)
.unstarted(this::run);
mThreads.add(thread);
thread.start();
}
}
/**
* Sets the tiles to load, dropping the loaded and requested tiles of the previous source. Call on the thread that
* requests tiles.
* @param source of the tiles, or null to load none
*/
public void setSource(TileSource source)
{
if(Objects.equals(source, mSource))
{
return;
}
mSource = source;
mQueue.clear();
mPending.clear();
mFailures.clear();
synchronized(mMemoryCache)
{
mMemoryCache.clear();
}
}
/**
* Tile image from the memory cache
* @param key of the tile
* @return image, or null when it isn't loaded
*/
public Image get(TileKey key)
{
synchronized(mMemoryCache)
{
return mMemoryCache.get(key);
}
}
/**
* Sets the tiles that are in view. Queued requests for other tiles are dropped when they come up.
*/
public void setWanted(Set<TileKey> wanted)
{
mWanted = Set.copyOf(wanted);
}
/**
* Requests a tile, unless it's loaded, already requested, or failed recently. The newest request loads first.
*/
public void request(TileKey key)
{
TileSource source = mSource;
if(source == null || !source.isAvailable() || get(key) != null)
{
return;
}
Long failed = mFailures.get(key);
if(failed != null && System.currentTimeMillis() < failed + RETRY_DELAY.toMillis())
{
return;
}
if(mPending.add(key))
{
mQueue.addLast(key);
}
else if(mQueue.remove(key))
{
//Requested again, so move it to the front of the line
mQueue.addLast(key);
}
}
/**
* Stops the download threads
*/
public void dispose()
{
mRunning = false;
mThreads.forEach(Thread::interrupt);
}
/**
* Download thread: takes the newest request, from the disk cache when it's fresh, else from the tile server
*/
private void run()
{
trimDiskCache();
while(mRunning)
{
TileKey key;
try
{
key = mQueue.takeLast();
}
catch(InterruptedException e)
{
return;
}
TileSource source = mSource;
try
{
if(source != null && source.isAvailable() && mWanted.contains(key))
{
Image image = load(key, source);
//Drop the tile when the source changed while it loaded
if(source == mSource)
{
if(image != null)
{
mFailures.remove(key);
synchronized(mMemoryCache)
{
mMemoryCache.put(key, image);
}
mLoadedListener.accept(key);
}
else
{
mFailures.put(key, System.currentTimeMillis());
}
}
}
}
catch(Exception e)
{
mLog.error("Error loading map tile " + (source != null ? source.cacheName() : "") + " " + key, e);
mFailures.put(key, System.currentTimeMillis());
}
finally
{
mPending.remove(key);
}
}
}
/**
* Loads a tile from the disk cache while it's fresh, else downloads it, falling back to a stale cached copy when the
* download fails. Recolors the tile when the source darkens its tiles.
* @return image, or null
*/
private Image load(TileKey key, TileSource source)
{
Path file = getCacheFile(key, source);
byte[] bytes = null;
boolean fresh = false;
if(file != null && Files.isRegularFile(file))
{
try
{
//The file's modified time is when it expires
fresh = Files.getLastModifiedTime(file).toMillis() > System.currentTimeMillis();
bytes = Files.readAllBytes(file);
}
catch(IOException e)
{
bytes = null;
}
}
if(!fresh)
{
byte[] downloaded = download(key, file, source);
if(downloaded != null)
{
bytes = downloaded;
}
}
if(bytes == null)
{
return null;
}
Image image = new Image(new ByteArrayInputStream(bytes));
if(image.isError())
{
return null;
}
return source.darken() ? TileDarkener.darken(image) : image;
}
/**
* Downloads the tile and stores it in the disk cache
* @param key of the tile
* @param file of the disk cache, or null
* @param source of the tile
* @return tile image bytes, or null when the download failed
*/
private byte[] download(TileKey key, Path file, TileSource source)
{
if(!mRunning)
{
return null;
}
URI uri = URI.create(source.getUrl(key));
//The URL can hold the user's key, so the log names the source and the tile instead
String tile = source.cacheName() + " " + key;
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(20))
.header("User-Agent", USER_AGENT).GET().build();
try
{
HttpResponse<byte[]> response = mHttpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
if(response.statusCode() != 200)
{
mLog.debug("Map tile " + tile + " response " + response.statusCode());
return null;
}
byte[] bytes = response.body();
if(file != null)
{
store(file, bytes, getExpiry(response));
}
return bytes;
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch(IOException e)
{
mLog.debug("Unable to download map tile " + tile + " - " + e.getMessage());
}
return null;
}
/**
* Time the tile expires: the Cache-Control max-age, else the Expires header, else a week, and at least an hour
*/
private static long getExpiry(HttpResponse<?> response)
{
long now = System.currentTimeMillis();
Duration expiry = DEFAULT_EXPIRY;
Optional<String> cacheControl = response.headers().firstValue("Cache-Control");
Optional<String> expires = response.headers().firstValue("Expires");
if(cacheControl.isPresent())
{
Matcher matcher = MAX_AGE.matcher(cacheControl.get());
if(matcher.find())
{
expiry = Duration.ofSeconds(Long.parseLong(matcher.group(1)));
}
}
else if(expires.isPresent())
{
try
{
long time = ZonedDateTime.parse(expires.get(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()
.toEpochMilli();
expiry = Duration.ofMillis(time - now);
}
catch(Exception e)
{
//Use the default
}
}
if(expiry.compareTo(MINIMUM_EXPIRY) < 0)
{
expiry = MINIMUM_EXPIRY;
}
return now + expiry.toMillis();
}
/**
* Writes the tile to the disk cache, with its modified time set to when it expires
*/
private static void store(Path file, byte[] bytes, long expiry)
{
try
{
Files.createDirectories(file.getParent());
Path temporary = Files.createTempFile(file.getParent(), "tile", ".tmp");
Files.write(temporary, bytes);
Files.setLastModifiedTime(temporary, FileTime.fromMillis(expiry));
Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
catch(IOException e)
{
mLog.debug("Unable to cache map tile " + file + " - " + e.getMessage());
}
}
private Path getCacheFile(TileKey key, TileSource source)
{
return mCacheDirectory != null ? mCacheDirectory.resolve(source.cacheName())
.resolve(String.valueOf(key.zoom())).resolve(String.valueOf(key.x())).resolve(key.y() + ".tile") : null;
}
/**
* Deletes the tiles that expire first when the disk cache grows past its limit. Runs once per instance.
*/
private void trimDiskCache()
{
if(mCacheDirectory == null || !Files.isDirectory(mCacheDirectory) || mTrimmed.getAndSet(true))
{
return;
}
record CachedTile(Path path, long size, long expiry) {}
List<CachedTile> tiles = new ArrayList<>();
try(Stream<Path> stream = Files.walk(mCacheDirectory))
{
stream.filter(Files::isRegularFile).forEach(path -> {
try
{
tiles.add(new CachedTile(path, Files.size(path), Files.getLastModifiedTime(path).toMillis()));
}
catch(IOException e)
{
//Skip it
}
});
}
catch(IOException e)
{
mLog.debug("Unable to read the map tile cache - " + e.getMessage());
return;
}
long total = tiles.stream().mapToLong(CachedTile::size).sum();
if(total <= DISK_CACHE_LIMIT_BYTES)
{
return;
}
tiles.sort(Comparator.comparingLong(CachedTile::expiry));
int deleted = 0;
for(CachedTile tile: tiles)
{
if(total <= DISK_CACHE_TRIM_BYTES)
{
break;
}
try
{
Files.deleteIfExists(tile.path());
total -= tile.size();
deleted++;
}
catch(IOException e)
{
//Skip it
}
}
mLog.info("Trimmed the map tile cache: deleted " + deleted + " tiles");
}
}

View File

@@ -0,0 +1,546 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.geometry.VPos;
import javafx.scene.Cursor;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.input.ZoomEvent;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
/**
* JavaFX slippy map: tiles from a {@link TileSource} drawn on a canvas, with {@link MapLayer} overlays. While a tile
* loads, the matching part of a loaded tile from a farther zoom level stands in for it. Past the source's highest
* zoom level, its closest tiles are enlarged.
*
* Mouse: drag with the primary button to pan, scroll to zoom at the mouse, double-click or middle-click to center and
* zoom in. Keys: arrows pan, plus and minus zoom. Use on the JavaFX thread.
*/
public class TileMapView extends Region
{
private static final Color BACKGROUND = Color.rgb(221, 221, 221);
private static final Color DARK_BACKGROUND = Color.rgb(38, 38, 38);
private static final Color ATTRIBUTION_BACKGROUND = Color.rgb(255, 255, 255, 0.75);
private static final Color DARK_ATTRIBUTION_BACKGROUND = Color.rgb(30, 30, 30, 0.75);
private static final Color ATTRIBUTION_TEXT = Color.rgb(40, 40, 40);
private static final Color DARK_ATTRIBUTION_TEXT = Color.rgb(210, 210, 210);
private static final Font ATTRIBUTION_FONT = Font.font(11);
private static final Font MESSAGE_FONT = Font.font(14);
private static final int FALLBACK_LEVELS = 5;
//Scroll distance for one zoom step: one mouse wheel notch, or several trackpad events
private static final double SCROLL_STEP = 40.0;
private static final double PINCH_STEP = 1.4;
private static final double KEY_PAN_PIXELS = 64.0;
private final Canvas mCanvas = new Canvas();
private final MapViewport mViewport = new MapViewport();
private final TileLoader mTileLoader;
private final List<MapLayer> mLayers = new ArrayList<>();
private final List<Runnable> mViewListeners = new CopyOnWriteArrayList<>();
private final ReadOnlyIntegerWrapper mZoom = new ReadOnlyIntegerWrapper(mViewport.getZoom());
private final Text mMeasure = new Text();
private TileSource mSource;
private boolean mRedrawPending;
private double mDragX = Double.NaN;
private double mDragY = Double.NaN;
private double mScrollAccumulator;
private double mPinchAccumulator = 1.0;
/**
* Constructs an instance
* @param cacheDirectory for the map tiles on disk, or null to not keep tiles on disk
* @param loadTiles true to download tiles, or false for a blank map (tests and off-screen rendering)
*/
public TileMapView(Path cacheDirectory, boolean loadTiles)
{
mTileLoader = loadTiles ? new TileLoader(cacheDirectory, key -> Platform.runLater(this::requestRedraw)) : null;
getChildren().add(mCanvas);
setFocusTraversable(true);
setMinSize(0, 0);
setPrefSize(600, 400);
addEventHandler(MouseEvent.MOUSE_PRESSED, this::mousePressed);
addEventHandler(MouseEvent.MOUSE_DRAGGED, this::mouseDragged);
addEventHandler(MouseEvent.MOUSE_RELEASED, this::mouseReleased);
addEventHandler(MouseEvent.MOUSE_CLICKED, this::mouseClicked);
addEventHandler(ScrollEvent.SCROLL, this::scrolled);
addEventHandler(ZoomEvent.ZOOM_STARTED, event -> mPinchAccumulator = 1.0);
addEventHandler(ZoomEvent.ZOOM, this::pinched);
addEventHandler(KeyEvent.KEY_PRESSED, this::keyPressed);
}
/**
* Viewport, for converting positions to screen pixels
*/
public MapViewport getViewport()
{
return mViewport;
}
/**
* Sets the tiles to show, dropping the tiles of the previous source
* @param source of the tiles, or null to show none
*/
public void setSource(TileSource source)
{
mSource = source;
if(mTileLoader != null)
{
mTileLoader.setSource(source);
}
requestRedraw();
}
/**
* Source of the tiles, or null
*/
public TileSource getSource()
{
return mSource;
}
/**
* Tile zoom level, updated when the map zooms
*/
public ReadOnlyIntegerProperty zoomProperty()
{
return mZoom.getReadOnlyProperty();
}
public int getZoom()
{
return mViewport.getZoom();
}
/**
* Sets the tile zoom level, keeping the center point
*/
public void setZoom(int zoom)
{
if(zoom != mViewport.getZoom())
{
mViewport.setZoom(zoom);
viewChanged();
}
}
/**
* Changes the zoom level, keeping the position under the screen point in place
*/
public void zoomAt(int zoom, double x, double y)
{
if(zoom != mViewport.getZoom())
{
mViewport.zoomAt(zoom, x, y);
viewChanged();
}
}
public GeoPosition getCenter()
{
return mViewport.getCenter();
}
/**
* Centers the map on the position
*/
public void setCenter(GeoPosition position)
{
if(position != null)
{
mViewport.setCenter(position);
viewChanged();
}
}
/**
* Adds a layer over the tiles and the layers added before it
*/
public void addLayer(MapLayer layer)
{
mLayers.add(layer);
requestRedraw();
}
/**
* Adds a listener that's notified on the JavaFX thread each time the map pans or zooms
*/
public void addViewListener(Runnable listener)
{
mViewListeners.add(listener);
}
/**
* Redraws the map on the next JavaFX pulse. Can be called often: the requests are combined.
*/
public void requestRedraw()
{
if(!mRedrawPending)
{
mRedrawPending = true;
Platform.runLater(() -> {
mRedrawPending = false;
draw();
});
}
}
/**
* Stops loading tiles
*/
public void dispose()
{
if(mTileLoader != null)
{
mTileLoader.dispose();
}
}
private void viewChanged()
{
mZoom.set(mViewport.getZoom());
requestRedraw();
mViewListeners.forEach(Runnable::run);
}
@Override
protected void layoutChildren()
{
double width = snapSizeX(getWidth());
double height = snapSizeY(getHeight());
if(mCanvas.getWidth() != width || mCanvas.getHeight() != height)
{
mCanvas.setWidth(width);
mCanvas.setHeight(height);
mViewport.setSize(width, height);
draw();
}
}
/**
* Draws the tiles and the layers now
*/
public void draw()
{
GraphicsContext gc = mCanvas.getGraphicsContext2D();
double width = mCanvas.getWidth();
double height = mCanvas.getHeight();
boolean dark = mSource != null && mSource.dark();
gc.setFill(dark ? DARK_BACKGROUND : BACKGROUND);
gc.fillRect(0, 0, width, height);
if(width <= 0 || height <= 0)
{
return;
}
if(mSource != null && mSource.isAvailable())
{
drawTiles(gc, width, height);
}
else if(mSource != null && mSource.unavailableReason() != null)
{
gc.setFill(dark ? DARK_ATTRIBUTION_TEXT : ATTRIBUTION_TEXT);
gc.setFont(MESSAGE_FONT);
gc.setTextAlign(TextAlignment.CENTER);
gc.setTextBaseline(VPos.CENTER);
gc.fillText(mSource.unavailableReason(), width / 2.0, height / 2.0);
}
for(MapLayer layer: mLayers)
{
gc.save();
layer.draw(gc, this);
gc.restore();
}
if(mSource != null)
{
drawAttribution(gc, mSource.attribution(), dark, width, height);
}
}
private void drawTiles(GraphicsContext gc, double width, double height)
{
int zoom = mViewport.getZoom();
int count = Mercator.tileCount(zoom);
double left = mViewport.getLeft();
double top = mViewport.getTop();
int firstColumn = (int)Math.floor(left / Mercator.TILE_SIZE);
int lastColumn = (int)Math.floor((left + width - 1) / Mercator.TILE_SIZE);
int firstRow = Math.max(0, (int)Math.floor(top / Mercator.TILE_SIZE));
int lastRow = Math.min(count - 1, (int)Math.floor((top + height - 1) / Mercator.TILE_SIZE));
//Past the source's highest zoom level, its closest tiles are enlarged
int enlarged = Math.max(0, zoom - mSource.maxZoom());
Set<TileKey> wanted = new HashSet<>();
List<TileKey> missing = new ArrayList<>();
for(int row = firstRow; row <= lastRow; row++)
{
for(int column = firstColumn; column <= lastColumn; column++)
{
TileKey key = new TileKey(zoom, Math.floorMod(column, count), row);
TileKey source = enlarged > 0 ? key.parent(enlarged) : key;
double x = column * (double)Mercator.TILE_SIZE - left;
double y = row * (double)Mercator.TILE_SIZE - top;
wanted.add(source);
Image image = mTileLoader != null ? mTileLoader.get(source) : null;
if(image != null)
{
drawPart(gc, image, key, enlarged, x, y);
}
else
{
drawFallback(gc, key, enlarged, x, y);
if(!missing.contains(source))
{
missing.add(source);
}
}
}
}
if(mTileLoader != null)
{
mTileLoader.setWanted(wanted);
//Request the tiles nearest the middle last, so they load first
double scale = 1 << enlarged;
int sourceCount = Mercator.tileCount(zoom - enlarged);
double middleColumn = ((left + width / 2.0) / Mercator.TILE_SIZE) / scale - 0.5;
double middleRow = ((top + height / 2.0) / Mercator.TILE_SIZE) / scale - 0.5;
missing.sort((a, b) -> Double.compare(distance(b, middleColumn, middleRow, sourceCount),
distance(a, middleColumn, middleRow, sourceCount)));
missing.forEach(mTileLoader::request);
}
}
/**
* Distance in tiles from the middle of the view, allowing for the world repeating east and west
*/
private static double distance(TileKey key, double column, double row, int count)
{
double dx = Math.abs(key.x() - Math.floorMod((long)Math.floor(column), count));
dx = Math.min(dx, count - dx);
return Math.hypot(dx, key.y() - row);
}
/**
* Draws the part of a tile from a farther zoom level that covers the tile, enlarged to the tile's size
* @param image of the tile from the farther zoom level
* @param key of the tile to cover
* @param levels between the tiles' zoom levels, 0 to draw the whole image
*/
private static void drawPart(GraphicsContext gc, Image image, TileKey key, int levels, double x, double y)
{
if(levels == 0)
{
gc.drawImage(image, x, y, Mercator.TILE_SIZE, Mercator.TILE_SIZE);
return;
}
TileKey parent = key.parent(levels);
double size = image.getWidth() / (1 << levels);
double sourceX = (key.x() - ((long)parent.x() << levels)) * size;
double sourceY = (key.y() - ((long)parent.y() << levels)) * size;
gc.drawImage(image, sourceX, sourceY, size, size, x, y, Mercator.TILE_SIZE, Mercator.TILE_SIZE);
}
/**
* Draws the part of a loaded tile from a farther zoom level than the requested tile that covers the tile
* @param enlarged levels between the tile and the requested tile
*/
private void drawFallback(GraphicsContext gc, TileKey key, int enlarged, double x, double y)
{
if(mTileLoader == null)
{
return;
}
for(int levels = enlarged + 1; levels <= enlarged + FALLBACK_LEVELS && key.zoom() - levels >= 0; levels++)
{
Image image = mTileLoader.get(key.parent(levels));
if(image != null)
{
drawPart(gc, image, key, levels, x, y);
return;
}
}
}
/**
* Attribution in the bottom right corner, required by the tile servers
*/
private void drawAttribution(GraphicsContext gc, String attribution, boolean dark, double width, double height)
{
mMeasure.setText(attribution);
mMeasure.setFont(ATTRIBUTION_FONT);
double boxWidth = mMeasure.getLayoutBounds().getWidth() + 8;
double boxHeight = 16;
gc.setFill(dark ? DARK_ATTRIBUTION_BACKGROUND : ATTRIBUTION_BACKGROUND);
gc.fillRect(width - boxWidth, height - boxHeight, boxWidth, boxHeight);
gc.setFill(dark ? DARK_ATTRIBUTION_TEXT : ATTRIBUTION_TEXT);
gc.setFont(ATTRIBUTION_FONT);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.CENTER);
gc.fillText(attribution, width - boxWidth + 4, height - boxHeight / 2.0);
}
private void mousePressed(MouseEvent event)
{
requestFocus();
if(event.getButton() == MouseButton.PRIMARY)
{
mDragX = event.getX();
mDragY = event.getY();
}
}
private void mouseDragged(MouseEvent event)
{
if(event.isPrimaryButtonDown() && !Double.isNaN(mDragX))
{
mViewport.pan(mDragX - event.getX(), mDragY - event.getY());
mDragX = event.getX();
mDragY = event.getY();
setCursor(Cursor.MOVE);
viewChanged();
}
}
private void mouseReleased(MouseEvent event)
{
if(event.getButton() == MouseButton.PRIMARY)
{
mDragX = Double.NaN;
mDragY = Double.NaN;
setCursor(Cursor.DEFAULT);
}
}
private void mouseClicked(MouseEvent event)
{
boolean doubleClick = event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2 &&
event.isStillSincePress();
if(doubleClick || event.getButton() == MouseButton.MIDDLE)
{
mViewport.setCenter(mViewport.getPosition(event.getX(), event.getY()));
mViewport.setZoom(mViewport.getZoom() + 1);
viewChanged();
}
}
private void scrolled(ScrollEvent event)
{
if(event.getDeltaY() == 0)
{
return;
}
//Restart when the direction changes
if(Math.signum(event.getDeltaY()) != Math.signum(mScrollAccumulator))
{
mScrollAccumulator = 0;
}
mScrollAccumulator += event.getDeltaY();
int steps = (int)(mScrollAccumulator / SCROLL_STEP);
if(steps != 0)
{
mScrollAccumulator -= steps * SCROLL_STEP;
zoomAt(mViewport.getZoom() + steps, event.getX(), event.getY());
}
event.consume();
}
private void pinched(ZoomEvent event)
{
mPinchAccumulator *= event.getZoomFactor();
if(mPinchAccumulator >= PINCH_STEP)
{
mPinchAccumulator = 1.0;
zoomAt(mViewport.getZoom() + 1, event.getX(), event.getY());
}
else if(mPinchAccumulator <= 1.0 / PINCH_STEP)
{
mPinchAccumulator = 1.0;
zoomAt(mViewport.getZoom() - 1, event.getX(), event.getY());
}
event.consume();
}
private void keyPressed(KeyEvent event)
{
switch(event.getCode())
{
case LEFT, KP_LEFT -> pan(-KEY_PAN_PIXELS, 0);
case RIGHT, KP_RIGHT -> pan(KEY_PAN_PIXELS, 0);
case UP, KP_UP -> pan(0, -KEY_PAN_PIXELS);
case DOWN, KP_DOWN -> pan(0, KEY_PAN_PIXELS);
case PLUS, EQUALS, ADD -> setZoom(getZoom() + 1);
case MINUS, SUBTRACT -> setZoom(getZoom() - 1);
default -> {
return;
}
}
event.consume();
}
private void pan(double dx, double dy)
{
mViewport.pan(dx, dy);
viewChanged();
}
}

View File

@@ -0,0 +1,129 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* Free map tile server. A server with a dark style follows the theme; a server without one has its light tiles
* recolored in dark themes.
* @param id stored in the map preference. Don't change it.
* @param name shown to the user
* @param lightUrl template of the light style tiles, see {@link TileSource#urlTemplate()}, with a {key} placeholder
* when the server needs a key
* @param darkUrl template of the dark style tiles, or null when the server has no dark style
* @param subdomains for the {s} placeholder, or empty
* @param maxZoom highest zoom level the server provides
* @param attribution required by the server
* @param keyUrl web page where the user gets a free key, or null when the server doesn't need a key
*/
public record TileServer(String id, String name, String lightUrl, String darkUrl, List<String> subdomains,
int maxZoom, String attribution, String keyUrl)
{
private static final String OSM = "© OpenStreetMap contributors";
public static final TileServer OPEN_STREET_MAP = new TileServer("osm", "OpenStreetMap",
"https://tile.openstreetmap.org/{z}/{x}/{y}.png", null, List.of(), 19, OSM, null);
/**
* Positron (light) and Dark Matter (dark). Needs a free key since 25 September 2026: 5 million tiles per month
* for non-commercial use.
*/
public static final TileServer CARTO = new TileServer("carto", "CARTO",
"https://basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}.png?key={key}",
"https://basemaps.cartocdn.com/rastertiles/dark_all/{z}/{x}/{y}.png?key={key}", List.of(), 18,
OSM + ", © CARTO", "https://carto.com/basemaps/apikey/");
public static final TileServer ESRI_GRAY = new TileServer("esri.gray", "Esri Gray Canvas",
"https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}",
"https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}",
List.of(), 16, "Tiles © Esri — Esri, HERE, Garmin, " + OSM, null);
public static final TileServer OPEN_TOPO_MAP = new TileServer("opentopomap", "OpenTopoMap",
"https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png", null, List.of("a", "b", "c"), 17,
"Map data: " + OSM + ", SRTM | Map style: © OpenTopoMap (CC-BY-SA)", null);
/**
* Servers offered to the user, in menu order
*/
public static final List<TileServer> SERVERS = List.of(OPEN_STREET_MAP, CARTO, ESRI_GRAY, OPEN_TOPO_MAP);
/**
* Server with the id
* @param id from the map preference, or null
* @return server, or OpenStreetMap when there's no server with the id
*/
public static TileServer get(String id)
{
return SERVERS.stream().filter(server -> server.id().equals(id)).findFirst().orElse(OPEN_STREET_MAP);
}
/**
* Indicates if the server needs a key from the user
*/
public boolean requiresKey()
{
return keyUrl != null;
}
/**
* Indicates if the server has its own dark style
*/
public boolean hasDarkStyle()
{
return darkUrl != null;
}
/**
* Tiles to load for the theme
* @param dark true for a dark theme
* @param key from the user, for a server that needs one, or null
*/
public TileSource getSource(boolean dark, String key)
{
boolean darkStyle = dark && hasDarkStyle();
String template = darkStyle ? darkUrl : lightUrl;
String cacheName = id + (darkStyle ? "/dark" : "/light");
String unavailable = null;
if(requiresKey())
{
if(key == null || key.isBlank())
{
unavailable = name + " needs a free API key: enter it in the map's Settings tab";
}
else
{
template = template.replace("{key}", URLEncoder.encode(key.strip(), StandardCharsets.UTF_8));
}
}
return new TileSource(cacheName, template, subdomains, maxZoom, dark && !hasDarkStyle(), dark, attribution,
unavailable);
}
@Override
public String toString()
{
return name;
}
}

View File

@@ -0,0 +1,57 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import java.util.List;
/**
* Tiles the map loads: one style of a {@link TileServer}, resolved for the theme and the user's key.
* @param cacheName folder of the tiles in the disk cache, e.g. osm/light
* @param urlTemplate with {s} subdomain, {z} zoom, {x} column and {y} row placeholders, or null when unavailable
* @param subdomains for the {s} placeholder, or empty
* @param maxZoom highest zoom level the server provides. Closer zoom levels enlarge these tiles.
* @param darken true to recolor the tiles for a dark theme, for a server without a dark style
* @param dark true when the tiles are dark, from a dark style or recolored
* @param attribution shown on the map, as the server requires
* @param unavailableReason shown instead of tiles when the source can't load tiles, or null
*/
public record TileSource(String cacheName, String urlTemplate, List<String> subdomains, int maxZoom, boolean darken,
boolean dark, String attribution, String unavailableReason)
{
/**
* Indicates if the source can load tiles
*/
public boolean isAvailable()
{
return urlTemplate != null && unavailableReason == null;
}
/**
* URL of the tile. Spreads the tiles over the subdomains by position, so each tile always comes from the same
* subdomain and stays in the server's and the browser-style caches.
*/
public String getUrl(TileKey key)
{
String subdomain = subdomains.isEmpty() ? "" :
subdomains.get(Math.floorMod(key.x() + key.y(), subdomains.size()));
return urlTemplate.replace("{s}", subdomain).replace("{z}", String.valueOf(key.zoom()))
.replace("{x}", String.valueOf(key.x())).replace("{y}", String.valueOf(key.y()));
}
}

View File

@@ -0,0 +1,228 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.alias.Alias;
import io.github.dsheirer.icon.Icon;
import io.github.dsheirer.icon.IconModel;
import io.github.dsheirer.map.PlottableEntityHistory;
import io.github.dsheirer.map.PlottableEntityModel;
import io.github.dsheirer.map.TimestampedGeoPosition;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javafx.geometry.VPos;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
/**
* Plotted tracks: for each entity, a two-tone trail through its most recent positions, its alias icon at the latest
* position and its alias name (or identifier) beside the icon, in the alias color. Use on the JavaFX thread.
*/
public class TrackLayer implements MapLayer
{
private static final Color DEFAULT_COLOR = Color.BLUE;
private static final Color TRAIL_BACKGROUND = Color.BLACK;
private static final Color LABEL_HALO = Color.rgb(255, 255, 255, 0.85);
private static final Font LABEL_FONT = Font.font(12);
//Map edge allowance for icons and labels that are partly in view
private static final double MARGIN = 200;
private final PlottableEntityModel mEntityModel;
private final IconModel mIconModel;
private final Set<PlottableEntityHistory> mEntities = new LinkedHashSet<>();
private int mTrackHistoryLength = 3;
/**
* Constructs an instance
* @param entityModel for the entities' aliases
* @param iconModel for the alias icons
*/
public TrackLayer(PlottableEntityModel entityModel, IconModel iconModel)
{
mEntityModel = entityModel;
mIconModel = iconModel;
}
/**
* Number of positions in each trail, including the latest position
*/
public int getTrackHistoryLength()
{
return mTrackHistoryLength;
}
public void setTrackHistoryLength(int length)
{
mTrackHistoryLength = length;
}
/**
* Shows the entity
* @return true if it wasn't shown
*/
public boolean add(PlottableEntityHistory entity)
{
return entity != null && mEntities.add(entity);
}
/**
* Shows the entities
* @return true if any wasn't shown
*/
public boolean addAll(Collection<PlottableEntityHistory> entities)
{
boolean added = false;
for(PlottableEntityHistory entity: entities)
{
added |= add(entity);
}
return added;
}
/**
* Stops showing the entities
*/
public void removeAll(Collection<PlottableEntityHistory> entities)
{
mEntities.removeAll(entities);
}
/**
* Stops showing all entities. They're shown again when they report a new position.
*/
public void clear()
{
mEntities.clear();
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
MapViewport viewport = map.getViewport();
gc.setLineCap(StrokeLineCap.ROUND);
gc.setLineJoin(StrokeLineJoin.ROUND);
gc.setFont(LABEL_FONT);
gc.setTextAlign(TextAlignment.LEFT);
gc.setTextBaseline(VPos.CENTER);
for(PlottableEntityHistory entity: mEntities)
{
List<TimestampedGeoPosition> history = entity.getTrackHistoryModel().getTrackHistory();
if(history.isEmpty() || !history.getFirst().isValid())
{
continue;
}
List<Alias> aliases = mEntityModel.getAliases(entity);
Alias alias = aliases.isEmpty() ? null : aliases.getFirst();
Color color = alias != null ? toColor(alias.getColor()) : DEFAULT_COLOR;
drawTrail(gc, viewport, history, color);
TimestampedGeoPosition latest = history.getFirst();
double x = viewport.getScreenX(latest.getLongitude());
double y = viewport.getScreenY(latest.getLatitude());
if(x < -MARGIN || x > viewport.getWidth() + MARGIN || y < -MARGIN || y > viewport.getHeight() + MARGIN)
{
continue;
}
double iconWidth = drawIcon(gc, alias, x, y);
String label = alias != null ? alias.getName() : String.valueOf(entity.getIdentifier());
double labelX = x + iconWidth / 2.0 + 3;
gc.setStroke(LABEL_HALO);
gc.setLineWidth(3);
gc.strokeText(label, labelX, y);
gc.setFill(color);
gc.fillText(label, labelX, y);
}
}
/**
* Trail through the most recent positions: a wide black line under a narrow line in the entity's color
*/
private void drawTrail(GraphicsContext gc, MapViewport viewport, List<TimestampedGeoPosition> history,
Color color)
{
int length = Math.min(history.size(), mTrackHistoryLength);
if(length < 2)
{
return;
}
double[] xs = new double[length];
double[] ys = new double[length];
double reference = viewport.getScreenX(history.getFirst().getLongitude());
double worldSize = viewport.getWorldSize();
for(int index = 0; index < length; index++)
{
TimestampedGeoPosition position = history.get(index);
double x = viewport.getScreenX(position.getLongitude());
//Keep the trail on the same copy of the world as the latest position
xs[index] = x - Math.round((x - reference) / worldSize) * worldSize;
ys[index] = viewport.getScreenY(position.getLatitude());
}
gc.setStroke(TRAIL_BACKGROUND);
gc.setLineWidth(3);
gc.strokePolyline(xs, ys, length);
gc.setStroke(color);
gc.setLineWidth(1);
gc.strokePolyline(xs, ys, length);
}
/**
* Draws the alias icon, or the default icon, centered on the point
* @return drawn icon width
*/
private double drawIcon(GraphicsContext gc, Alias alias, double x, double y)
{
Icon icon = mIconModel.getIcon(alias != null ? alias.getIconName() : null);
Image image = icon != null ? icon.getFxImage() : null;
if(image == null || image.getHeight() <= 0)
{
return 0;
}
double height = IconModel.DEFAULT_ICON_SIZE;
double width = image.getWidth() * height / image.getHeight();
gc.drawImage(image, x - width / 2.0, y - height / 2.0, width, height);
return width;
}
private static Color toColor(int rgb)
{
return Color.rgb((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
}
}

View File

@@ -0,0 +1,90 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.gui.map;
import io.github.dsheirer.map.GeoPosition;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeLineCap;
/**
* Push-pin at the user's location, with the tip of the pin at the location. Use on the JavaFX thread.
*/
public class UserLocationLayer implements MapLayer
{
private static final Color NEEDLE = Color.rgb(90, 90, 90);
private static final Color HEAD = Color.rgb(220, 40, 40);
private static final Color HEAD_OUTLINE = Color.rgb(110, 0, 0);
private static final Color HIGHLIGHT = Color.rgb(255, 255, 255, 170 / 255.0);
private static final Color SHADOW = Color.rgb(0, 0, 0, 70 / 255.0);
private static final double NEEDLE_LENGTH = 14.0;
private static final double HEAD_RADIUS = 7.0;
private GeoPosition mPosition;
/**
* Sets the location to mark
* @param position of the user, or null to remove the pin
*/
public void setPosition(GeoPosition position)
{
mPosition = position;
}
/**
* Location that is marked, or null
*/
public GeoPosition getPosition()
{
return mPosition;
}
@Override
public void draw(GraphicsContext gc, TileMapView map)
{
if(mPosition == null)
{
return;
}
MapViewport viewport = map.getViewport();
double x = viewport.getScreenX(mPosition.getLongitude());
double y = viewport.getScreenY(mPosition.getLatitude());
double headY = y - NEEDLE_LENGTH - HEAD_RADIUS;
//Shadow where the needle enters the map, so the tip reads as the location
gc.setFill(SHADOW);
gc.fillOval(x - 4, y - 2, 8, 4);
gc.setStroke(NEEDLE);
gc.setLineWidth(2.0);
gc.setLineCap(StrokeLineCap.ROUND);
gc.strokeLine(x, y, x, headY);
gc.setFill(HEAD);
gc.fillOval(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
gc.setStroke(HEAD_OUTLINE);
gc.setLineWidth(1.0);
gc.strokeOval(x - HEAD_RADIUS, headY - HEAD_RADIUS, HEAD_RADIUS * 2, HEAD_RADIUS * 2);
gc.setFill(HIGHLIGHT);
gc.fillOval(x - HEAD_RADIUS / 2 - 1, headY - HEAD_RADIUS / 2 - 1, 4, 4);
}
}