Last active
July 5, 2019 02:50
-
-
Save alpha-beta-soup/e6af529ccedf0da0e52c191811e56f79 to your computer and use it in GitHub Desktop.
GeoJSON serialiser that doesn't explode your nested coordinate arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const replacerWrapper = val => val.replace(/\"\[/g, '[').replace(/\]\"/g,']') | |
const replacer = (name, val) => { | |
console.log({name, val}) | |
if (name === 'coordinates' && Array.isArray(val)) { | |
val = JSON.stringify(val) | |
} | |
return val | |
} | |
module.exports = { | |
replacer, replacerWrapper, | |
geojsonSerialiser: (geojson, space) => replacerWrapper(JSON.stringify(geojson, replacer, space)) | |
} | |
// Usage: | |
// import { geojsonSerialiser } from 'geojson-stringify' | |
// geojsonSerialiser(geojsonObject, 2) | |
// Output is the same as JSON.stringify(geojson, null, 2), but with `geometry.coordinates` arrays on a single line, e.g. | |
// { | |
// "@context": { | |
// "geojson": "https://purl.org/geojson/vocab#", | |
// "Feature": "geojson:Feature", | |
// "FeatureCollection": "geojson:FeatureCollection", | |
// "GeometryCollection": "geojson:GeometryCollection", | |
// "LineString": "geojson:LineString", | |
// "MultiLineString": "geojson:MultiLineString", | |
// "MultiPoint": "geojson:MultiPoint", | |
// "MultiPolygon": "geojson:MultiPolygon", | |
// "Point": "geojson:Point", | |
// "Polygon": "geojson:Polygon", | |
// "bbox": { | |
// "@container": "@list", | |
// "@id": "geojson:bbox" | |
// }, | |
// "coordinates": { | |
// "@container": "@list", | |
// "@id": "geojson:coordinates" | |
// }, | |
// "features": { | |
// "@container": "@set", | |
// "@id": "geojson:features" | |
// }, | |
// "geometry": "geojson:geometry", | |
// "id": "@id", | |
// "properties": "geojson:properties", | |
// "type": "@type", | |
// "description": "http://purl.org/dc/terms/description", | |
// "title": "http://purl.org/dc/terms/title" | |
// }, | |
// "type": "Feature", | |
// "id": "sample-multipolygon", | |
// "geometry": { | |
// "type": "MultiPolygon", | |
// "coordinates": [[[[180,40],[180,50],[170,50],[170,40],[180,40]]],[[[-170,40],[-170,50],[-180,50],[-180,40],[-170,40]]]] | |
// }, | |
// "properties": { | |
// "title": "Sample MultiPolygon", | |
// "description": "Antimerdian-straddling MultiPolygon from RFC7946" | |
// } | |
// } | |
// Note the value of geometry.coordinates does not have line breaks! Sanity prevails. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment