Dynamically updating markers in swing JXMapKit

1.9k views Asked by At

I'm looking for a way to programmatically add waypoints to a map that is displayed using JXMapKit (which runs on the Java Swing toolkit). I'd like to supply a list of geo coordinates in a list.

1

There are 1 answers

0
Nándor Krácser On

You have to provide the Waypoints through a WaypointPainter and pass this painter to the JXMapViewer. By default the WaypointPainter accepts a Set<Waypoint>, so we can just extend WaypointPainer with our own class that accepts a List instead.

import org.jdesktop.swingx.JXMapKit;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.mapviewer.DefaultWaypoint;
import org.jdesktop.swingx.mapviewer.Waypoint;
import org.jdesktop.swingx.mapviewer.WaypointPainter;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

class CustomPainter extends WaypointPainter<JXMapViewer> {
    public void setWaypoints(List<? extends Waypoint> waypoints) {
        super.setWaypoints(new HashSet<Waypoint>(waypoints));
    }
}

public class Waypoints {
    public static void main(String[] args) {
        List<DefaultWaypoint> waypoints = new ArrayList<DefaultWaypoint>();
        waypoints.add(new DefaultWaypoint(51.5, 0));

        JXMapKit jxMapKit = new JXMapKit();
        jxMapKit.setDefaultProvider(JXMapKit.DefaultProviders.OpenStreetMaps);
        CustomPainter painter = new CustomPainter();
        painter.setWaypoints(waypoints);
        jxMapKit.getMainMap().setOverlayPainter(painter);

        final JFrame frame = new JFrame();
        frame.add(jxMapKit);
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }
}