HarryStevens / geometric

A JavaScript library for doing geometry.
https://www.npmjs.com/package/geometric
MIT License
980 stars 49 forks source link

Support for parsing geometries from WKT strings #37

Closed anieuwland closed 2 years ago

anieuwland commented 2 years ago

We communicate geometric shapes a lot via WKT strings. Does this project consider parsing from such a string within scope? For example:

const polygon = geometric.wkt.parse("POLYGON (( 0.0 0.0, 0.0 10.0, 10.0 10.0, 10.0 0.0, 0.0 0.0 ))");

If so, we might be able to contribute this.

Or alternatively, does geometric envision other ways to instantiate a shape, perhaps from a geojson, without manually recognizing the geometry type and juggling coordinates?

HarryStevens commented 2 years ago

Hey @anieuwland ,

Thanks for your interest in Geometric.js.

The first thing to note is that WKT supports multipart geometries, such as MultiLineStrings and MultiPolygons, as well as polygons with holes. Geometric.js does not support those and has no plans to do so. That is because I've designed the library to work with native JavaScript arrays, rather than non-native data types such as GeoJSON or WKT. This is a tradeoff. You can do many more operations when you support multipart geometries, such as boolean operations. However, there are already mature and well-supported libraries, such as d3-geo and Turf.js, that work with GeoJSON, and I have no desire to try to replicate them. And there are benefits of working with native JavaScript arrays. They are simpler, and you can simply pass them to the points attribute of an SVG polygon or SVG polyline, which is very convenient.

That said, you can write a custom parser that would handle the polygon in your example:

function parse(string) {
  return string
    .replace("POLYGON (( ", "")
    .replace(" ))", "")
    .split(", ")
    .map(d => d.split(" ").map(Number));
}

You could pass that function's output to one of Geometric's polygon functions. It would be easy enough to write parsers for other data types. But it is beyond the scope of this library to incorporate those parsers.