create a polyline in gluon mapLayer

拥有回忆 提交于 2019-12-01 11:03:01

While there's no explicit API for drawing lines, polylines or polygons on top of a MapView, the MapLayer is a layer where you can draw any JavaFX Shape, providing you take care of scaling it to the map coordinates.

For that, if you have a look at the PoiLayer class, you can see that for any MapPoint (defined by latitude and longitude) you can get a 2D point (defined by x and y), and you can draw a node at that position:

MapPoint point = new MapPoint(37.396256,-121.953847);
Node icon = new Circle(5, Color.BLUE);
Point2D mapPoint = baseMap.getMapPoint(point.getLatitude(), point.getLongitude());
icon.setTranslateX(mapPoint.getX());
icon.setTranslateY(mapPoint.getY());

So if you want to create, for instance, a Polygon based on a set of points, you have to add a Polygon object to the layer:

public class PoiLayer extends MapLayer {

    private final Polygon polygon;

    public PoiLayer() {
        polygon = new Polygon();
        polygon.setStroke(Color.RED);
        polygon.setFill(Color.rgb(255, 0, 0, 0.5));
        this.getChildren().add(polygon);
    }

    @Override
    protected void layoutLayer() {
        polygon.getPoints().clear();
        for (Pair<MapPoint, Node> candidate : points) {
            MapPoint point = candidate.getKey();
            Node icon = candidate.getValue();
            Point2D mapPoint = baseMap.getMapPoint(point.getLatitude(), point.getLongitude());
            icon.setTranslateX(mapPoint.getX());
            icon.setTranslateY(mapPoint.getY());

            polygon.getPoints().addAll(mapPoint.getX(), mapPoint.getY());
        }
    }
}

Now, on the demo class, create a set of mapPoints, and add them to the map:

private final List<MapPoint> polPoints = Arrays.asList(
        new MapPoint(37.887242, -122.178799), new MapPoint(37.738729, -121.921567),
        new MapPoint(37.441704, -121.921567), new MapPoint(37.293191, -122.178799),
        new MapPoint(37.441704, -122.436031), new MapPoint(37.738729, -122.436031));

private MapLayer myDemoLayer () {
    PoiLayer poi = new PoiLayer();
    for (MapPoint mapPoint : polPoints) {
        poi.addPoint(mapPoint, new Circle(5, Color.BLUE));
    }
    return poi;
}

And you will have a map with your geo-located polygon on top of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!