JavaFX with Geotools Tutorial - Part 1: Load shape file
Prerequisites
- JDK 8u40 or greater (includes JavaFX 8)
- A favorite text editor or IDE
- Maven
- Geotools
- FXGraphics2D
- Shape files from DIVA-GIS, STATSilk etc.
Build with Maven
First you set up a basic build script.
Create the project structure
- Create directory structure following maven standard
- Download global country boundaries shape files and put to resource directory
- Create 2 classes for
Main.java
andMapCanvas.java
Configure pom.xml
- Define the version number of libraries as you wish.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<geotools.version>15-SNAPSHOT</geotools.version>
<fxgraphics2d.version>1.3</fxgraphics2d.version>
</properties>
- Geotools
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
</dependency>
- FXGraphics2D
<dependency>
<groupId>org.jfree</groupId>
<artifactId>fxgraphics2d</artifactId>
<version>${fxgraphics2d.version}</version>
</dependency>
Implementation
Now that you’ve done with setting up the project, next you can create map canvas.
Create map canvas
- Initial java fx canvas and
GraphicsContext
. TheGraphicsContext
will be used to draw map content on the canvas
private Canvas canvas;
private MapContent map;
private GraphicsContext gc;
public MapCanvas(int width, int height) {
canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
initMap();
drawMap(gc);
}
public Node getCanvas() {
return canvas;
}
- Load shape files and setting up style for displaying on the screen.
private void initMap() {
try {
FileDataStore store = FileDataStoreFinder.getDataStore(this.getClass().getResource("countries.shp"));
SimpleFeatureSource featureSource = store.getFeatureSource();
map = new MapContent();
map.setTitle("Quickstart");
Style style = SLD.createSimpleStyle(featureSource.getSchema());
FeatureLayer layer = new FeatureLayer(featureSource, style);
map.addLayer(layer);
map.getViewport().setScreenArea(new Rectangle((int) canvas.getWidth(), (int) canvas.getHeight()));
} catch (IOException e) {
e.printStackTrace();
}
}
- Use StreamingRender to draw MapContent on the canvas
Initial main application and screen size for display map
Main.java
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
MapCanvas canvas = new MapCanvas(1024, 768);
Pane pane = new Pane(canvas.getCanvas());
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Map Example");
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Source Code
What’s next?
In Tutorial Part 2, we will add more functionality like pan, zoom in and zoom out.