wkt-parser-helper
Version:
Module to help parse GeoJSONs to WKT and back
85 lines (84 loc) • 3.06 kB
JavaScript
import { geoJSONToWkt, wktToGeoJSON } from "betterknown";
import { klona } from "klona/json";
const EMPTY_GEOMETRY_COLLECTION_WKT = 'GEOMETRYCOLLECTION EMPTY';
function geometryToWkt(geojson) {
return geoJSONToWkt(geojson);
}
function featureToWkt(geojson) {
return geometryToWkt(geojson.geometry);
}
function featureCollectionToWkt(featureCollection) {
if ('FeatureCollection' !== featureCollection.type) throw new Error('GeoJSON is not a FeatureCollection');
return 0 === featureCollection.features.length ? EMPTY_GEOMETRY_COLLECTION_WKT : `GEOMETRYCOLLECTION(${featureCollection.features.map((d)=>featureToWkt(d)).join(',')})`;
}
function geojsonToWkt(geojson) {
switch(geojson.type){
case 'Feature':
return featureToWkt(geojson);
case 'FeatureCollection':
return featureCollectionToWkt(geojson);
default:
return geometryToWkt(geojson);
}
}
function featureCollectionToWktList(geojson) {
return geojson.features.map((d)=>({
wkt: geometryToWkt(d.geometry),
...d.properties
}));
}
function wktToGeojson(item, asFeature = false, properties = {}) {
let parsed;
parsed = item === EMPTY_GEOMETRY_COLLECTION_WKT ? {
type: 'GeometryCollection',
geometries: []
} : wktToGeoJSON(item);
if (asFeature) return {
type: 'Feature',
geometry: parsed,
properties
};
return parsed;
}
function stripZCoordinates(coords) {
if ('number' == typeof coords[0]) return coords.slice(0, 2);
return coords.map(stripZCoordinates);
}
function geojson3dTo2d(geojson) {
const newGeoJSON = klona(geojson);
function processGeometry(geom) {
if (null == geom) return null;
const type = geom.type;
switch(type){
case 'Point':
case 'MultiPoint':
case 'LineString':
case 'MultiLineString':
case 'Polygon':
case 'MultiPolygon':
geom.coordinates = stripZCoordinates(geom.coordinates);
break;
case 'GeometryCollection':
geom.geometries = geom.geometries.map(processGeometry);
break;
default:
throw new Error(`geometry type not supported: ${type}`);
}
return geom;
}
function processFeature(feature) {
if (feature.geometry) feature.geometry = processGeometry(feature.geometry);
return feature;
}
if ('Feature' === newGeoJSON.type) return processFeature(newGeoJSON);
if ('FeatureCollection' === newGeoJSON.type) {
newGeoJSON.features = newGeoJSON.features.map(processFeature);
return newGeoJSON;
}
return processGeometry(newGeoJSON);
}
function wkt3dTo2d(wkt) {
const geojson = wktToGeojson(wkt);
return geojsonToWkt(geojson3dTo2d(geojson));
}
export { EMPTY_GEOMETRY_COLLECTION_WKT, featureCollectionToWkt, featureCollectionToWktList, featureToWkt, geojson3dTo2d, geojsonToWkt, geometryToWkt, wkt3dTo2d, wktToGeojson };