summaryrefslogtreecommitdiff
path: root/lib/DBInfoscreen/Controller/Map.pm
blob: df749bfb3a36b4792ca4bde17f7bd363dac82ea7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package DBInfoscreen::Controller::Map;
use Mojo::Base 'Mojolicious::Controller';
use Mojo::JSON qw(decode_json);

my $dbf_version = qx{git describe --dirty} || 'experimental';

chomp $dbf_version;

sub get_hafas_polyline {
	my ( $ua, $cache, $trip_id, $line ) = @_;

	my $url
	  = "https://2.db.transport.rest/trips/${trip_id}?lineName=${line}&polyline=true";

	if ( my $content = $cache->thaw($url) ) {
		return $content;
	}

	$ua->request_timeout(2);

	#say $url;
	my $res
	  = $ua->get(
"https://2.db.transport.rest/trips/${trip_id}?lineName=${line}&polyline=true"
		  => { 'User-Agent' => "dbf.finalrewind.org/${dbf_version}" } )->result;
	if ( $res->is_error ) {
		return;
	}

	my $json = decode_json( $res->body );
	my @coordinate_list;

	for my $feature ( @{ $json->{polyline}{features} } ) {
		if ( exists $feature->{geometry}{coordinates} ) {
			push( @coordinate_list, $feature->{geometry}{coordinates} );
		}

		#if ($feature->{type} eq 'Feature') {
		#	say "Feature " . $feature->{properties}{name};
		#}
	}

	my $ret = {
		name      => $json->{line}{name} // '?',
		polyline  => [@coordinate_list],
		stopovers => $json->{stopovers},
	};

	$cache->freeze( $url, $ret );
	return $ret;
}

sub route {
	my ($self)  = @_;
	my $trip_id = $self->stash('tripid');
	my $line_no = $self->stash('lineno');

	my $pl = get_hafas_polyline( $self->ua, $self->app->cache_iris_main,
		$trip_id, $line_no );
	my @polyline = @{ $pl->{polyline} };
	my @line_pairs;
	my @station_coordinates;

	for my $i ( 1 .. $#polyline ) {
		push(
			@line_pairs,
			[
				[ $polyline[ $i - 1 ][1], $polyline[ $i - 1 ][0] ],
				[ $polyline[$i][1],       $polyline[$i][0] ]
			]
		);
	}

	for my $stop ( @{ $pl->{stopovers} // [] } ) {
		push(
			@station_coordinates,
			[
				[
					$stop->{stop}{location}{latitude},
					$stop->{stop}{location}{longitude}
				],
				$stop->{stop}{name}
			]
		);
	}

	$self->render(
		'route_map',
		title           => $pl->{name},
		hide_opts       => 1,
		with_map        => 1,
		polyline_groups => [
			{
				polylines  => \@line_pairs,
				color      => '#00838f',
				opacity    => 0.6,
				fit_bounds => 1,
			}
		],
		station_coordinates => [@station_coordinates],
	);
}

1;