-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
1457 lines (1317 loc) · 44.6 KB
/
index.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Initialize map
var map = L.map('map').setView([25.795865,-80.287046], 11);
var debug = false; // Enable console debug messages
var enableRefresh = true;
var showAllLayers = true;
// Load MapBox map
var accessToken = 'pk.eyJ1IjoicXRyYW5kZXYiLCJhIjoiSDF2cGNjZyJ9.D1ybOKe77AQDPHkxCCEpJQ';
var osmLayer = L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=' + accessToken, {
maxZoom: 20,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>'
});
osmLayer.addTo(map);
// Set up Google Maps layers
var googleRoadmap = new L.Google('ROADMAP', { maxZoom: 20 });
var googleHybrid = new L.Google('HYBRID', { maxZoom: 20 });
var googleTraffic = new L.GoogleTraffic('ROADMAP', { maxZoom: 20 });
// Add Control Panel
addControlPane();
// Set up layers to allow user to control map display
var busLayer = new L.LayerGroup();
var busStopsLayer = new L.LayerGroup();
var metroRailLayer = new L.LayerGroup();
var poiLayer = new L.LayerGroup();
var trolleyLayer = new L.LayerGroup();
var trolleyStopsLayer = new L.LayerGroup();
var bikeLayer = new L.LayerGroup();
var nearbyLayer = new L.LayerGroup();
var doralTrolleyLayer = new L.LayerGroup();
var miamiBeachTrolleyLayer = new L.LayerGroup();
//var miamiTransitAPILayer = new L.LayerGroup();
L.control.layers({'Open Street Map':osmLayer, 'Google Maps':googleRoadmap, 'Google Maps Satellite':googleHybrid, 'Google Maps Traffic':googleTraffic},{
'Miami-Dade Transit Live Buses': busLayer,
'Miami-Dade Transit Bus Stops': busStopsLayer,
'Miami-Dade Transit Metro Rail': metroRailLayer,
'Points of Interest': poiLayer,
'Miami Trolleys': trolleyLayer,
'Miami Trolley Stops': trolleyStopsLayer,
'Miami Beach Trolleys': miamiBeachTrolleyLayer,
'Doral Trolleys': doralTrolleyLayer,
'Citi Bikes': bikeLayer,
//'Miami Transit API Bus GPS': miamiTransitAPILayer
}).addTo(map);
// Add certain layers as default to be shown
busLayer.addTo(map);
metroRailLayer.addTo(map);
trolleyLayer.addTo(map);
doralTrolleyLayer.addTo(map);
miamiBeachTrolleyLayer.addTo(map);
//miamiTransitAPILayer.addTo(map);
//poiLayer.addTo(map);
bikeLayer.addTo(map);
//nearbyLayer.addTo(map);
// Button to allow user to locate current position
L.control.locate({ locateOptions: { maxZoom: 15 }}).addTo(map);
// Button to allow map to be full-screen
L.control.fullscreen().addTo(map);
// FontAwesome prefix
L.AwesomeMarkers.Icon.prototype.options.prefix = 'fa';
var defaultIconSize = [27, 35];
var defaultIconAnchor = [14, 32];
// Initialize bus icon
var busIcon = L.AwesomeMarkers.icon({
icon: 'bus',
markerColor: 'cadetblue',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Initialize blue bus icon
var busIconBlue = L.AwesomeMarkers.icon({
icon: 'bus',
markerColor: 'blue',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Initialize aqua bus icon
var busIconAqua = L.AwesomeMarkers.icon({
icon: 'bus',
markerColor: 'cadetblue',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Initialize gray bus icon
var busIconGray = L.AwesomeMarkers.icon({
icon: 'bus',
markerColor: 'gray',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Initialize bus stop icon
var busStopIcon = L.AwesomeMarkers.icon({
icon: 'circle',
iconColor: '#333',
markerColor: 'transparent',
iconAnchor: [17, 12],
shadowSize: [0, 0]
});
// Initialize Metrorail icon
var metroRailIcon = L.AwesomeMarkers.icon({
icon: 'train',
markerColor: 'purple',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Initialize Metrorail station icon
var metroRailStationIcon = L.AwesomeMarkers.icon({
icon: 'circle',
iconColor: '#7100ab',
markerColor: 'transparent',
iconAnchor: [17, 12],
shadowSize: [0, 0]
});
// Trolley icon
var trolleyIcon = L.AwesomeMarkers.icon({
icon: 'subway',
markerColor: 'blue',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Doral trolley icon
var doralTrolleyIcon = L.AwesomeMarkers.icon({
icon: 'subway',
markerColor: 'orange',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Miami Beach trolley icon
var miamiBeachTrolleyIcon = L.AwesomeMarkers.icon({
icon: 'subway',
markerColor: 'green',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// Trolley stop icon
var trolleyStopIcon = L.AwesomeMarkers.icon({
icon: 'circle',
iconColor: '#666',
markerColor: 'transparent',
iconAnchor: [17, 12],
shadowSize: [0, 0]
});
// Doral trolley route icon
var TSOTrolleyrouteIcon = L.AwesomeMarkers.icon({
icon: 'circle',
iconColor: '#666',
markerColor: 'transparent',
shadowSize: [0, 0],
iconAnchor: [17, 12]
});
// Citi bike icon
var bikeIcon = L.AwesomeMarkers.icon({
icon: 'bicycle',
markerColor: 'blue',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
// POI icon
var poiIcon = L.AwesomeMarkers.icon({
icon: 'map-pin',
markerColor: 'orange',
iconSize: defaultIconSize,
iconAnchor: defaultIconAnchor
});
//iconColor:
//spin:true
// Keep track of each route ID, trip ID and its shape ID, and color of the route.
var tripRouteShapeRef = []; // Format is {tripId: "", routeId: "", shapeId: "", color: ""}
// Track which shape ID and the corresponding has already been displayed
var displayedShapeIds = [];
// Track all routes and their directions
var routeDirections = []; // Format is {routeId: "", "direction"}
// Track bus stops of each route-direction that has already been displayed
var displayedBusStops = [];
// Keep track of scope to refresh the page after data is received
var scope;
// Hold bus routes in array map to zoom when selecting route in bus stops table
var polylineMapping = [];
// Hold POIs in array map to allow zoom to a specifc POI
var poiMapping = [];
// Hold buses in array map to allow zoom to a specific bus
var busMapping = [];
// Cache nearby markers to remove later
var nearbyCache = [];
// Track the city to receive trolley information
var cityTrolley = "";
// Refresh time for Miami Transit API
var refreshTime = 5000;
// Cache old locations of buses to display history
var refreshDisplayCache = [];
refreshDisplayCache.Buses = [];
refreshDisplayCache.BusGPS = [];
// Cache markers
var cachedMarkers = [];
var cachedBusGPSMarkers = [];
var cachedMetroRailMarkers = [];
var cachedMDTBusMarkers = [];
var cachedMiamiTrolleyMarkers = [];
var cachedDoralTrolleyMarkers = [];
var cachedMiamiBeachTrolleyMarkers = [];
var fakePositionOffset = 0.0;
// Base URL for API server
var apiURL = 'https://miami-transit-api.herokuapp.com/';
init();
function init() {
angular.module('transitApp', []).controller('transitController', ['$scope', function($scope) {
scope = $scope;
$scope.tripRouteShapeRef = tripRouteShapeRef;
$scope.refreshTime = refreshTime;
}
]);
$.getJSON(apiURL + 'api/Buses.json',
function(data) {
$("#wait").hide();
var records = data.RecordSet;
loadBusData(records);
});
}
function loadBusData(data) {
if (data !== null) generateBusList(data.Record, "REAL-TIME");
loadRouteColors(); // Bus list must be loaded first
//displayRoutesFromTripId(tripRouteShapeRef); // Bus list must be loaded first to have the trip IDs
showPOIs();
getTrolleyData(scope);
loadTrolleyRoutes();
getTrolleyStops(scope);
getCitiBikes();
addDoralTrolleys();
addDoralTrolleyRoutes();
addMetroRail();
addMetroRailRoutes();
addMetroRailStations();
addMiamiBeachTrolleys();
addMiamiBeachTrolleyRoutes();
// Refresh Miami Transit API data every 5 seconds
setInterval(function() {
if (enableRefresh) callMiamiTransitAPI();
}, refreshTime);
}
function callMiamiTransitAPI() {
//loadBusTrackingGPSData();
//loadMiamiTransitAPIBuses();
addMetroRail();
refreshMDTBuses();
refreshMiamiTrolleys();
addDoralTrolleys();
addMiamiBeachTrolleys();
}
function generateBusList(data, realText) {
var i = 0;
var uniqueBusRoutes = [];
for (i = 0; i < data.length; i++) {
// Add each bus to the map
addBusMarker(
busLayer,
data[i].Latitude,
data[i].Longitude,
data[i].BusName,
data[i].TripHeadsign,
data[i].BusID,
data[i].LocationUpdated,
realText
);
// Add to the global trip-route-shape list
tripRouteShapeRef[tripRouteShapeRef.length] = {
tripId: data[i].TripID,
routeId: data[i].RouteID,
shapeId: ""
};
addRouteDirection(data[i].RouteID,data[i].ServiceDirection);
// Filter out unique buses to display in bus stops table dropdown
var routeId = data[i].RouteID;
var serviceDirection = data[i].ServiceDirection;
var unique = true;
if (uniqueBusRoutes.length > 0) {
var j =0;
for (j = 0; j < uniqueBusRoutes.length; j++) {
if ((uniqueBusRoutes[j].RouteID === routeId) && (uniqueBusRoutes[j].ServiceDirection === serviceDirection)) {
// Found duplicate, don't add
unique = false;
break;
}
}
}
if (unique) {
uniqueBusRoutes.push({
RouteID : routeId,
ServiceDirection : serviceDirection
});
}
}
scope.buses = data;
scope.uniqueBusRoutes = uniqueBusRoutes;
scope.$apply();
}
function addRouteDirection(route, serviceDirection) {
if (routeDirections.length > 0) {
if (debug) console.log("routeDirections.length = "+routeDirections.length);
var allowAdd = true;
var i = 0;
for (i = 0; i < routeDirections.length; i++) {
if ((routeDirections[i].routeId == route) && (routeDirections[i].direction == serviceDirection)) {
allowAdd = false;
break;
}
}
if (allowAdd) {
routeDirections[routeDirections.length] = {routeId: route, direction: serviceDirection}; // Add if not a duplicate
if (debug) console.log("Added route: "+route+" and direction: "+serviceDirection);
}
} else {
routeDirections[0] = {routeId: route, direction: serviceDirection};
scope.routeDir = route+' '+serviceDirection; // Set the first bus stop route-direction to show
if (debug) console.log("Added route: "+route+" and direction: "+serviceDirection);
}
}
function loadRouteColors() {
$.getJSON(apiURL + 'api/BusRoutes.json',
function(data) {
var records = data.RecordSet.Record;
scope.routes = records;
var i = 0;
for (i = 0; i < records.length; i++) {
// Add to global ref list
// Data format is {tripId: "", routeId: "", shapeId: "", color: ""}
var route = records[i].RouteID;
for (j = 0; j < tripRouteShapeRef.length; j++) {
if (tripRouteShapeRef[j].routeId == route) {
tripRouteShapeRef[j].color = records[i].RouteColor;
}
}
}
scope.$apply();
});
}
function addBusMarker(layer, lat, lon, name, desc, id, time, realText) {
var marker = L.marker([lat, lon], {icon: busIcon}).bindPopup(
realText+' ('+name+') Bus # '+desc+
' (ID: '+id+') <br /> Location Updated: '+time,
{ offset: new L.Point(0, 0) });
marker.addTo(layer);
busMapping[id] = marker;
cachedMDTBusMarkers[id] = marker;
}
function displayRoutesFromTripId(tripRefs) {
if (debug) console.log("Trip refs length = "+tripRefs.length);
var i = 0;
for (i = 0; i < tripRefs.length; i++) {
// Send the request to get the shape ID for each trip ID
$.getJSON(apiURL + 'api/BusRouteShapesByTrip.json?TripID='+tripRefs[i].tripId,
(function(thistripId) {
return function(data) {
var records = data.RecordSet.Record;
var shapeId = records.ShapeID;
var routeId;
// Add shape ID into global trip reference list
// Data format is {tripId: "", routeId: "", shapeId: "", color: ""}
for (i = 0; i < tripRouteShapeRef.length; i++) {
if (tripRouteShapeRef[i].tripId == thistripId) {
tripRouteShapeRef[i].shapeId = shapeId;
routeId = tripRouteShapeRef[i].routeId;
break; // Can break since a separate request is sent for each trip ID
}
}
displayFromShapeId(shapeId, routeId);
};
}(tripRefs[i].tripId))
);
}
}
// Retrieve lat/long list for each route's shape ID
function displayFromShapeId(shapeId, routeId) {
$.getJSON(apiURL + 'api/BusRouteShape.json?ShapeID='+shapeId,
function(data) {
// Find the color for the route
var color = "";
var records = data.RecordSet.Record;
for (i = 0; i < tripRouteShapeRef.length; i++) {
if (tripRouteShapeRef[i].shapeId == shapeId) {
color = tripRouteShapeRef[i].color;
break;
}
}
if (displayedShapeIds.length === 0) { // Display the first shape ID
addRoutePoints(busLayer, '#'+color, records, routeId);
addDisplayedShapeId(shapeId);
} else { // Check for any duplicate shape ID and not display
for (var displayed in displayedShapeIds) {
if (displayed == shapeId) break;
addRoutePoints(busLayer, '#'+color, records, routeId);
addDisplayedShapeId(shapeId);
break;
}
}
});
}
// Add all the route lines and colors to the map for each shape point list
function addRoutePoints(layer, routeColor, records, routeId) {
var latlngs = [];
for (i = 0; i < records.length; i++) {
latlngs[latlngs.length] = (L.latLng(records[i].Latitude, records[i].Longitude));
}
var markerLine = L.polyline(latlngs, {color: routeColor});
markerLine.addTo(layer);
polylineMapping[routeId] = markerLine;
}
// Track which shape ID has already been displayed
function addDisplayedShapeId(shapeId) {
displayedShapeIds[displayedShapeIds.length] = shapeId;
requestBusStops(shapeId);
}
function requestBusStops(shapeId) {
if (debug) console.log("Requesting bus stops for "+shapeId);
if (debug) console.log("tripRouteShapeRef length = "+tripRouteShapeRef.length);
var i = 0;
for (i = 0; i < tripRouteShapeRef.length; i++) {
//if (debug) console.log("Inspecting item shape ID: "+tripRouteShapeRef[i].shapeId+" trip ID: "+tripRouteShapeRef[i].tripId);
if (shapeId == tripRouteShapeRef[i].shapeId) {
if (debug) console.log("Shape ID matched tripRouteShapeRef "+shapeId+" at index "+i+" of "+tripRouteShapeRef.length);
if (debug) console.log("routeDirections.length = "+routeDirections.length);
var j = 0;
for (j = 0; j < routeDirections.length; j++) {
var route = routeDirections[j].routeId;
if (debug) console.log("Comparing routeDirections list route "+route+" against trip Ref list route: "+tripRouteShapeRef[i].routeId);
if (route === tripRouteShapeRef[i].routeId) {
if (debug) console.log("Route ID found "+route+ " at index "+j+" of "+routeDirections.length);
sendBusStopRequest(route, routeDirections[j].direction);
// break; Keep looking for Eastbound/Southbound and Clockwise/CntrClockwise
}
}
break;
}
}
}
function sendBusStopRequest(route, direction) {
// Ignore requested routes and directions
if (displayedBusStops.indexOf(route+""+direction) > -1) {
if (debug) console.log("Ignore "+route+" "+direction+" since it has already been requested.");
return;
}
displayedBusStops[displayedBusStops.length] = route+""+direction;
$.getJSON(apiURL + 'api/BusRouteStops.json?RouteID='+route+'&Dir='+direction,
function(data) {
var records = data.RecordSet.Record;
if (!scope.busStops) scope.busStops = [];
scope.busStops[route+" "+direction] = records;
scope.$apply();
var i = 0;
for (i = 0; i < records.length; i++) {
addBusStopMarker(
busStopsLayer,
records[i].Latitude,
records[i].Longitude,
records[i].StopName,
route
);
}
});
}
function addBusStopMarker(layer, lat, lon, name, route) {
// var marker = L.circleMarker(L.latLng(lat, lon), {color: 'green', radius: 8}).bindPopup(
// 'Route: '+route+' Bus Stop: '+name,
// { offset: new L.Point(0, 0) });
var marker = L.marker([lat, lon], {icon: busStopIcon, zIndexOffset: -100}).bindPopup(
'Route: '+route+' Bus Stop: '+name,
{ offset: new L.Point(0, 0) });
marker.addTo(layer);
}
function showPOIs() {
$.getJSON(apiURL + 'api/PointsOfInterest.json',
function(data) {
var records = data.RecordSet.Record;
scope.POIs = records;
scope.$apply();
var i = 0;
for (i = 0; i < records.length; i++) {
var address =
records[i].Address + '<br>' +
records[i].City + ', ' +
records[i].State + ' ' +
records[i].Zip;
addPOIMarker(
poiLayer,
records[i].Latitude,
records[i].Longitude,
records[i].PointName,
records[i].PointID,
records[i].CategoryID,
records[i].CategoryName,
address
);
}
});
}
function addPOIMarker(layer, lat, lon, name, poiId, catId, catName, address) {
//var poiIcon = L.icon({
// iconUrl: 'icons/icon-POI-'+catId+'.png',
// iconSize: [33, 33], // Normal size is 44x44
// iconAnchor: [16, 33]
//});
var marker = L.marker([lat, lon], {icon: poiIcon, zIndexOffset: -1000}).bindPopup(
'<strong>' + catName + '</strong><br><br>' + name + '<br>' + address,
{ offset: new L.Point(0, -16) });
layer.addLayer(marker);
poiMapping[poiId] = marker;
}
function getTrolleyData(scope) {
$.getJSON( apiURL + 'api/trolley/vehicles.json',
function(data) {
var trolleys = data.get_vehicles;
var count = trolleys.length;
for (i = 0; i < count; i++) {
trolleys[i].receiveTime = (new Date(trolleys[i].receiveTime)).toLocaleString();
addTrolleyMarker(
trolleyLayer,
trolleys[i].lat,
trolleys[i].lng,
trolleys[i].equipmentID,
trolleys[i].routeID,
trolleys[i].receiveTime
);
}
scope.trolleys = trolleys;
});
}
function addTrolleyMarker(layer, lat, lng, equipmentID, routeID, receiveTime) {
var marker = L.marker([lat, lng], {icon: trolleyIcon}).bindPopup(
'Trolley # '+equipmentID+
'<br />Route: '+routeID+
'<br />Received Time: '+receiveTime,
{ offset: new L.Point(0, 0) });
marker.addTo(layer);
cachedMiamiTrolleyMarkers[equipmentID] = marker;
}
function loadTrolleyRoutes() {
$.getJSON('routeCoords.json',
function(data) {
var i = 1;
for (i = 1; i < 8; i++) {
var color = data[i].color.normal;
displayTrolleyRouteColors(trolleyLayer, color, data[i].coords);
}
});
}
function displayTrolleyRouteColors(layer, color, coords) {
var latlngs = [];
for (i = 0; i < coords.length; i++) {
latlngs.push(L.latLng(coords[i][1], coords[i][0]));
}
var lineMarker = L.polyline(latlngs, {color: '#'+color});
lineMarker.addTo(layer);
}
function getTrolleyStops(scope) {
$.getJSON( apiURL + 'api/trolley/stops.json',
function(data) {
var stops = data.get_stops;
var count = stops.length;
for (i = 0; i < count; i++) {
addTrolleyStopMarker(
trolleyStopsLayer,
stops[i].lat,
stops[i].lng,
stops[i].name,
stops[i].id
);
}
scope.stops = stops;
});
}
function addTrolleyStopMarker(layer, lat, lon, name, id) {
var marker = L.marker([lat, lon], {icon: trolleyStopIcon, zIndexOffset: -110}).bindPopup(
'Stop ID: '+id+'<br />Stop Name: '+name,
{ offset: new L.Point(0, 0) });
marker.addTo(layer);
}
function routeChanged(rd) {
scope.routeDir = rd;
scope.$apply();
var routeId = rd.split(" ")[0];
focusRoute(routeId);
}
function focusPOI(poiIdLatLng) {
map.addLayer(poiLayer);
map.addLayer(nearbyLayer);
var array = poiIdLatLng.split(",");
var poiId = array[0];
var lat = array[1];
var lng = array[2];
map.fitBounds(L.latLngBounds([poiMapping[poiId].getLatLng()]));
poiMapping[poiId].openPopup();
$('.navbar-nav a[href="#mapWrapper"]').tab('show');
getNearBy(poiId,lat,lng);
}
function focusRoute(routeId) {
if (polylineMapping[routeId]) {
map.addLayer(busLayer);
$('.navbar-nav a[href="#mapWrapper"]').tab('show');
setTimeout(function() {
map.fitBounds(polylineMapping[routeId].getBounds());
polylineMapping[routeId].setStyle({
opacity: 1.0,
weight: 10
});
}, 2000);
} else {
alert("Please request the bus routes/stops on the map first and also confirm it exists!");
}
}
function focusBus(busId) {
map.addLayer(busLayer);
map.fitBounds(L.latLngBounds([busMapping[busId].getLatLng()]));
busMapping[busId].openPopup();
$('.navbar-nav a[href="#mapWrapper"]').tab('show');
}
function getCitiBikes() {
var source = "http://citibikemiami.com/downtown-miami-locations.xml";
$.getJSON(
'http://www.whateverorigin.org/get?url='+source+'&callback=?',
(function(thisScope) {
return function(data) {
var xmlDoc = $.parseXML(data.contents);
$xml = $( xmlDoc );
$Id = $xml.find("Id");
$Address = $xml.find("Address");
$Distance = $xml.find("Distance");
$Latitude = $xml.find("Latitude");
$Longitude = $xml.find("Longitude");
$Bikes = $xml.find("Bikes");
$Dockings = $xml.find("Dockings");
var i = 0;
for (i = 0; i < $Id.length; i++) {
addBikeMarker(
bikeLayer,
$Latitude[i].textContent,
$Longitude[i].textContent,
$Id[i].textContent,
$Address[i].textContent,
$Bikes[i].textContent,
$Dockings[i].textContent
);
}
};
}(scope))
);
}
function addBikeMarker(layer, lat, lng, id, address, bikes, dockings) {
var marker = L.marker([lat, lng], {icon: bikeIcon, zIndexOffset: -500}).bindPopup(
'<strong>Citi Bike Station ID: ' + id + '</strong><br><br>Address: ' + address + '<br>Bikes: ' + bikes + '<br>Dockings: ' + dockings,
{ offset: new L.Point(0, -21) });
layer.addLayer(marker);
}
function getNearBy(poiId, lat, lng) {
if (nearbyCache.length > 0) {
for (i = 0; i < nearbyCache.length; i++) {
map.removeLayer(nearbyCache[i]);
}
}
$.getJSON(apiURL + 'api/Nearby.json?Lat='+lat+'&Long='+lng,
function(data) {
var records = data.RecordSet.Record;
nearbyCache = [];
var bounds = [];
for (i = 0; i < records.length; i++) {
addNearByMarker(
nearbyLayer,
records[i].NearbyID,
records[i].NearbyName,
records[i].NearbyType,
records[i].Descr,
records[i].Distance,
records[i].Latitude,
records[i].Longitude,
lat,
lng
);
bounds[i] = [records[i].Latitude,records[i].Longitude];
}
map.fitBounds(bounds);
}
);
}
function addNearByMarker(layer, NearbyID, NearbyName, NearbyType, Descr, Distance, Latitude, Longitude, sourceLat, sourceLng) {
var marker = L.marker([Latitude, Longitude], {icon: poiIcon, zIndexOffset: 10}).bindPopup(
'<strong>'+NearbyType+'</strong><br /><br />'+
'Name: '+NearbyName+
'<br />Description: '+Descr+
'<br />Distance: <strong>'+Distance+'</strong>'+
'<br />Nearby ID: '+NearbyID,
{ offset: new L.Point(0, -22) });
marker.on('mouseover', function (e) {
this.openPopup();
});
marker.addTo(layer);
nearbyCache.push(marker);
var latlngs = [L.latLng(Latitude, Longitude), L.latLng(sourceLat, sourceLng)];
var markerLine = L.polyline(latlngs, {color: 'aqua'});
markerLine.addTo(layer);
nearbyCache.push(markerLine);
}
function addDoralTrolleys() {
var api = 'http://rest.tsoapi.com/';
var controller = 'MappingController';
var methodName = 'GetUnitFromRouteAntibunching';
var data = [];
var doraltkn = '582EB861-9C13-4C89-B491-15F0AFBF9F47';
data[0] = { tkn: doraltkn, geofencesid: '35929', lan: 'en' };
data[1] = { tkn: doraltkn, geofencesid: '36257', lan: 'en' };
data[2] = { tkn: doraltkn, geofencesid: '36270', lan: 'en' };
sendTSOTrolleyRequest(api, controller, methodName, data[0], handleDoralTrolleyCallback);
sendTSOTrolleyRequest(api, controller, methodName, data[1], handleDoralTrolleyCallback);
sendTSOTrolleyRequest(api, controller, methodName, data[2], handleDoralTrolleyCallback);
}
function sendTSOTrolleyRequest(api, controller, methodName, data, callback) {
$.ajax({
url: api + "/" + controller + "/" + methodName,
data: data,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (data, textStatus) {
//console.log(data);
callback(data);
},
error: function (xhr, status, errorThrown) {
console.log(xhr.statusText);
}
});
}
function handleDoralTrolleyCallback(data) {
var obj = jQuery.parseJSON(data);
var trolleys = obj.Units;
var i = 0;
for (i = 0; i < trolleys.length; i++) {
addDoralTrolleyMarker(
doralTrolleyLayer,
trolleys[i].MarkerID,
trolleys[i].MarkerName,
trolleys[i].Latitude,
trolleys[i].Longitude,
trolleys[i].Direction,
trolleys[i].Heading
);
}
}
function addDoralTrolleyMarker(layer, MarkerID, MarkerName, Latitude, Longitude, Direction, Heading) {
if (cachedDoralTrolleyMarkers[MarkerID] !== undefined) {
var currentMarker = cachedDoralTrolleyMarkers[MarkerID];
currentMarker.setLatLng(L.latLng(Latitude, Longitude));
flashMarker(layer, currentMarker);
return;
}
var marker = L.marker([Latitude, Longitude], {icon: doralTrolleyIcon, zIndexOffset: 100}).bindPopup(
'<strong>Doral Trolley ' + MarkerName + '</strong><br><br>ID: ' + MarkerID + '<br>Direction: ' + Direction,
{ offset: new L.Point(0, -22) });
layer.addLayer(marker);
cachedDoralTrolleyMarkers[MarkerID] = marker;
}
function addMiamiBeachTrolleyRoutes() {
// Add delay since there's a sharing bug with Doral route-getting code
setTimeout(
function(){
cityTrolley = "Miami Beach";
addTSOTrolleyRoutes('825894C5-2B5F-402D-A055-88F2297AF99A');
}, 2000);
}
function addDoralTrolleyRoutes() {
cityTrolley = "Doral";
addTSOTrolleyRoutes('582EB861-9C13-4C89-B491-15F0AFBF9F47');
}
function addTSOTrolleyRoutes(tkn) {
var api = 'http://rest.tsoapi.com/';
var controller = 'Routes';
var methodName = 'GetRouteFromToken';
var data = { tkn: tkn, routeId: '-1'};
sendTSOTrolleyRequest(api, controller, methodName, data, handleTSORoutesCallback);
}
function handleTSORoutesCallback(data) {
var obj = jQuery.parseJSON(data);
/** Example:
"ID": "662978",
"ContactID": "2047762",
"StopNumber": "3001",
"Street": "7701 Northwest 79th Avenue 7701 Northwest 79th Avenue",
"City": "Miami",
"State": "FL",
"PostalCode": "33166",
"CountryCode": "US",
"Sequence": "1",
"Latitude": "25.843700",
"Longitude": "-80.323900",
"Description": "Palmetto Metrorail Station, Transfers to Route 2, MDT MetroRail Green Line & Route 87",
"RouteId": "36270"
*/
var stops = obj.stops;
/** Example:
"Name": "Doral Transportation",
"MapType": "MAP",
"MapImageURL": "MapImage_CityOfDoral.png",
"RouteId": "35929",
"ShowAutomatically": "True",
"Name1": "Public Doral Route #1",
"LineColor": "#3A77C7",
"RoutePath": "oxj|CnijiNF..."
*/
var routes = obj.routes;
/** Example:
"Id": "166461",
"RouteId": "36257",
"Lat": "25.8443000000",
"Lng": "-80.3237000000",
"Direction": "W ",
"Angle": "-90.000000",
"StopA": "729094",
"StopB": "729095",
"Seq": "0",
"DesignerStopID": "729094",
"OriginalLat": "25.8443000000",
"OriginalLng": "-80.3237000000",
"AudioID": "156"
*/
var points = obj.points;
var layer = doralTrolleyLayer;
if (cityTrolley === "Miami Beach") {
layer = miamiBeachTrolleyLayer;
}
var i = 0;
for (i = 0; i < stops.length; i++) {
addTSOTrolleyRouteStops(layer, stops[i], routes);
}
addTSOTrolleyRouteLines(layer, points, routes);
}
function addTSOTrolleyRouteStops(layer, stop, routes) {
// Match the stop with the route
var routeLineColor;
var routeName;
var i = 0;
for (i = 0; i < routes.length; i++) {
if (stop.RouteId == routes[i].RouteId) {
routeLineColor = routes[i].LineColor;
routeName = routes[i].Name1;
break;
}
}
var marker = L.marker([stop.Latitude, stop.Longitude], {icon: TSOTrolleyrouteIcon, zIndexOffset: -100}).bindPopup(
'<strong>' + cityTrolley + ' Trolley Stop ' + stop.StopNumber + '</strong>' +
'<br><br>' + stop.Description +
'<br><br>' + stop.Street +
'<br>' + stop.City + ', ' + stop.State + ' ' + stop.PostalCode +
'<br><span style="color:'+ routeLineColor +'">Route ID: ' + stop.RouteId + "</span>" +
'<br><span style="color:'+ routeLineColor +'">Route Name: ' + routeName + "</span>" +
'<br>Sequence: ' + stop.Sequence +
'<br>ID: ' + stop.ID +
'<br>ContactID: ' + stop.ContactID,
{ offset: new L.Point(0, 0) });
layer.addLayer(marker);
}
function addTSOTrolleyRouteLines(layer, points, routes) {
// Map the RouteId with the color for easy lookup
var routeColorMap = [];
var i = 0;
for (i = 0; i < routes.length; i++) {
routeColorMap[routes[i].RouteId] = {LineColor: routes[i].LineColor, Points: []};
}
// Separate points for each route
i = 0;
for (i = 0; i < points.length; i++) {
routeColorMap[points[i].RouteId].Points.push(L.latLng(points[i].Lat, points[i].Lng));
}
for (var routeId in routeColorMap) {
var markerLine = L.polyline(routeColorMap[routeId].Points, {color: routeColorMap[routeId].LineColor});
layer.addLayer(markerLine);
}
}
function addMetroRail() {
$.getJSON(apiURL + 'api/Trains.json',
function(data) {
if (data.RecordSet === null) return; // No rail data at night
var records = data.RecordSet.Record;
var i = 0;
for (i = 0; i < records.length; i++) {
addMetroRailMarker(
metroRailLayer,
records[i].Latitude,
records[i].Longitude,
records[i].TrainID,
records[i].LineID,
records[i].Cars,
records[i].Direction,
records[i].ServiceDirection,
records[i].LocationUpdated
);
}
});
}
function addMetroRailMarker(layer, Latitude, Longitude, TrainID, LineID, Cars, Direction, ServiceDirection, LocationUpdated) {
if (cachedMetroRailMarkers[TrainID] !== undefined) {