geojson.js (1865B)
1 import {decode} from 'utf8'; 2 3 function parseGeojson(txt, fileName) { 4 let error; 5 6 const tracks = []; 7 const points = []; 8 9 function parsePoints(features) { 10 features.forEach((feature) => { 11 let pointName = ''; 12 13 if ('name' in feature.properties) { 14 pointName = decode(feature.properties.name.toString()); 15 } 16 17 const [lng, lat] = feature.geometry.coordinates; 18 19 if (typeof lng !== 'number' || typeof lat !== 'number') { 20 error = 'CORRUPT'; 21 22 return; 23 } 24 25 points.push({ 26 lng, 27 lat, 28 name: pointName, 29 }); 30 }); 31 } 32 33 function parseTracks(features) { 34 features.forEach((feature) => { 35 const segment = []; 36 37 feature.geometry.coordinates.forEach((coordinate) => { 38 const [lng, lat] = coordinate; 39 40 if (typeof lng !== 'number' || typeof lat !== 'number') { 41 error = 'CORRUPT'; 42 43 return; 44 } 45 46 segment.push({ 47 lng, 48 lat, 49 }); 50 }); 51 52 if (segment.length < 2) { 53 error = 'CORRUPT'; 54 55 return; 56 } 57 58 tracks.push(segment); 59 }); 60 } 61 62 try { 63 const json = JSON.parse(txt); 64 65 const features = json.features; 66 67 parsePoints(features.filter((feature) => feature.geometry.type === 'Point')); 68 parseTracks(features.filter((feature) => feature.geometry.type === 'LineString')); 69 } catch (err) { 70 error = 'CORRUPT'; 71 } 72 73 return [ 74 { 75 name: fileName, 76 tracks, 77 points, 78 error, 79 }, 80 ]; 81 } 82 83 export {parseGeojson};