transport-accessibility/transport_accessibility/pt_map/templates/parsing_files.js

59 lines
2.4 KiB
JavaScript

function parseCSV(data) {
const lines = data.split(/\r\n|\n|\r/); // parse by \n and/or by \n
const headers = lines[0].split(',');
return lines.slice(1).map(line => { // lines.slice(1) creates a new array that excludes the first line (headers)
const values = line.split(','); // splits the line into an array of values
return headers.reduce((object, header, index) => {
object[header] = values[index];
return object;
}, {});
});
}
/**
* Function to parse shapes.txt file, add the shape geometries to the shapes["routes"] dictionary
* and draw the shapes on the map.
*/
function parseShapesFile(file) {
const reader = new FileReader();
reader.onload = function(event) {
const text = event.target.result;
const lines = text.split('\n');
const headers = lines[0].split(',');
const shapeIdIndex = headers.indexOf('shape_id');
const shapePtSequenceIndex = headers.indexOf('shape_pt_sequence');
const shapePtLatIndex = headers.indexOf('shape_pt_lat');
const shapePtLonIndex = headers.indexOf('shape_pt_lon');
for (let i = 1; i < lines.length; i++) {
const line = lines[i].trim();
if (line) {
const columns = line.split(',');
const shape_id = columns[shapeIdIndex];
const shape_pt_sequence = parseInt(columns[shapePtSequenceIndex], 10);
const shape_pt_lat = parseFloat(columns[shapePtLatIndex]);
const shape_pt_lon = parseFloat(columns[shapePtLonIndex]);
if (!shapes["routes"][shape_id]) {
shapes["routes"][shape_id] = [];
}
shapes["routes"][shape_id].push({
sequence: shape_pt_sequence,
lat: shape_pt_lat,
lon: shape_pt_lon
});
}
}
// Sort the shape points by sequence and draw them with click listeners
for (let shape_id in shapes["routes"]) {
if (shapes["routes"].hasOwnProperty(shape_id)) {
shapes["routes"][shape_id].sort((a, b) => a.sequence - b.sequence);
const latlngs = shapes["routes"][shape_id].map(point => [point.lat, point.lon]);
addClickableShape (latlngs, shape_id)
}
}
};
reader.readAsText(file);
}