diff options
Diffstat (limited to 'app/geometry.js')
| -rw-r--r-- | app/geometry.js | 56 |
1 files changed, 45 insertions, 11 deletions
diff --git a/app/geometry.js b/app/geometry.js index 0952bbb..37bb34f 100644 --- a/app/geometry.js +++ b/app/geometry.js @@ -65,6 +65,17 @@ export class Bounds { } /** + * @enum {string} + */ +export const GeometryType = { + linestring: "Line", + multilinestring: "MultiLineString", + multipolygon: "MultiPolygon", + point: "Point", + polygon: "Polygon", +}; + +/** * @typedef {[number, number]} Coordinate - [longitude, latitude] in decimal degrees */ @@ -133,6 +144,24 @@ export class Geometry { /** * Deserialize geometry from GeoJSON + * @param {Point|LineString|Polygon|MultiLineString} geometry + */ + static toEnum(geometry) { + if (geometry instanceof Point) { + return GeometryType.point; + } else if (geometry instanceof LineString) { + return GeometryType.linestring; + } else if (geometry instanceof MultiLineString) { + return GeometryType.multilinestring; + } else if (geometry instanceof Polygon) { + return GeometryType.polygon; + } else { + throw new Error(`Invalid GeoJSON object: missing required 'type' property`); + } + } + + /** + * Deserialize geometry from GeoJSON * @param {{type: string, coordinates?: any, [key: string]: any}} geojson * @returns {Point|LineString|Polygon|MultiLineString} */ @@ -161,13 +190,11 @@ export class Geometry { static bounds(geometry) { if (geometry instanceof Point) { return new Bounds(geometry.lng, geometry.lat, geometry.lng, geometry.lat); - } - - if (geometry instanceof LineString) { + } else if (geometry instanceof LineString) { return Geometry.calculateBoundsFromCoords(geometry.coordinates); - } - - if (geometry instanceof Polygon) { + } else if (geometry instanceof MultiLineString) { + return Geometry.calculateBoundsFromCoords(geometry.coordinates); + } else if (geometry instanceof Polygon) { return Geometry.calculateBoundsFromCoords(geometry.rings[0]); } throw new Error(`Unsupported geometry type: ${geometry}`); @@ -1028,12 +1055,14 @@ export class Polygon extends Geometry { export class Feature { /** - * @param {Geometry} geometry - Feature geometry - * @param {Object} [properties={}] - Feature properties - * @param {string|number} [id] - Feature ID + * @param {Geometry} geometry + * @param {GeometryType} type + * @param {Object} [properties={}] + * @param {string|number} [id] */ - constructor(geometry, properties = {}, id = "") { + constructor(geometry, type, properties = {}, id = "") { this.geometry = geometry; + this.type = type; this.properties = properties; this.id = id; } @@ -1062,7 +1091,12 @@ export class Feature { const geometry = Geometry.fromGeoJSON(geojson.geometry); if (!geometry) return null; - return new Feature(geometry, geojson.properties ?? {}, geojson.id ?? ""); + return new Feature( + geometry, + Geometry.toEnum(geometry), + geojson.properties ?? {}, + geojson.id ?? "", + ); } } |
