hirebike.page.ts 19 KB
Newer Older
1
import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
Priyanka Upadhye's avatar
Priyanka Upadhye committed
2
3
4

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { RestService } from '../rest.service';
5
import { Observable, Subject } from 'rxjs';
Priyanka Upadhye's avatar
Priyanka Upadhye committed
6
7
8
9
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { ToastService } from '../services/toast.service';
import { Router } from '@angular/router';
10
import { MapDataService } from '../services/map-data.service';
11
12
import { LocationService } from '../services/location.service';
import { LoadingService } from '../services/loading.service';
Priyanka Upadhye's avatar
Priyanka Upadhye committed
13
declare var H: any;
14

Priyanka Upadhye's avatar
Priyanka Upadhye committed
15
16
17
18
19
20
21
22
23
24
25
@Component({
  selector: 'app-hirebike',
  templateUrl: './hirebike.page.html',
  styleUrls: ['./hirebike.page.scss'],
})
export class HirebikePage implements OnInit {

  private platform: any;

  reservedBike: any = {};
  bikeDetails: any = {};
26
27
  address = "sample";
  isBikeHired = false;
Priyanka Upadhye's avatar
Priyanka Upadhye committed
28
29
  noReservation = true;

30
31
  isBikeReserved = true;

32
33
34
35
  currentRoute: any;
  routeSummary: any;
  wayPointsInfo:any;

36
37
  startRideSubject: Subject<any> = new Subject();
  gotReservedBikeSubject: Subject<any> = new Subject();
38
  maneuverList: any = [];
Priyanka Upadhye's avatar
Priyanka Upadhye committed
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  @ViewChild("mapElement", { static: false })
  public mapElement: ElementRef;

  private map: any;
  private ui: any;
  private defaultLayers: any;
  private locationsGroup: any;

  private currentUserPosition = { lat: 48.783480, lng: 9.180319 };
  private bikePosition = { lat: 48.783480, lng: 9.180319 };
  private destinationPosition = { lat: 48.783480, lng: 9.180319 };

  public currentLocationMarker: any;
  public destinationMarker: any;

  public rideStarted = false;

Priyanka Upadhye's avatar
Priyanka Upadhye committed
57
58
59
60
61
  constructor(private geolocation: Geolocation,
    public restService: RestService,
    public httpClient: HttpClient,
    private storage: Storage,
    private toastService: ToastService,
62
    private router: Router,
63
64
65
66
    private mapDataService: MapDataService,
    public locationService: LocationService,
    public loadingService: LoadingService) {
      
67
68
69
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
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
  }

  ngOnInit() {
    
  }

  ngAfterViewInit() {
    window.addEventListener('resize', () => this.map.getViewPort().resize());
  }

  ionViewWillEnter() {
    this.currentUserPosition.lat = this.locationService.currentUserPosition.lat;
    this.currentUserPosition.lng = this.locationService.currentUserPosition.lng;

    this.initializeMap();

    //get user location
    if (this.currentLocationMarker) {
      this.currentLocationMarker.setGeometry({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng })
    } else {
      this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
    }

    this.locationService.liveLocationSubject.subscribe((position) => {
      console.log('got location inside home subscription');
      this.currentUserPosition.lat = position.lat;
      this.currentUserPosition.lng = position.lng;
      if (this.currentLocationMarker) {
        this.currentLocationMarker.setGeometry({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng })
      } else {
        this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
      }
    });
    this.getReservedBike();

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    this.mapDataService.mapDataSubject.subscribe(receiveddata => {
      console.log('data received ');
      console.log(receiveddata);
      this.currentRoute = receiveddata;
      let content = '';
      content += 'Total distance: ' + receiveddata.summary.distance + 'm. ';
      content += 'Travel Time: ' + Math.floor(receiveddata.summary.travelTime / 60) + ' minutes ' + (receiveddata.summary.travelTime % 60) + ' seconds.' + ' (in current traffic)';
      this.routeSummary = content;
      this.showRouteInfoPanel(receiveddata);
      let waypointLabels = [];
      for (let i = 0; i < receiveddata.waypoint.length; i += 1) {
        waypointLabels.push(receiveddata.waypoint[i].label)
      }
      this.wayPointsInfo = waypointLabels.join(' - ');
    });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    this.gotReservedBikeSubject.subscribe(bikeDetails => {
      console.log('Got Bike in map');
      console.log(bikeDetails);
      this.bikePosition.lat = bikeDetails.lat;
      this.bikePosition.lng = bikeDetails.lon;
      var img = ['../../../assets/images/100_percent.png', '../../../assets/images/75_percent.png', '../../../assets/images/50_percent.png', '../../../assets/images/25_percent.png', '../../../assets/images/0_percent.png'];
      if (bikeDetails.batteryPercentage < 100 && bikeDetails.batteryPercentage >= 75) {
        this.addMarker(Number(bikeDetails.lat), Number(bikeDetails.lon), img[0]);
      }
      else if (bikeDetails.batteryPercentage < 75 && bikeDetails.batteryPercentage >= 50) {
        this.addMarker(Number(bikeDetails.lat), Number(bikeDetails.lon), img[1]);
      }
      else if (bikeDetails.batteryPercentage < 50 && bikeDetails.batteryPercentage >= 25) {
        this.addMarker(Number(bikeDetails.lat), Number(bikeDetails.lon), img[2]);
      } else if (bikeDetails.batteryPercentage < 25 && bikeDetails.batteryPercentage >= 0) {
        this.addMarker(Number(bikeDetails.lat), Number(bikeDetails.lon), img[3]);
      }
Priyanka Upadhye's avatar
Priyanka Upadhye committed
138

139
140
      this.setZoomLevelToPointersGroup();
    });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
141

142
143
144
145
146
147
    this.startRideSubject.subscribe(event => {
      console.log('start ride');
      //remove event listener
      this.rideStarted = true;
      this.calculateRoute();
    });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
148
149
  }

150
151
152
153
154
155
156
157
158
159
160
161
162
163
  showRouteInfoPanel(route) {
    // Add a marker for each maneuver
    let maneuverList = [];
    for (let i = 0; i < route.leg.length; i += 1) {
      for (let j = 0; j < route.leg[i].maneuver.length; j += 1) {
        // Get the next maneuver.
        let maneuver = route.leg[i].maneuver[j];
        maneuverList.push(maneuver);
      }
    }

    this.maneuverList = maneuverList;
  }

Priyanka Upadhye's avatar
Priyanka Upadhye committed
164
  getReservedBike() {
165
    this.loadingService.showLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
166
167
168
169
170
171
172
173
174
    this.storage.get('token').then((token) => {
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
      //call reserved bike api
      let reserveUrl = 'http://193.196.52.237:8081/active-rent';
      let bikeReservationStatusApi = this.httpClient.get(reserveUrl, { headers });
      bikeReservationStatusApi.subscribe((resp: any) => {
        console.log('Reserved Bike', resp);
        if (resp.data) {
          this.reservedBike = resp.data;
175
          this.isBikeHired = this.reservedBike.rented;
Priyanka Upadhye's avatar
Priyanka Upadhye committed
176
177
178
179
180
181
182
          //Call Bike Details api
          let bikeDetailsUrl = 'http://193.196.52.237:8081/bikes/' + this.reservedBike.bikeId;
          let bikeDetailsApi = this.httpClient.get(bikeDetailsUrl, { headers });
          bikeDetailsApi.subscribe((resp: any) => {
            console.log('Bike Details', resp);
            this.bikeDetails = resp.data;
            this.noReservation = false;
183
            this.reverseGeocode(this.platform, this.bikeDetails.lat, this.bikeDetails.lon);
184
            this.isBikeReserved = true;
185

186
187
            //pass reserved bike subject here map
            this.gotReservedBikeSubject.next(resp.data);
188
            this.loadingService.hideLoader();
189
190
          }, (reservedBikeError) => {
            console.log(reservedBikeError);
191
192
            this.loadingService.hideLoader();
            this.isBikeReserved = false;
193
          });
194
195
196
        } else {
          this.loadingService.hideLoader();
          this.isBikeReserved = false;
Priyanka Upadhye's avatar
Priyanka Upadhye committed
197
        }
198
199
      }, (bikeDetailsError) => {
        console.log(bikeDetailsError);
200
201
        this.loadingService.hideLoader();
        this.isBikeReserved = false;
202
      });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
203
204
205
    });
  }

gap95's avatar
gap95 committed
206
  startTrip() {
207
208
209
    this.isBikeHired = true;
    this.startRideSubject.next('some value');
    this.loadingService.showLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
210
    this.storage.get('token').then((token) => {
Priyanka Upadhye's avatar
Priyanka Upadhye committed
211
      let url = 'http://193.196.52.237:8081/rent' + '?bikeId=' + this.bikeDetails.id;
Priyanka Upadhye's avatar
Priyanka Upadhye committed
212
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
Priyanka Upadhye's avatar
Priyanka Upadhye committed
213
      let bikeApi = this.httpClient.get(url, { headers });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
214
      bikeApi.subscribe((resp) => {
Priyanka Upadhye's avatar
Priyanka Upadhye committed
215
        console.log('my data: ', resp);
216
        this.loadingService.hideLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
217
        this.toastService.showToast("Trip Started");
218
        this.isBikeHired = true;
Priyanka Upadhye's avatar
Priyanka Upadhye committed
219
      }, (error) => {
220
        console.log(error);
221
        this.loadingService.hideLoader();
222
        this.toastService.showToast("This is ongoing Trip");
Priyanka Upadhye's avatar
Priyanka Upadhye committed
223
      });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
224
    });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
225

Priyanka Upadhye's avatar
Priyanka Upadhye committed
226
227
  }

gap95's avatar
gap95 committed
228
  startTrip1() {
229
230
231
    this.isBikeHired = true;
    this.startRideSubject.next('some value');
  }
Priyanka Upadhye's avatar
Priyanka Upadhye committed
232

233
  CancelTrip() {
234
    this.loadingService.showLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
235
236
237
238
239
240
    this.storage.get('token').then((token) => {
      let url = 'http://193.196.52.237:8081/rent' + '?bikeId=' + this.bikeDetails.id;
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
      let bikeApi = this.httpClient.delete(url, { headers });
      bikeApi.subscribe((resp) => {
        console.log('my data: ', resp);
241
        this.loadingService.hideLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
242
243
        this.toastService.showToast("Trip Ended!");
      }, (error) => {
244
        console.log(error);
245
        this.loadingService.hideLoader();
Priyanka Upadhye's avatar
Priyanka Upadhye committed
246
        this.toastService.showToast("No Ongong Trip to End")
Priyanka Upadhye's avatar
Priyanka Upadhye committed
247
248
      });
    });
Priyanka Upadhye's avatar
Priyanka Upadhye committed
249
  }
250
251
252
253
254

  ngOnDestroy() {
    // needed if child gets re-created (eg on some model changes)
    // note that subsequent subscriptions on the same subject will fail
    // so the parent has to re-create parentSubject on changes
255
    //this.startRideSubject.unsubscribe();
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
  }

  onSuccess(result) {
    var route = result.response.route[0];
    /*
     * The styling of the route response on the map is entirely under the developer's control.
     * A representitive styling can be found the full JS + HTML code of this example
     * in the functions below:
     */
    this.addRouteShapeToMap(route);
    this.addManueversToMap(route);
    this.mapDataService.mapDataSubject.next(route);

    //addWaypointsToPanel(route.waypoint);
    //addManueversToPanel(route);
    //addSummaryToPanel(route.summary);
  }

  /**
     * This function will be called if a communication error occurs during the JSON-P request
     * @param  {Object} error  The error message received.
     */
  onError(error) {
    alert('Can\'t reach the remote server');
  }

  bubble;

  /**
   * Opens/Closes a infobubble
   * @param  {H.geo.Point} position     The location on the map.
   * @param  {String} text              The contents of the infobubble.
   */
  openBubble(position, text) {
    if (!this.bubble) {
      this.bubble = new H.ui.InfoBubble(
        position,
        // The FO property holds the province name.
        { content: text });
      this.ui.addBubble(this.bubble);
    } else {
      this.bubble.setPosition(position);
      this.bubble.setContent(text);
      this.bubble.open();
    }
  }

  /**
   * Creates a H.map.Polyline from the shape of the route and adds it to the map.
   * @param {Object} route A route as received from the H.service.RoutingService
   */
  addRouteShapeToMap(route) {
    var lineString = new H.geo.LineString(),
      routeShape = route.shape,
      polyline;

    routeShape.forEach(function (point) {
      var parts = point.split(',');
      lineString.pushLatLngAlt(parts[0], parts[1]);
    });

    polyline = new H.map.Polyline(lineString, {
      style: {
        lineWidth: 4,
        strokeColor: 'rgba(0, 128, 255, 0.7)'
      }
    });
    // Add the polyline to the map
    this.map.addObject(polyline);
    // And zoom to its bounding rectangle
    this.map.getViewModel().setLookAtData({
      bounds: polyline.getBoundingBox()
    });
  }

  /**
  * Creates a series of H.map.Marker points from the route and adds them to the map.
  * @param {Object} route  A route as received from the H.service.RoutingService
  */
  addManueversToMap(route) {
    var svgMarkup = '<svg width="18" height="18" ' +
      'xmlns="http://www.w3.org/2000/svg">' +
      '<circle cx="8" cy="8" r="8" ' +
      'fill="#1b468d" stroke="white" stroke-width="1"  />' +
      '</svg>',
      dotIcon = new H.map.Icon(svgMarkup, { anchor: { x: 8, y: 8 } }),
      group = new H.map.Group()
    var group = new H.map.Group();

    // Add a marker for each maneuver
    for (let i = 0; i < route.leg.length; i += 1) {
      for (let j = 0; j < route.leg[i].maneuver.length; j += 1) {
        // Get the next maneuver.
        var maneuver = route.leg[i].maneuver[j];
        // Add a marker to the maneuvers group
        var marker = new H.map.Marker({
          lat: maneuver.position.latitude,
          lng: maneuver.position.longitude
        },
          { icon: dotIcon });
        marker.instruction = maneuver.instruction;
        group.addObject(marker);
      }
    }

    group.addEventListener('tap', (evt) => {
      this.map.setCenter(evt.target.getGeometry());
      this.openBubble(
        evt.target.getGeometry(), evt.target.instruction);
    }, false);

    // Add the maneuvers group to the map
    this.map.addObject(group);
  }

  calculateRoute() {
    var waypoint0 = this.bikePosition.lat + ',' + this.bikePosition.lng;
    var waypoint1 = this.destinationPosition.lat + ',' + this.destinationPosition.lng;
    var router = this.platform.getRoutingService(),
      routeRequestParams = {
        mode: 'fastest;bicycle',
        representation: 'display',
        routeattributes: 'waypoints,summary,shape,legs',
        maneuverattributes: 'direction,action',
        waypoint0: waypoint0, // Brandenburg Gate
        waypoint1: waypoint1  // Friedrichstraße Railway Station
      };

    router.calculateRoute(
      routeRequestParams,
      this.onSuccess.bind(this),
      this.onError.bind(this)
    );
  }


  initializeMap() {
    // Obtain the default map types from the platform object
    this.defaultLayers = this.platform.createDefaultLayers();
    this.map = new H.Map(
      this.mapElement.nativeElement,
      this.defaultLayers.raster.normal.map,
      {
        center: { lat: this.locationService.preiousUserPosition.lat, lng: this.locationService.preiousUserPosition.lng },
        zoom: 17,
        pixelRatio: window.devicePixelRatio || 1
      }
    );

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
    this.ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
    this.ui.removeControl("mapsettings");
    // create custom map settings (icons on map)
    var customMapSettings = new H.ui.MapSettingsControl({
      baseLayers: [
        {
          label: "3D", layer: this.defaultLayers.vector.normal.map
        }, {
          label: "Normal", layer: this.defaultLayers.raster.normal.map
        }, {
          label: "Satellite", layer: this.defaultLayers.raster.satellite.map
        }, {
          label: "Terrain", layer: this.defaultLayers.raster.terrain.map
        }
      ],
      layers: [
        {
          label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
        },
        {
          label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
        }
      ]
    });
    this.ui.addControl("custom-mapsettings", customMapSettings);
    var mapSettings = this.ui.getControl('custom-mapsettings');
    var zoom = this.ui.getControl('zoom');
    mapSettings.setAlignment('top-right');
    zoom.setAlignment('right-top');

    this.map.getViewPort().setPadding(30, 30, 30, 30);

    // Listen for base layer change event (eg. from satellite to 3D)
    this.map.addEventListener('baselayerchange', (evt) => {
      let mapConfig = this.map.getBaseLayer().getProvider().getStyleInternal().getConfig();
      if (mapConfig === null || (mapConfig && mapConfig.sources && mapConfig.sources.omv)) {
        this.map.getViewModel().setLookAtData({ tilt: 60 });
      } else {
        this.map.getViewModel().setLookAtData({ tilt: 0 });
      }
    });

    // listen for map click event
    this.map.addEventListener('tap', this.mapClickedEvent.bind(this));

    if(!this.locationsGroup) {
      this.locationsGroup = new H.map.Group();
    }
    this.map.addObject(this.locationsGroup);
  }

  mapClickedEvent(event) {
    if(this.rideStarted) {
      return;
    }
    //console.log(event.type, event.currentPointer.type);
    var coord = this.map.screenToGeo(event.currentPointer.viewportX,
      event.currentPointer.viewportY);
    console.log(coord.lat + ', ' + coord.lng);

    this.destinationPosition = { lat: coord.lat, lng: coord.lng };

    if (this.destinationMarker) {
      this.destinationMarker.setGeometry({ lat: coord.lat, lng: coord.lng })
    } else {
      let icon = new H.map.Icon('../../../assets/images/current_location.png');
      // Create a marker using the previously instantiated icon:
      this.destinationMarker = new H.map.Marker({ lat: coord.lat, lng: coord.lng }, { icon: icon });
      // Add the marker to the map:
      if(!this.locationsGroup) {
        this.locationsGroup = new H.map.Group();
      }
      this.locationsGroup.addObjects([this.destinationMarker]);
      this.setZoomLevelToPointersGroup();
    }
  }

  //TODO change this logic
  getCurrentPosition() {
    if (!this.currentLocationMarker) {
      this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
    }
    this.map.setZoom(17);
    this.map.setCenter({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng });
  }

  setZoomLevelToPointersGroup() {
    this.map.getViewModel().setLookAtData({
      bounds: this.locationsGroup.getBoundingBox()
    });
  }

  showUserLocationOnMap(lat, lng) {
    let svgMarkup = '<svg width="24" height="24" ' +
      'xmlns="http://www.w3.org/2000/svg">' +
      '<circle cx="10" cy="10" r="10" ' +
      'fill="#007cff" stroke="white" stroke-width="2"  />' +
      '</svg>';
    let icon = new H.map.Icon(svgMarkup);
    //let icon = new H.map.Icon('../../../assets/images/current_location.png');
    // Create a marker using the previously instantiated icon:
    this.currentLocationMarker = new H.map.Marker({ lat: lat, lng: lng }, { icon: icon });
    // Add the marker to the map:
    if(!this.locationsGroup) {
      this.locationsGroup = new H.map.Group();
    }
    this.locationsGroup.addObjects([this.currentLocationMarker]);
    this.setZoomLevelToPointersGroup();

    //this.map.addObject(marker);
    //this.map.setCenter({ lat: lat, lng: lng });
  }

  addMarker(lat, lng, img) {
    var icon = new H.map.Icon(img);
    // Create a marker using the previously instantiated icon:
    var marker = new H.map.Marker({ lat: lat, lng: lng }, { icon: icon });
    // Add the marker to the map:
    //this.map.addObject(marker);
    if(!this.locationsGroup) {
      this.locationsGroup = new H.map.Group();
    }
    this.locationsGroup.addObjects([marker]);
  }

  enable3DMaps() {
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
  }

535
536
537
538
539
540
541
542
543
544
545
546
547
548
  reverseGeocode(platform, lat, lng) {
    var prox = lat + ',' + lng + ',56';
    var geocoder = platform.getGeocodingService(),
      parameters = {
        prox: prox,
        mode: 'retrieveAddresses',
        maxresults: '1',
        gen: '9'
      };

    geocoder.reverseGeocode(parameters, result => {
      var streets = result.Response.View[0].Result[0].Location.Address.Street;
      var houseNumber = result.Response.View[0].Result[0].Location.Address.HouseNumber;
      var zipcode = result.Response.View[0].Result[0].Location.Address.PostalCode;
549

550
      return streets + houseNumber + zipcode;
551
552
553
554
    }, (error) => {
      alert(error);
    });
  }
Priyanka Upadhye's avatar
Priyanka Upadhye committed
555
}