2

I am making a GIS maven project in GeoTools.

How can we display data from the PostgreSQL database in GeoTools?

Presently I can display the shapefile from the file path, but I want to display this shapefile from the PostgreSQL database. So I could run spatial queries here in GeoTools. I gave all the dependency for connectivity of PostgreSQL database to GeoTools in pom.xml file.

  • Thanks for your reply, I have already applied this solution. But here filenotfound exception has occurred. I think here also i can't open the table (exported shape file from the QGIS) from the postgresql database. In my project I have made a shape file in QGIS and import this shape file into the postgresql database. Now here this is in the form of table in which a column called geometry column. I want to display my shape file on JMapframe from this exported shape file (geometry column of the table in postgresql) of the postgresql. My code is..... [![enter image description here](i.stack – Neeraj Gangwal Aug 8 '16 at 17:31
  • take out the URL from the parameters - there is no need for any reference to the old shapefile – Ian Turton Aug 12 '16 at 10:44
1

The process for displaying a Layer in GeoTools is exactly the same regardless of where the data is stored so your question boils down to "how do I read in features from PostGIS?"

Currently your code must (should) construct a parameters map with the URL of the shapefile and passes that to DataStoreFinder:

String lines = "./linetest.shp";
Map<String, Object> params = new HashMap<>();
params.put("url", DataUtilities.fileToURL(new File(lines)));
DataStore ds = DataStoreFinder.getDataStore(params);

You then get a FeatureSource and combine it with a Style to make a Layer:

String type = ds.getTypeNames()[0];
FeatureLayer layer = new FeatureLayer(ds.getFeatureSource(type), style);

To do this with a PostGIS datastore is simply a case of creating the required parameters for the PostGIS connection and doing everything else the same. Helpfully the PostGIS datastore page of the documentation provides example code:

Map<String,Object> params = new HashMap<String,Object>();
params.put( "dbtype", "postgis");
params.put( "host", "localhost");
params.put( "port", 5432);
params.put( "schema", "public");
params.put( "database", "database");
params.put( "user", "postgres");
params.put( "passwd", "postgres");

DataStore dataStore=DataStoreFinder.getDataStore(params);

The only other difference is that now instead of only one typename as with the shapefile now you have a choice of one for each geographic table in the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.