Graphics2D to paint a line on a map
I'm trying to paint a path on a map using coordinates. I'm trying to use GeneralPath but it doesn't create a line just bunch of dots where lat/long coordinates are. How do I connect them or is there something else that I can use? Not really familiar with 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开发者_JS百科 : 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();
}
I believe you need only a single moveTo(...) method to start the drawing of the line. Then you do multiple lineTo(...) method to draw the actual line.
Here is an example I found on the web a long time ago:
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();
}
}
精彩评论