Estimate project
← All posts

My First Steps in the Geospatial World: PostGIS, JTS, and What I Learned

A recap of my first encounter with the field – insights, lessons, and tips – written from the point of view of a backend engineer handling geospatial features for the first time in a real-world project.

9 min read
backendgeospatialpostGISJTS

Let me start by saying that I don’t come from the GIS world. Day to day, I build Scala-based, microservice-oriented systems, where we mostly worry about business logic, clean APIs, and distributed architecture. Geospatial data was unfamiliar territory for me – and this blog post recaps my first encounter with it – insights, lessons, and tips – written from the point of view of a backend engineer handling geospatial features for the first time in a real-world project.

We needed geospatial logic to manipulate, display, and analyze shipment trajectories based on data coming from vessels, trucks, IoT devices, and other sources. Two tools proved especially helpful:

  • PostGIS – a spatial extension to PostgreSQL that adds support for geographic objects – lets you store, query, and manipulate location-based data right in the database.
  • JTS Topology Suite – a Java library for modeling and processing 2D linear geometry.

The two tools work well together. PostGIS deals efficiently with large volumes of persistent spatial data, while JTS gives you more control and flexibility for complex logic in the application layer – for example, business rules with several conditional steps, temporary geometry transformations, or cases where performance depends on avoiding repeated database calls.

Sample spatial data showing a shipment trajectory between the ports of Rotterdam, Netherlands and Houston, USA.

Below are some insights & lessons I picked up while working with coordinates and geospatial queries:

1. Bringing PostGIS into the backend

Because PostGIS is a PostgreSQL extension, working with it feels just like running ordinary SQL. On the backend side, the main task is dealing with spatial types in your application code.

To use PostGIS types such as geography(Point, 4326), you have to convert between your application model and the spatial format the database expects. This matters particularly when ingesting data from sources such as JSON APIs – you parse the raw coordinates into your domain model and then insert or query them with PostGIS functions like:

ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)

In my case, I used Doobie, a functional JDBC layer for Scala. It lets you write raw SQL and specify, through implicit mapping, how spatial types travel between the database and the application (using the postgis-jdbc driver).

2. Spatial indices

To use PostGIS effectively, it helps to understand first why it handles spatial queries so well – and that story begins with spatial indexing. Conventional indexing approaches such as B-tree fall short for spatial operations. PostGIS builds on PostgreSQL’s native index types to support operations on spatial data, which is one of its strongest features.

PostGIS mainly relies on GiST (Generalized Search Tree) indexes, which arrange data in a hierarchy based on the bounding boxes of geometries. This lets the database rapidly discard irrelevant records by testing bounding box intersections before running more exact geometry calculations. To index spatial data, PostGIS uses an R-Tree index built on top of GiST. R-Trees split data into rectangles, sub-rectangles, and sub-sub rectangles.

Blog%20post%20pic%2002

The R-Tree hierarchy, (source).

SP-GiST (Space-Partitioned Generalized Search Tree) closely resembles GiST but is tuned specifically for spatial partitioning – that is, for data that doesn’t overlap and can be split cleanly into separate spaces.

Another index worth noting is BRIN (Block Range Index), which is even quicker to build and far smaller, but suits only particular kinds of data – spatially sorted and rarely or never updated (e.g., timestamped GPS logs).

For more on spatial indices, I suggest the PostGIS documentation itself.

3. PostGIS turns complex operations into simple ones

PostGIS hides the complexity of spatial computation behind compact SQL. Consider a practical case: excluding vessel trajectories that pass through a restricted area. A real-world scenario might be the closure of the Suez Canal, which would suddenly cut off access to it.

Given a PostGIS geography(LineString, 4326) column holding vessel positions:

CREATE TABLE trajectories(
   id uuid PRIMARY KEY,
   positions geography(LineString, 4326) NOT NULL
)

PostGIS lets us capture this requirement in one readable SQL query, without any complicated loops or geometry calculations in the application code:

SELECT * FROM trajectories
WHERE NOT ST_Intersects(
positions, 
ST_MakeEnvelope(32.1, 30.01, 32.66, 31.03, 4326)::geography
);

The geo boundary box [32.1, 30.01, 32.66, 31.03] used to represent a simplified Suez Canal region.

Another real-world case is filtering trajectories by their distance from a given position – for instance, finding vessels close to a port (given as approximate long/lat coordinates) in order to raise alerts:

SELECT * FROM trajectories WHERE ST_Distance(
positions,
ST_SetSRID(ST_MakePoint(18.698, 54.401), 4326)::geography
) <= 100000; -- 100km

4. In-memory JTS computations have their place too

At times, computing in memory is the right choice, even with large-scale data. Here’s a real-world example: we had to roughly verify whether vessel trajectories run into the earth’s land, so that faulty trajectories could be flagged for analytical purposes. The volume was considerable, the validation had to catch only genuinely serious collisions (ignoring “small” ones caused by the signal dropping for a few minutes), and it had to run on every request.

Our initial plan was to:

  1. Import an open-source map of the earth’s coastlines into PostGIS. We picked NaturalEarth data – more on it later in the blogpost
  2. Use ST_Buffer and ST_Simplify to shrink and tidy up the geometries – boosting performance and cutting down noise.
  3. Add checks at the SQL level with ST_Intersects

Close-up examples of a heavily simplified earth coastlines map around several major sea ports.

After these operations, however, the coastline map in WKB (Well-Known-Binary) format weighed just 175KB. Since this API is used fairly heavily and our Azure-hosted PostgreSQL instances were frequently constrained in certain operations, we concluded we could afford to load the entire map into the JVM on startup and run the checks in memory with the JTS library.

private val CoastlinesPolygonsFilePath = "/coastlines_polygons.wkb"

private val coastlinesJTSSpatialIndex: jts.index.STRtree = {
 val inputStream = getClass.getResourceAsStream(CoastlinesPolygonsFilePath)
 if (inputStream == null) throw new FileNotFoundException(CoastlinesPolygonsFilePath)

 val index = new jts.index.STRtree()
 val reader = new jts.io.WKBReader()

 Using.resource(Source.fromInputStream(inputStream)) { source =>
   source.getLines().foreach { wkbHex =>
     val wkbBytes = jts.io.WKBReader.hexToBytes(wkbHex)
     val geometry = reader.read(wkbBytes)
     index.insert(geometry.getEnvelopeInternal, geometry)
   }
 }

 index.build()
 index
}

def isTrajectoryColliding(trajectory: jts.geom.LineString): Boolean =
   coastlinesJTSSpatialIndex
       .query(trajectory.getEnvelopeInternal)
       .asInstanceOf[java.util.List[Geometry]]
       .asScala
       .exists(coastlines => coastlines.intersects(trajectory))

5. Watch the coordinate system – SRID

PostGIS binds geometries to an SRID (Spatial Reference System Identifiers), such as 4326 for standard GPS coordinates, and its spatial functions depend on it. JTS, by contrast, sees geometries as plain X/Y points with no notion of a coordinate system. As soon as a geometry passes through JTS, the SRID information is lost unless you take care of it yourself.

I learned the hard way that if you change a geometry in JTS and write it back to PostGIS without restoring the SRID, operations such as ST_Distance, ST_Intersects, or ST_Area may return wrong results. So always set the SRID explicitly again before storing geometries back in PostGIS, for example:

SELECT ST_SetSRID(geometry, 4326)

6. The 180th meridian is a tricky crossing

This one caught me off guard. A geometry that crosses the 180th meridian (called the antimeridian) can behave strangely. Some functions cope with it poorly, and even valid geometries may turn “invalid” in the eyes of PostGIS / JTS.
Here is how a sample trajectory crossing the 180th meridian looks when projected in GeoJSON format:

A vessel trajectory from Tokyo, Japan to Los Angeles, USA.

Here, the trajectory appears to stretch across the whole globe. This is a well-known issue in the GIS world. By default, longitudes run from -180° to +180°, and the 180th meridian marks where they meet. Sadly, many geometry engines – PostGIS and JTS included – treat that boundary as a hard edge instead of letting values wrap around.

The jump from +180° to -180°.

Our workaround for this case is normalizing longitudes to the 0°-360° range before any processing. Built-in PostGIS or JTS methods can do this (e.g., ST_ShiftLongitude), and it works fine for most internal processing.

The solution recommended by the GeoJSON spec for such cases, on the other hand, is: A geometry crossing the antimeridian SHOULD be represented by splitting it into two parts, neither of which crosses the antimeridian in its representation.

This lets, for instance, a map in your frontend draw two valid geometries rather than a single invalid one.

7. There’s no standard coordinate order

Another thing that surprised me is the lack of a universally agreed order for coordinates (latitude/longitude or longitude/latitude). When an API returns coordinates as a raw array such as [[10, 0], [15, 0]], you can’t immediately tell whether it is [long, lat] or [lat, long] unless this is stated explicitly.

A few more examples:

  • PostGIS keeps geometry in the database in WKB (Well-Known-Binary) or WKT (Well-Known-Text) format, following the long/lat convention
  • Google Maps expects coordinates for search in lat/long order
  • The JTS library operates on a Cartesian plane using the Coordinate(x, y) model, treating x as horizontal (longitude) and y as vertical (latitude)

If you happened to load data into PostGIS in lat/long order, you can still swap it easily with the ST_FlipCoordinates function. Either way, always verify the coordinate order of your data, or it could take you halfway around the world. Literally.

8. Natural Earth & Open Street Map data

Two great open-source resources cover most of the basic, good-quality geospatial data you’ll need – Natural Earth and OpenStreetMap (OSM).

OpenStreetMap is a famous, enormous global project with highly detailed maps, but what I needed was data that roughly outlines country borders and coastlines. For that, Natural Earth came out on top with its clean, pre-simplified geometries. Its datasets are light and simple to import into PostGIS, and for global-scale spatial queries and overlays, they simply work.

9. IntelliJ extensions for viewing geographies

To take a quick visual look at your geographies, you can export PostGIS data to GeoJson format and paste it into geojson.io. As a Scala developer, though, I spend most of my time in IntelliJ and prefer not to leave the IDE when I can avoid it. For that, you can use:

  • IntelliJ’s built-in GeoViewer – works right away, but requires an IntelliJ Ultimate license. When using the database plugin, you can click Show Geo Viewer on a PostGIS query result. A nice touch is the wide choice of map backgrounds (the example below uses Esri.WorldPhysical).

The GeoViewer built into IntelliJ.

  • GeoJSON Editor – an IntelliJ plugin that fully supports files with the .geo.json extension. It comes in handy when your repo contains such files, e.g., for storing snapshots of specific geospatial test results, readmes, etc., or when you export data from PostGIS in GeoJSON format to keep it for later.

The GeoJSON Editor in IntelliJ.

What’s especially interesting is that the GeoJSON editor lets you edit geographies – adding simple shapes or changing a route – and writes the result to the file in real time. This is very handy for building specific test cases.

The GeoJSON Editor in edit mode.

Summary

Coming from outside the GIS world, I found my first encounter with geospatial data surprisingly enjoyable. PostGIS and JTS made it feel natural to build features right in the backend, from simple distance checks to dealing with antimeridian crossings and coastline collisions. I hope this blog has been useful to you – whether you’re just starting out with spatial data or already experimenting with it at work.