[GIS] WKB to WKT JavaScript function

javascriptwell-known-binarywell-known-text

Turns out json isn't so good at transporting binary data. But with HTML5, XHR2 is now capable of transferring blobs cleanly. I'm looking to transfer binary geometry (to save bandwidth) and decode it on the client.

To no avail, I've scoured the web for a javascript-based WKB (Well-known Binary) to WKT (Well-known Text) function. Before I re-invent the wheel — is anyone aware of any open-source solutions?

Best Answer

It looks like a new and better supported JS WKB parsing library has since appeared.

https://github.com/cschwarz/wkx

I've been able to use it to convert WKB directly from postgres into JS objects that can be mapped in the browser. You'll need to include https://github.com/cschwarz/wkx/blob/master/dist/wkx.js in your webpage for this to work.

// Required imports (works in browser, too)
var wkx = require('wkx');
var buffer = require('buffer');

// Sample data to convert
var wkbLonlat = '010100000072675909D36C52C0E151BB43B05E4440';

// Split WKB into array of integers (necessary to turn it into buffer)
var hexAry = wkbLonlat.match(/.{2}/g);
var intAry = [];
for (var i in hexAry) {
  intAry.push(parseInt(hexAry[i], 16));
}

// Generate the buffer
var buf = new buffer.Buffer(intAry);

// Parse buffer into geometric object
var geom = wkx.Geometry.parse(buf);

// Should log '-73.700380647'
console.log(geom.x)

// Should log '40.739754168'
console.log(geom.y)
Related Question