Skip to content

Instantly share code, notes, and snippets.

@pborissow
Last active July 23, 2020 14:02
Show Gist options
  • Save pborissow/3f60108462ad6f5a33df531d4bb31f78 to your computer and use it in GitHub Desktop.
Save pborissow/3f60108462ad6f5a33df531d4bb31f78 to your computer and use it in GitHub Desktop.
How to create PostGIS HEXEWKB formatted geometry

How to create PostGIS HEXEWKB formatted geometry

When copying geometry data into PostgreSQL using COPY FROM STDIN it is a good idea to use the PostGIS HEXEWKB format. Here's how to create HEXEWKB using Java and JTS:

import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.WKBWriter;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.io.ByteOrderValues;

PrecisionModel precisionModel = new PrecisionModel();
GeometryFactory geometryFactory = new GeometryFactory(precisionModel, 4326);

WKBWriter wkbWriter = new WKBWriter(2, ByteOrderValues.LITTLE_ENDIAN, true);
byte[] b = wkbWriter.write(geometryFactory.createPoint(new Coordinate(longitude, latitude)));
String hex = WKBWriter.toHex(b);

Of course, you can create a geometry using WKT like this:

WKTReader wktReader = new WKTReader(geometryFactory);
Geometry geom = wktReader.read(point);
byte[] b = wkbWriter.write(geom);
String hex = WKBWriter.toHex(b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment