minor changes

This commit is contained in:
Jan Kiljanski
2024-06-11 20:53:52 +02:00
parent f2260b3a76
commit 9f541916e3
7 changed files with 10 additions and 3 deletions

View File

@@ -10,6 +10,9 @@
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw/dist/leaflet.draw.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine/dist/leaflet-routing-machine.css" />
{% load static %}
<style>
body, html {
height: 100%;
@@ -43,7 +46,6 @@
}
</style>
</style>
{% load static %}
</head>
<body>
<div class="sidebar">
@@ -105,9 +107,14 @@
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<script src="https://unpkg.com/leaflet-draw/dist/leaflet.draw.js"></script>
<!-- Scripts with helper functions -->
<script src="sidebar.js"></script>
<!-- <script src="sidebar.js"></script>
<script src="shapes_on_map.js"></script>
<script src="parsing_files.js"></script>
<script src="parsing_files.js"></script> -->
<script src="{%static 'pt_map/sidebar.js'%}"></script>
<script src="{%static 'pt_map/shapes_on_map.js'%}"></script>
<script src="{%static 'pt_map/parsing_files.js'"%}></script>
<script>
// Initialize the map centered on Toruń, Poland

View File

@@ -1,110 +0,0 @@
// This script is not imported in the main script at all
// Function that takes a shape of a route and draws an OSRM path along it
function shapeToOSRM (polyline) {
if (!polyline) {
console.error('Invalid polyline');
return;
}
// Get the latlngs array from the polyline
const latlngs = polyline.getLatLngs();
if (latlngs.length < 2) {
console.error('Polyline should have at least two points');
return;
}
// Define start and end points
const startPoint = latlngs[0];
const endPoint = latlngs[latlngs.length - 1];
const initialWaypoints = [
L.latLng(startPoint.lat, startPoint.lng),
L.latLng(endPoint.lat, endPoint.lng)
];
console.log('initialWaypoints', initialWaypoints[0]);
const routingControl = L.Routing.control({
waypoints: initialWaypoints,
routeWhileDragging: false,
createMarker: () => null // Don't create markers for initial route
}).addTo(map);
console.log('Added routingControl.');
routingControl.on('routesfound', function (e) {
const routes = e.routes;
const routePolyline = routes[0].coordinates;
console.log('routePolyline[0]: ', routePolyline[0]);
// Find the furthest point from the original polyline to the generated polyline
const furthestPoint = findFurthestPoint(latlngs, routePolyline);
console.log('furthestPoint: ', furthestPoint);
// Create new waypoints with the furthest point added
const newWaypoints = [
L.latLng(startPoint.lat, startPoint.lng),
L.latLng(furthestPoint.lat, furthestPoint.lng),
L.latLng(endPoint.lat, endPoint.lng)
];
// Generate the new route with the updated waypoints
generateNewRoute(newWaypoints);
});
}
function generateNewRoute(waypoints) {
if (window.finalRoutingControl) {
map.removeControl(window.finalRoutingControl);
}
window.finalRoutingControl = L.Routing.control({
waypoints: waypoints,
routeWhileDragging: false
}).addTo(map);
}
function findFurthestPoint(originalPolyline, generatedPolyline) {
let maxDistance = -1;
let furthestPoint = null;
originalPolyline.forEach(point => {
const latlngPoint = L.latLng(point.lat, point.lng);
const distance = findDistanceToPolyline(latlngPoint, generatedPolyline);
if (distance > maxDistance) {
maxDistance = distance;
furthestPoint = point;
}
});
return furthestPoint;
}
function findDistanceToPolyline(point, polyline) {
let minDistance = Infinity;
polyline.forEach((segmentPoint, index) => {
if (index === 0) return;
const prevPoint = polyline[index - 1];
console.log('Current shapefile point: ', point);
console.log('Current generated polyline point: ', segment);
const segmentDistance = L.GeometryUtil.distanceSegment(map, point, prevPoint, segmentPoint);
minDistance = Math.min(minDistance, segmentDistance);
});
return minDistance;
}

View File

@@ -1,59 +0,0 @@
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);
}

View File

@@ -1,99 +0,0 @@
function addClickableShape (latlngs, shape_id) {
// Create polyline and add to map
const polyline = L.polyline(latlngs, { color: 'blue', weight: 5 }).addTo(map);
// Store polyline reference in shapes object for reset purpose
shapes["routes"][shape_id].polyline = polyline;
// Add click event listener to polyline
polyline.on('click', function (e) {
let shape_ids = [shape_id];
highlightShapes(shape_ids, "routes");
displayShapeOptions(shape_id, shapes);
console.log('Shape clicked:', shape_id);
});
}
function addClickablePoint(latlng, point_id) {
// latlng = a pair of coordinates, e.g., (52.2297, 21.0122) for Warsaw.
// Tags version
// Create marker and add to map
// const marker = L.marker(latlng).addTo(map);
// Points version
// Create circle marker and add to map
const marker = L.circleMarker(latlng, { radius: 10, color: 'blue'}).addTo(map);
// Store marker reference in points object for reset purpose
shapes["stops"][point_id]["marker"] = marker;
// Add click event listener to marker
marker.on('click', function (e) {
let point_ids = [point_id];
highlightShapes(point_ids, "stops");
console.log('Point clicked:', point_id);
});
}
function deleteShape(shapeID) {
if (shapes["routes"][shapeID] && shapes["routes"][shapeID].polyline) {
map.removeLayer(shapes["routes"][shapeID].polyline); // Remove the polyline from the map
delete shapes["routes"][shapeID]; // Delete the shape from the shapes object
console.log('Shape deleted:', shapeID);
}
}
function highlightShapes(shape_ids, type) {
// Reset previous polylines to blue
if (currentShapeIDs["routes"].length > 0) {
for (const id of currentShapeIDs["routes"]) {
if (shapes["routes"][id] && shapes["routes"][id].polyline) {
shapes["routes"][id].polyline.setStyle({ color: 'blue' });
}
}
}
if (currentShapeIDs["stops"].length > 0) {
for (const id of currentShapeIDs["stops"]) {
if (shapes["stops"][id] && shapes[id]["marker"]) {
shapes["stops"][id]["marker"].setStyle({ color: 'blue' });
}
}
}
if (type == "routes") {
for (const id of shape_ids) {
// Highlight the clicked polyline
if (shapes[type][id] && shapes[type][id].polyline) {
shapes[type][id].polyline.setStyle({ color: 'red' }).bringToFront();
}
}
}
if (type == "stops") {
for (const id of shape_ids) {
// Highlight the clicked polyline
if (shapes[type][id] && shapes[type][id]["marker"]) {
shapes[type][id]["marker"].setStyle({ color: 'red' }).bringToFront();
}
}
}
// Set new currentShapeIDs value
currentShapeIDs[type] = shape_ids;
}
function makeShapesBlue() {
// Reset previous polylines to blue
if (currentShapeIDs["routes"].length > 0) {
for (const id of currentShapeIDs["routes"]) {
if (shapes["routes"][id] && shapes["routes"][id].polyline) {
shapes["routes"][id].polyline.setStyle({ color: 'blue' });
}
}
}
}

View File

@@ -1,349 +0,0 @@
function handleFileSelect(event) {
const files = event.target.files;
const routesFile = Array.from(files).find(file => file.name === 'routes.txt');
const tripsFile = Array.from(files).find(file => file.name === 'trips.txt');
const stopsFile = Array.from(files).find(file => file.name === 'stops.txt');
const stopTimesFile = Array.from(files).find(file => file.name === 'stop_times.txt');
if (routesFile && tripsFile && stopsFile && stopTimesFile) {
// Read and parse the routes file
const routesReader = new FileReader();
routesReader.onload = function(e) {
routesData = parseCSV(e.target.result);
displayRouteIds(routesData);
};
routesReader.readAsText(routesFile);
// Read and parse the trips file
const tripsReader = new FileReader();
tripsReader.onload = function(e) {
tripsData = parseCSV(e.target.result);
};
tripsReader.readAsText(tripsFile);
// Read and parse the stops file
const stopsReader = new FileReader();
stopsReader.onload = function(e) {
stopsData = parseCSV(e.target.result);
//console.log(stopsData[0]);
for (let stop of stopsData) {
let id = stop["stop_id"];
// console.log("id: ", id);
let stop_lat = stop["stop_lat"];
let stop_lon = stop["stop_lon"];
if (stop_lat == undefined || stop_lon == undefined) {
continue;
}
else {
//console.log("stop_lat: ", stop_lat);
//console.log("stop_lon: ", stop_lon);
shapes["stops"][id] = {
lat: stop_lat,
lon: stop_lon
};
//console.log(shapes["stops"][stop["stop_id"]]);
addClickablePoint([stop_lat, stop_lon], id);
}
}
};
stopsReader.readAsText(stopsFile);
// Read and parse the stops file
const stopTimesReader = new FileReader();
stopTimesReader.onload = function(e) {
stopTimesData = parseCSV(e.target.result);
};
stopTimesReader.readAsText(stopTimesFile);
console.log(stopsData.length);
} else {
alert('Please select a valid GTFS folder containing routes.txt, trips.txt, stops.txt, and stop_times.txt files.');
}
// Handle shapes file
let shapesFile;
for (let file of files) {
if (file.name === 'shapes.txt') {
shapesFile = file;
break;
}
}
if (shapesFile) {
// Parse shapes.txt file and draw on the map
parseShapesFile(shapesFile);
} else {
alert('shapes.txt file not found in the selected folder.');
}
}
function displayRouteIds(routes) {
const currentRoutes = document.getElementById('currentRoutes');
const routeList = document.createElement('div');
routeList.className = 'list-group route-list';
routes.forEach(route => {
const routeItem = document.createElement('a');
routeItem.className = 'list-group-item list-group-item-action';
routeItem.textContent = route.route_id;
//routeItem.onclick = () => showTrips(route.route_id);
routeItem.href = '/?timetable=' + route.route_id;
routeList.appendChild(routeItem);
});
currentRoutes.appendChild(routeList);
}
function showTrips(chosenRouteId) {
// Filter the routesData rows where route_id is equal to the targetRouteId
const filteredTrips = tripsData.filter(route => route.route_id == chosenRouteId);
console.log('chosenRouteId: ', chosenRouteId);
console.log('filteredTrips[0]: ', filteredTrips[0]);
// Map the filtered rows to their shape_id values
const shapeIds = filteredTrips.map(trip => trip.shape_id);
console.log('shapeIds[0]: ', shapeIds[0]);
highlightShapes(shapeIds, "routes");
const tripsTable = document.getElementById('tripsTable');
tripsTable.innerHTML = '';
if (filteredTrips.length > 0) {
const tripIds = filteredTrips.map(trip => trip.trip_id);;
console.log('headers: ', tripIds);
const headerRow = document.createElement('tr');
tripIds.forEach(tripId => {
const th = document.createElement('th');
th.textContent = tripId;
headerRow.appendChild(th);
});
tripsTable.appendChild(headerRow);
// Now filter data for table rows
const filteredStopTimes = stopTimesData.filter(stopTime => tripIds.includes(stopTime.trip_id));
const filteredDepartureTimes = filteredStopTimes.map(stopTime => stopTime.departure_time)
const uniqueStopIds = [...new Set(filteredStopTimes.map(stopTime => stopTime.stop_id))];
// Create stop_names array by finding the stop_name for each unique stop_id
const rowValues = uniqueStopIds.map(stopId => {
const stop = stopsData.find(stop => stop.stop_id === stopId);
stop_name = stop ? stop.stop_name : 'Unknown Stop';
currentStopTimes = filteredStopTimes.filter(stopTime => stopTime.stop_id == stopId)
const sortedStopTimes = currentStopTimes.sort((a, b) => {
return tripIds.indexOf(a.trip_id) - tripIds.indexOf(b.trip_id);
}).map(stop => stop.departure_time);
return [stop_name].concat(sortedStopTimes);
});
console.log(rowValues);
// Create rows with stop_names as row headers
stop_names.forEach(stopName => {
const row = document.createElement('tr');
const rowHeader = document.createElement('th');
rowHeader.textContent = stopName;
row.appendChild(rowHeader);
// Add empty cells for each tripId
tripIds.forEach(() => {
const cell = document.createElement('td');
row.appendChild(cell);
});
tripsTable.appendChild(row);
});
} else {
const noDataRow = document.createElement('tr');
const noDataCell = document.createElement('td');
noDataCell.colSpan = Object.keys(trips[0] || {}).length;
noDataCell.textContent = 'No trips found for this route.';
noDataRow.appendChild(noDataCell);
tripsTable.appendChild(noDataRow);
}
$('#tripsModal').modal('show');
}
function addNewShape() {
console.log("Function addNewShape() not defined.");
}
function drawNewShape() {
shapeStops = [];
cancelShapeEdit();
// Create a container div for the buttons
const buttonContainer = document.createElement('div');
buttonContainer.className = 'button-container mt-3 p-3 border rounded';
// Create Toggle OSM router machine button
const editButton = document.createElement('button');
editButton.className = 'btn btn-primary btn-block my-2';
editButton.textContent = 'Toggle OSM router machine';
editButton.onclick = () => {
// Open route editing tool
shapeToOSRM(shapes["routes"][shapeId].polyline);
};
buttonContainer.appendChild(editButton);
// Create Save button
const saveButton = document.createElement('button');
saveButton.className = 'btn btn-secondary btn-block my-2';
saveButton.textContent = 'Save Shape';
saveButton.setAttribute('ready-to-save', 'false');
saveButton.onclick = () => {
if (saveButton.getAttribute('ready-to-save') === 'true') {
// Append coordinates to stops list
var latlngs = currentLayer.getLatLngs();
latlngs.forEach(function(latlng) {
//stops.push([latlng.lat, latlng.lng]);
});
// Transform the polyline into the specified format in the shapes dictionary
shape_id = "n_" + numNewShapes;
numNewShapes += 1;
shapes["routes"][shape_id] = [];
latlngs.forEach(function(latlng, index) {
shapes["routes"][shape_id].push({
sequence: index + 1,
lat: latlng.lat,
lon: latlng.lng
});
});
// Delete the layer with the drawn polyline
map.removeLayer(currentLayer);
// Create polyline and add to map
addClickableShape (latlngs, shape_id);
// Log the results
console.log('Stops:', stops);
console.log('Shapes:', shapes["routes"]);
// Change button esthetics to default
saveButton.style.backgroundColor = '';
saveButton.style.color = '';
cancelShapeEdit();
}
};
buttonContainer.appendChild(saveButton);
// Create Cancel button
const cancelButton = document.createElement('button');
cancelButton.className = 'btn btn-secondary btn-block my-2';
cancelButton.textContent = 'Cancel';
cancelButton.onclick = () => {
cancelShapeEdit();
};
buttonContainer.appendChild(cancelButton);
// Append the button container to the chosenShape element
chosenShape.appendChild(buttonContainer);
polylineDrawer.enable();
// Add created polylines to the map
map.on(L.Draw.Event.CREATED, function (event) {
var layer = event.layer;
currentLayer = layer;
drawnItems.addLayer(layer);
});
// Add created shapes to the map and handle the polyline
map.on(L.Draw.Event.CREATED, function (event) {
var layer = event.layer;
// Check if the drawn shape is a polyline
if (layer instanceof L.Polyline && !(layer instanceof L.Polygon)) {
// Disable the drawing control
map.removeControl(drawControl);
saveButton.style.backgroundColor = 'green';
saveButton.style.color = 'white'; // Ensure the text is readable
saveButton.setAttribute('ready-to-save', 'true');
} else {
// Add the drawn layer to the map if it's not a polyline
drawnItems.addLayer(layer);
}
});
}
function displayShapeOptions(shapeId, shapes) {
const chosenShape = document.getElementById('chosenShape');
// Clear any existing content inside chosenShape
while (chosenShape.firstChild) {
chosenShape.removeChild(chosenShape.firstChild);
}
// Add text content at the top
const textContent = document.createElement('div');
textContent.textContent = "Shape " + shapeId;
chosenShape.appendChild(textContent);
// Create a container div for the buttons
const buttonContainer = document.createElement('div');
buttonContainer.className = 'button-container mt-3 p-3 border rounded';
// Create Edit button
const editButton = document.createElement('button');
editButton.className = 'btn btn-primary btn-block my-2';
editButton.textContent = 'Edit Shape';
editButton.onclick = () => {
// Open route editing tool
shapeToOSRM(shapes["routes"][shapeId].polyline);
};
buttonContainer.appendChild(editButton);
// Create Delete button
const deleteButton = document.createElement('button');
deleteButton.className = 'btn btn-danger btn-block my-2';
deleteButton.textContent = 'Delete Shape';
deleteButton.onclick = () => {
// Cancel the edit view for the current shape
cancelShapeEdit();
// Delete the current shape and its representation from the map
deleteShape(shapeId);
};
buttonContainer.appendChild(deleteButton);
// Create Cancel button
const cancelButton = document.createElement('button');
cancelButton.className = 'btn btn-secondary btn-block my-2';
cancelButton.textContent = 'Cancel';
cancelButton.onclick = () => {
cancelShapeEdit();
};
buttonContainer.appendChild(cancelButton);
// Append the button container to the chosenShape element
chosenShape.appendChild(buttonContainer);
}
function cancelShapeEdit () {
// Define reference to the chosenShape field
const chosenShape = document.getElementById('chosenShape');
// Remove any existing routing control (if needed)
if (window.routingControl) {
map.removeControl(window.routingControl);
}
// Disable the current drawing
polylineDrawer.disable();
// Clear all drawn items
drawnItems.clearLayers();
// Clear any existing content inside chosenShape
while (chosenShape.firstChild) {
chosenShape.removeChild(chosenShape.firstChild);
}
// Add text content at the top
const textContent = document.createElement('div');
textContent.textContent = "Chosen Shape";
chosenShape.appendChild(textContent);
makeShapesBlue();
}