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?
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 -
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.
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.
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]}}
.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With