Dynamically updating markers in JMapViewer

3k views Asked by At

Hello Stack Overflow community,

I am a Java newbie and I am doing a simple java project where I take coordinates (lat and lon) from a (dynamic) source and use JMapViewer (Yes, not JXMapViewer) to display the markers on a map. I have put all the coordinates in two ArrayList(s). It looks like that:

for(int i = 0; i < latArrayList.size(); i++){
    map.addMapMarker(new MapMarkerDot((double)latArrayList.get(i), (double)longArrayList.get(i)));
}

EDIT: map is a jMapViewer object.

And it works pretty fine. The problem is I need this map to refresh every 20 seconds using a Timer and the only way I found was to close and open the map, like this:

    theMap.setVisible(false);
    theMap  = new Map();
    theMap.setVisible(true); 

EDIT: theMap is an object (jFrame not jMapViewer) I create in the main function (like in the demo) and I can't use addMapMarker on it (like theMap.addMapMarker(150.2,150.2))

and well, as you can imagine this is pretty annoying (every 20 seconds the window closes and opens and the previous 'browsing' session is lost). So is there a way to refresh it? By adding markers dynamically or just refreshing the content?

Thanks a lot.

2

There are 2 answers

3
assylias On BEST ANSWER

I have never used that API but it looks like theMap.removeAllMapMarkers(); would do the trick. You can then start adding new markers again.

Regarding your loop, if you declared your Lists with generics you would not need to cast to double:

List<Double> latArrayList = new ArrayList<Double> ();
latArrayList.add(125.87); //or whatever

for(int i = 0; i < latArrayList.size(); i++){
    theMap.addMapMarker(new MapMarkerDot(latArrayList.get(i), longArrayList.get(i)));
}
0
trashgod On

I see two approaches:

  • Maintain a collection of existing MapMarker instances and use removeMapMarker() followed by addMapMarker() using the immutable MapMarkerDot implementation provided. Both methods invoke repaint().

  • Implement the MapMarker interface to create a MutableMapMarkerDot; add as many instances as required; update the coordinates in situ and invoke repaint() in your javax.swing.Timer listener.