本文介绍了在JMapViewer中绘制折线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JMapViewer在Java中使用OpenStreetMap。
我可以使用JMapViewer绘制多边形和矩形,但是如何绘制折线?

I'm working with OpenStreetMap in Java with JMapViewer.I can draw polygon and rectangle using JMapViewer, but how to draw polyline?

谢谢。

推荐答案

您可以创建自己的折线实现。以下是基于现有 MapPolygonImpl 的示例。这很hacky,但似乎没有方法在 JMapViewer 中添加行。

You could create your own implementation of a polyline. Below is an example that is based on existing MapPolygonImpl. It is hacky, but there seem to be no method in JMapViewer to add lines.

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();
            }
        });
    }
}

这篇关于在JMapViewer中绘制折线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:07