我正在尝试使用坐标在地图上绘制路径。我正在尝试使用GeneralPath,但它不会创建一条直线,其中是lat / long坐标。我如何连接它们还是有其他我可以使用的东西?不太熟悉Graphics2D ..
region.add(new GeoPosition(47.2971, -122.3822));
region.add(new GeoPosition(47.2975, -122.3701));
region.add(new GeoPosition(47.3006, -122.3535));
region.add(new GeoPosition(47.2899, -122.3356));
region.add(new GeoPosition(47.2895, -122.3111));
region.add(new GeoPosition(47.2903, -122.2989));
region.add(new GeoPosition(47.2929, -122.2921));
region.add(new GeoPosition(47.2914, -122.2920));
region.add(new GeoPosition(47.2934, -122.2883));
Painter<JXMapViewer> overlay = new Painter<JXMapViewer>() {
public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
g = (Graphics2D) g.create();
//convert from viewport to world bitmap
Rectangle rect = map.getViewportBounds();
g.translate(-rect.x, -rect.y);
GeneralPath path = new GeneralPath();
//Polygon poly = new Polygon();
for(GeoPosition gp : region) {
//convert geo to world bitmap pixel
mapViewer.setZoom(60);
Point2D pt = map.getTileFactory().geoToPixel(gp, map.getZoom());
//poly.addPoint((int)pt.getX(),(int)pt.getY());
path.moveTo((int)pt.getX(),(int)pt.getY());
path.lineTo((int)pt.getX(),(int)pt.getY());
}
//do the drawing
g.setColor(new Color(255,0,0,100));
g.fill(path);
g.setColor(Color.RED);
g.draw(path);
g.dispose();
}
答案 0 :(得分:1)
我相信你只需要一个moveTo(...)方法来开始绘制线条。然后你做多个lineTo(...)方法来绘制实际的行。
以下是我很久以前在网上找到的一个例子:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class GraphicPane extends JFrame
{
public GraphicPane()
{
super("polygon");
this.setSize(600,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPolygon mypolygon = new MyPolygon();
getContentPane().add(mypolygon);
this.setVisible(true);
try
{
Thread.sleep(2000);
}
catch (InterruptedException e){}
mypolygon.move();
}
class MyPolygon extends JPanel
{
Point[] p;
GeneralPath shape;
public MyPolygon()
{
p=new Point[4];
p[0]=new Point(10,10);
p[1]=new Point(100,10);
p[2]=new Point(170,170);
p[3]=new Point(80,180);
shape =new GeneralPath();
}
public void move()
{
int x=300;
int y=200;
p[0].setLocation(x, y);
shape = new GeneralPath();
repaint();
}
public void paintComponent(Graphics grap)
{
super.paintComponent(grap);
Graphics2D grap2D=(Graphics2D)grap;
shape.moveTo((float)p[0].getX(),(float)p[0].getY());
for(int i=1;i<p.length;i++)
{
shape.lineTo((float)p[i].getX(),(float)p[i].getY());
}
shape.closePath();
grap2D.setColor(Color.red);
grap2D.draw(shape);
grap2D.setColor(Color.blue);
grap2D.fill(shape);
}
}
public static void main(String[] args)
{
GraphicPane graph = new GraphicPane();
}
}