2013-11-27 128 views
2

我正在用JMapViewer在Java中使用OpenStreetMap。 我可以使用JMapViewer繪製多邊形和矩形,但如何繪製多段線?在JMapViewer中繪製折線

謝謝。

+1

您可能能夠使用所示[這裏]的方法(http://stackoverflow.com/q/10744798/230513)。 – trashgod

回答

3

您可以創建自己的折線實現。以下是一個基於現有的MapPolygonImpl的示例。這是hacky,但似乎沒有辦法在JMapViewer添加行。

enter image description here

import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.geom.Path2D; 
import java.util.ArrayList; 
import java.util.List; 

import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 
import org.openstreetmap.gui.jmapviewer.Coordinate; 
import org.openstreetmap.gui.jmapviewer.JMapViewer; 
import org.openstreetmap.gui.jmapviewer.MapPolygonImpl; 
import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate; 

public class TestMap { 

    public static class MapPolyLine extends MapPolygonImpl { 
     public MapPolyLine(List<? extends ICoordinate> points) { 
      super(null, null, points); 
     } 

     @Override 
     public void paint(Graphics g, List<Point> points) { 
      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.setColor(getColor()); 
      g2d.setStroke(getStroke()); 
      Path2D path = buildPath(points); 
      g2d.draw(path); 
      g2d.dispose(); 
     } 

     private Path2D buildPath(List<Point> points) { 
      Path2D path = new Path2D.Double(); 
      if (points != null && points.size() > 0) { 
       Point firstPoint = points.get(0); 
       path.moveTo(firstPoint.getX(), firstPoint.getY()); 
       for (Point p : points) { 
        path.lineTo(p.getX(), p.getY());  
       } 
      } 
      return path; 
     } 
    } 

    private static void createAndShowUI() { 
     JFrame frame = new JFrame("Demo"); 
     JMapViewer viewer = new JMapViewer(); 

     List<Coordinate> coordinates = new ArrayList<Coordinate>(); 
     coordinates.add(new Coordinate(50, 10)); 
     coordinates.add(new Coordinate(52, 15)); 
     coordinates.add(new Coordinate(55, 15)); 

     MapPolyLine polyLine = new MapPolyLine(coordinates); 
     viewer.addMapPolygon(polyLine); 

     frame.add(viewer); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationByPlatform(true); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowUI(); 
      } 
     }); 
    } 
} 
1

AFAIK JMapViewer擴展了JPanel。

因此,您只需重寫paintComponent並使用給定的Graphics對象。

class MyMap extends JMapViewer { 
    @Override 
    protected void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     g.setColor(Color.RED); 
     g.drawPolyline(...); 
    } 
}