added map to trip view

Thu, 13 Sep 2018 21:32:30 +0300

author
Teemu Piippo <teemu@hecknology.net>
date
Thu, 13 Sep 2018 21:32:30 +0300
changeset 114
b736478416d4
parent 113
b8467d51f1b8
child 115
9452b9ac69e6

added map to trip view

buses.py file | annotate | diff | comparison | revisions
service.py file | annotate | diff | comparison | revisions
templates/custom_cluster.html file | annotate | diff | comparison | revisions
templates/trip.html file | annotate | diff | comparison | revisions
--- a/buses.py	Wed Sep 12 08:27:27 2018 +0300
+++ b/buses.py	Thu Sep 13 21:32:30 2018 +0300
@@ -10,11 +10,12 @@
 	return reference
 
 class BusTrip:
-	def __init__(self, reference, route, service, length, block_id):
+	def __init__(self, reference, route, service, length, block_id, shape):
 		self.reference, self.route, self.service, self.block_id = reference, route, service, block_id
 		self.length = length
 		self.schedule = []
 		self.name = transform_trip_reference(reference)
+		self.shape = str(shape)
 	def __repr__(self):
 		return 'all_trips[%r]' % self.name
 	def contains_stop(self, stop):
@@ -219,6 +220,8 @@
 			result += stop.schedule(max_amount = max_amount)
 		result.sort(key = lambda schedule_entry: schedule_entry['time'])
 		return result[:max_amount]
+	def __lt__(self, other):
+		return (self.name and other.name) and (self.name < other.name) or (id(self) < id(other))
 
 class CustomBusStopCluster(BusStopCluster):
 	def __init__(self, *, name, stops):
@@ -232,6 +235,7 @@
 		from urllib.request import quote
 		return 'custom?stops=' + ';'.join(stop.code for stop in self.stops) + '&name=' + quote(self.name)
 
+from collections import defaultdict
 routes = {}
 routes_per_id = {}
 all_trips = {}
@@ -241,6 +245,7 @@
 viimeinen_käyttöpäivä = None
 clusters_by_name = {}
 services_for_day = {}
+shapes = defaultdict(list)
 
 def load_buses(gtfs_zip_path):
 	global viimeinen_käyttöpäivä
@@ -274,6 +279,7 @@
 		try:
 			with gtfs_zip.open('shapes.txt') as file:
 				for row in read_csv(map(bytes.decode, file)):
+					list.append(shapes[row['shape_id']], (row['shape_pt_lat'], row['shape_pt_lon']))
 					shape_distances[row['shape_id']] = max(shape_distances.get(row['shape_id'], 0), float(row['shape_dist_traveled']))
 		except KeyError:
 			pass
@@ -289,6 +295,7 @@
 					service = services[row['service_id']],
 					length = shape_distances.get(row.get('shape_id'), 1) * float(profile['metrics']['shape-modifier']),
 					block_id = row.get('block_id') or row['service_id'],
+					shape = row.get('shape_id')
 				)
 				route.trips.add(trip)
 				if trip.name in all_trips:
--- a/service.py	Wed Sep 12 08:27:27 2018 +0300
+++ b/service.py	Thu Sep 13 21:32:30 2018 +0300
@@ -790,8 +790,8 @@
 @app.route('/trip/<trip_reference>')
 def trip(trip_reference):
 	from flask import request
-	from buses import all_trips
-	from busroute import simplify_name
+	from buses import all_trips, shapes
+	from busroute import simplify_name,greatly_simplify_name
 	try:
 		trip = all_trips[trip_reference]
 	except KeyError:
@@ -824,8 +824,12 @@
 			'time': formatted_time,
 			'id': halt.stop.reference,
 			'code': halt.stop.code,
+			'ref': halt.stop.code or halt.stop.reference,
 			'name': tr(halt.stop.name, 'bus-stops'),
 			'typename': halt.stop.typename,
+			'arrival_time': time_representation(datetime.combine(today(), time()) + halt.arrival_time),
+			'departure_time': time_representation(datetime.combine(today(), time()) + halt.departure_time),
+			'location': str(halt.stop.location),
 		})
 	sign = trip.concise_schedule()
 	try:
@@ -836,11 +840,20 @@
 		schedule = schedule,
 		trip_reference = trip_reference,
 		route = trip.route.reference,
-		description = ' - '.join(tr(place, 'region_name') for place in sign),
+		#description = ' - '.join(tr(place, 'region_name') for place in sign),
+		description = greatly_simplify_name(sign[-1]),
 		night = is_night_time(datetime.combine(today(), time()) + trip.schedule[-1].arrival_time),
 		tr = tr,
 		length = trip.length / 1000,
 		service = trip.route.service,
+		shape = ','.join(str.format('[{}, {}]', point[0], point[1]) for point in shapes[trip.shape]),
+		stops = list(
+			dict(
+				ref = halt.stop.reference,
+				name = halt.stop.name,
+				position = str.format('[{}]', str(halt.stop.location)),
+			) for halt in trip.schedule
+		),
 	)
 
 @app.route('/route/<names>')
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/templates/custom_cluster.html	Thu Sep 13 21:32:30 2018 +0300
@@ -0,0 +1,1 @@
+make ur damn cluster here
--- a/templates/trip.html	Wed Sep 12 08:27:27 2018 +0300
+++ b/templates/trip.html	Thu Sep 13 21:32:30 2018 +0300
@@ -3,7 +3,18 @@
 	<link rel="icon" type="image/png" href="../static/favicon.png" />
 	<link rel="stylesheet" type="text/css" href="../static/style.css" />
 	<meta charset='UTF-8' />
-	<meta http-equiv='refresh' content='60'>
+	<!--<meta http-equiv='refresh' content='60'>-->
+	<link
+	rel="stylesheet"
+	href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"
+	integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
+	crossorigin=""
+	/>
+	<script
+		src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"
+		integrity="sha512-nMMmRyTVoLYqjP9hrbed9S+FzjZHW5gY1TWCHA5ckwXZBadntCNs8kEqAWdrb9O7rxbCaA4lKTIWjDXZxflOcA=="
+		crossorigin=""
+	></script>
 	<style>
 	.sarake-alue
 	{
@@ -42,6 +53,14 @@
 	{
 		text-align: right;
 	}
+	.bus_stop_ref
+	{
+		padding: 2px;
+		border: 1px solid #888;
+		background-color: #e0e0e0;
+		border-radius: 3px;
+	}
+	#mapid { height: 50vh; }
 	</style>
 	<script>
 	function toggle_fold(id)
@@ -80,6 +99,13 @@
 		</tr>
 	</thead>
 	<tbody>
+	<tr>
+	<td colspan="9100">
+	<div id="mapid"></div>
+	</td>
+	</tr>
+	</tbody>
+	<tbody>
 		{% for entry in schedule %}
 		<tr>
 			<td class='sarake-aika' style='vertical-align: top'>{{entry['time']}}</td>
@@ -99,5 +125,53 @@
 		{% endfor %}
 	</tbody>
 	</table>
+<script>
+function openBusStop(event) {
+	window.open(this.options._my_bus_stop_url);
+}
+var route = [{{shape}}];
+var mymap = L.map('mapid').setView([60.45175, 22.26705], 13);
+var myIcon = L.icon({
+    iconUrl: '/static/favicon.png',
+    iconSize: [16, 16],
+    iconAnchor: [8, 8],
+    popupAnchor: [-3, -76],
+});
+L.tileLayer(
+	'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
+	//'http://tiles.kartat.kapsi.fi/taustakartta/{z}/{x}/{y}.jpg',
+	{
+		attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
+		maxZoom: 18,
+	}
+).addTo(mymap);
+var polyline = L.polyline(route, {
+	color: 'black',
+	dashArray: [3, 5],
+}).addTo(mymap);
+// zoom the map to the polyline
+mymap.fitBounds(polyline.getBounds());
+
+{% for entry in schedule %}
+{% for halt in entry['stops'] %}
+marker = L.circleMarker([{{halt["location"]}}], {
+	radius: 6,
+	color: 'black',
+	fillColor: 'yellow',
+	fillOpacity: 1,
+	title: "{{halt['ref']}} {{halt['name']}}",
+	_my_bus_stop_url: "/stop/{{halt['ref']}}",
+}).addTo(mymap);
+popupmsg = "<h3><a href='/stop/{{halt['ref']}}'><span class='bus_stop_ref'>{{halt['ref']}}</span> {{halt['name']}}</a></h3>";
+	
+{% if halt['arrival_time'] != halt['departure_time'] %}
+	popupmsg += "<p><ul><li>Saapuu: {{halt['arrival_time']}}</li><li>Lähtee: {{halt['departure_time']}}</li></ul></p>";
+{% else %}
+	popupmsg += "<p><ul><li>Pysähtyy: {{halt['arrival_time']}}</li></ul></p>";
+{% endif %}
+marker.bindPopup(popupmsg);
+{% endfor %}
+{% endfor %}
+</script>
 </body>
 </html>

mercurial