javafxjavafx-8gluongluon-desktop

create a polyline in gluon mapLayer


Google maps API makes it possible to create a layer on the map containing a polyline linking points together.

I have searched where I could to find an example or an implementation for this for gluon's mapLayer.

Please advice


Solution

  • 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.

    poi