demarches-normaliennes/app/javascript/components/MapEditor/readGeoFile.ts

97 lines
2.6 KiB
TypeScript
Raw Normal View History

2020-09-20 13:19:09 +02:00
import { gpx, kml } from '@tmcw/togeojson/dist/togeojson.es.js';
import type { FeatureCollection, Feature } from 'geojson';
2020-09-20 13:19:09 +02:00
import { generateId } from '../shared/maplibre/utils';
export function readGeoFile(file: File) {
2021-05-06 18:51:53 +02:00
const isGpxFile = file.name.includes('.gpx');
const reader = new FileReader();
return new Promise<ReturnType<typeof normalizeFeatureCollection>>(
(resolve) => {
reader.onload = (event: FileReaderEventMap['load']) => {
const result = event.target?.result;
const xml = new DOMParser().parseFromString(
result as string,
'text/xml'
);
const featureCollection = normalizeFeatureCollection(
isGpxFile ? gpx(xml) : kml(xml),
file.name
);
2020-09-20 13:19:09 +02:00
resolve(featureCollection);
};
reader.readAsText(file, 'UTF-8');
}
);
2021-05-06 18:51:53 +02:00
}
function normalizeFeatureCollection(
featureCollection: FeatureCollection,
filename: string
) {
const features: Feature[] = [];
2020-09-20 13:19:09 +02:00
for (const feature of featureCollection.features) {
switch (feature.geometry.type) {
case 'MultiPoint':
for (const coordinates of feature.geometry.coordinates) {
features.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates
},
properties: feature.properties
});
}
break;
case 'MultiLineString':
for (const coordinates of feature.geometry.coordinates) {
features.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates
},
properties: feature.properties
});
}
break;
case 'MultiPolygon':
for (const coordinates of feature.geometry.coordinates) {
features.push({
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates
},
properties: feature.properties
});
}
break;
case 'GeometryCollection':
for (const geometry of feature.geometry.geometries) {
features.push({
type: 'Feature',
geometry,
properties: feature.properties
});
}
break;
default:
features.push(feature);
}
}
const featureCollectionFilename = `${generateId()}-${filename}`;
2021-05-06 18:51:53 +02:00
featureCollection.features = features.map((feature) => ({
...feature,
properties: {
...feature.properties,
filename: featureCollectionFilename
2021-05-06 18:51:53 +02:00
}
}));
return { ...featureCollection, filename: featureCollectionFilename };
2020-09-20 13:19:09 +02:00
}