Question

I've just started with geometries and I'm getting some really odd errors. I'm trying to create a WKB inside my java code with an specific SRID.

I've done:

GeometryFactory gm = new GeometryFactory(new PrecisionModel,4326)
WKBWriter w = new WKBWriter(2,ByteOrderValues.LITTLE_ENDIAN)

Geometry geom: Geometry = gm.createPoint(new Coordinate(4,5))
Array[Byte] the_geom = w.write(geom)

println(geom)
println(geom.getSRID)
println(WKBWriter.toHex(the_geom.get))

and obtained

POINT (4 5)
4326
010100000000000000000010400000000000001440

But with postgis in my DB:

GEOMETRYFROMTEXT('Point(4 5)',4326)) 

results in

0101000020E610000000000000000010400000000000001440

What I'm getting wrong here??

Was it helpful?

Solution

PostGIS doesn't use (only) the WKB standard when an SRID is present, it uses the EWKB format that supports 3d and SRIDs, which the WKB specification does not. Think of WKB as a kind of light binary 2d array, it is a very simple format. It doesnt include elevation or an SRID in the binary representation, in the OGC standard spatial reference systems are metadata. Here are some of the kinds of interactions that might shed light on how you work with WKB and EWKB:

moveable=> insert into my_table (some_other_geom) values (GeomFromText('POINT(4 5)'));
moveable=> insert into my_table (some_other_geom) values (GeomFromText('POINT(4 5)', 4326));

This gives you:

010100000000000000000010400000000000001440
0101000020E610000000000000000010400000000000001440

as you saw. If you start with a hex value and want to add SRID projection and store as EWKB you do some variant of:

==>insert into my_table (some_other_geom) values (ST_GeomFromWKB(decode('010100000000000000000010400000000000001440', 'hex'), 4326));
INSERT 0 1

or:

moveable=> insert into my_table (some_other_geom) values (ST_GeomFromWKB(decode('010100000000000000000010400000000000001440', 'hex')));
INSERT 0 1

As you would expect these yield, respectively:

0101000020E610000000000000000010400000000000001440
010100000000000000000010400000000000001440

where the null -1 default SRID is the same as the non-SRID 2d WKB format. In general I think it is safer to work with WKT, GeoJSON, and KML, since they are also OGC(?)1 open standards and the SQL version has some needed updates pending. As the PostGIS docs suggest: "PostGIS extended formats are currently superset of OGC one (every valid WKB/WKT is a valid EWKB/EWKT) but this might vary in the future, specifically if OGC comes out with a new format conflicting with our extensions. Thus you SHOULD NOT rely on this feature!"

(1) Actually have no idea what the status of half these standards are, but json, text and xml seem likely to be around for the life of any given application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top