Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert data from PostGIS database into GeoJSON in Java

I have a PostgreSQL/PostGIS database and I want to convert my data table from database into GeoJSON format.

My purpose is to use this GeoJSON for creating a map with JavaScript. I am using Java and JDBC in Spring MVC. What is the best way to convert data?

like image 382
jack Avatar asked Nov 10 '16 01:11

jack


People also ask

Which tool is used to convert data into and from PostGIS to many data formats?

ogr2ogr is a commandline utility for converting data between GIS data formats, including common file formats and common spatial databases. Windows: Builds of ogr2ogr can be downloaded from GIS Internals. ogr2ogr is included as part of QGIS Install and accessible via OSGeo4W Shell -

What is the difference between Postgres and PostGIS?

So PostgreSQL (a.k.a. Postgres) is THE database and PostGIS is like an add-on to that database. The latest release version of PostGIS now comes packaged with PostgreSQL. In a nutshell PostGIS adds spatial functions such as distance, area, union, intersection, and specialty geometry data types to PostgreSQL.

Is PostGIS a database?

PostGIS is a spatial database extender for PostgreSQL object-relational database. It adds support for geographic objects allowing location queries to be run in SQL.


2 Answers

This can be done in the query that pulls the data out of the database. You can use the postgis function ST_AsGeoJSON(). Here is a link to the documentation for it.

https://postgis.net/docs/ST_AsGeoJSON.html

One thing to note is that the result of ST_AsGeoJSON() only returns the geometry portion of the data. If you need to get a geojson feature, then you will have to create the feature object and add the geometry to it.

An example of the result that you should expect when using ST_AsGeoJSON() would be {"type": "Point", "coordinates": [12, 15]}.

If you wanted to create a feature out of the geometry object, that would look something like {"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [12, 15]}}.

like image 190
Dylan Hamilton Avatar answered Oct 19 '22 17:10

Dylan Hamilton


ogr2ogr is your friend. Steve Bennett gives an excellent example with custom properties/columns selection here, along the lines of this:

ogr2ogr -f GeoJSON out.json "PG:host=localhost dbname=mydb user=myuser password=mypw" -sql "SELECT column1, column2, column3 FROM mytable"

like image 42
chris Avatar answered Oct 19 '22 17:10

chris