Search code examples
javacoordinatesmouselistenermouseclick-eventjmapviewer

Using the mouseClicked method in the JMapViewer does not update the getPosition return value


I have create a MouseInputAdapter listener to get coordinates in a JMapViewer map and create the MapMarker on that spot but even though I click on a different possition the value of the map.getPossition() method does not updates with the new values.

My listener code:

@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1){
    Coordinate markeradd = map.getPosition();
    System.out.println(map.getPosition());
    map.addMapMarker(new MapMarkerDot(markeradd));
}

The system.out.print is there to print the value returned by the getPosition(). When I click for the first time, I get a set of coordinates then wherever I click, I always get the same coordinates. example of five different position clicks:

Coordinate[56.159963018590744, 10.199775695800781]
Coordinate[56.159963018590744, 10.199775695800781]
Coordinate[56.159963018590744, 10.199775695800781]
Coordinate[56.159963018590744, 10.199775695800781]
Coordinate[56.159963018590744, 10.199775695800781]

Solution

  • As you have observed, getPosition() "Calculates the latitude/longitude coordinate of the center of the currently displayed map area." You probably want

    Coordinate getPosition(java.awt.Point mapPoint)
    

    which "Converts the relative pixel coordinate … into a latitude / longitude coordinate." You can call it in your implementation of JMapController, as shown here for a subclass of DefaultMapController.

    new DefaultMapController(map) {
    
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println(map.getPosition(e.getPoint()));
        }
    };