myreservation.page.ts 12.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import { Geolocation } from '@ionic-native/geolocation/ngx';
import { RestService } from '../rest.service';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';
import { ToastService } from '../services/toast.service';
import { Router } from '@angular/router';
10
11
import { LocationService } from '../services/location.service';
import { LoadingService } from '../services/loading.service';
12
import { DistanceService } from '../services/distance.service';
13
14
15
16
17
18
19
20
21
22
23
24
25

declare var H: any;

@Component({
  selector: 'app-myreservation',
  templateUrl: './myreservation.page.html',
  styleUrls: ['./myreservation.page.scss'],
})
export class MyreservationPage implements OnInit {
  private platform: any;
  private map: any;
  // Get an instance of the routing service:
  private mapRouter: any;
26
27
  private ui: any;
  private defaultLayers: any;
28
29
30

  reservedBike: any = {};
  bikeDetails: any = {};
31
  isBikeHired = false;
32
33
  address = "sample";
  isBikeReserved = true;
34
  distance="0";
35

36
37
38
  private currentUserPosition = { lat: 48.783480, lng: 9.180319 };

  public currentLocationMarker: any;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

  // Create the parameters for the routing request:
  private routingParameters = {
    // The routing mode:
    mode: 'shortest;pedestrian',
    // The start point of the route:
    waypoint0: 'geo!50.1120423728813,8.68340740740811',
    // The end point of the route:
    waypoint1: 'geo!52.5309916298853,13.3846220493377',
    // To retrieve the shape of the route we choose the route
    // representation mode 'display'
    representation: 'display'
  };

  @ViewChild("mapElement", { static: false })
  public mapElement: ElementRef;

  constructor(private geolocation: Geolocation,
    public restService: RestService,
    public httpClient: HttpClient,
    private storage: Storage,
    private toastService: ToastService,
61
62
    private router: Router,
    public locationService: LocationService,
63
    public distanceService: DistanceService,
64
    public loadingService: LoadingService) {
65
    this.platform = new H.service.Platform({
66
67
      // Api key for HereMaps JS version 
      'apikey': ''
68
69
70
71
72
    });
    this.mapRouter = this.platform.getRoutingService();
  }

  ngOnInit() {
73

74
75
76
77
78
79
  }

  ngAfterViewInit() {

  }

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  ionViewWillEnter() {
    this.currentUserPosition.lat = this.locationService.currentUserPosition.lat;
    this.currentUserPosition.lng = this.locationService.currentUserPosition.lng;
    
    this.loadmap();
    
    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();

    this.locationService.liveLocationSubject.subscribe((position) => {
95
      //console.log('got location inside home subscription');
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
      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);
      }
    });
  }

  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:
    this.map.addObject(this.currentLocationMarker);

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

  addBikeOnMap() {
    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 (this.bikeDetails.batteryPercentage < 100 && this.bikeDetails.batteryPercentage >= 75) {
      this.addMarker(Number(this.bikeDetails.lat), Number(this.bikeDetails.lon), img[0]);
    }
    else if (this.bikeDetails.batteryPercentage < 75 && this.bikeDetails.batteryPercentage >= 50) {
      this.addMarker(Number(this.bikeDetails.lat), Number(this.bikeDetails.lon), img[1]);
    }
    else if (this.bikeDetails.batteryPercentage < 50 && this.bikeDetails.batteryPercentage >= 25) {
      this.addMarker(Number(this.bikeDetails.lat), Number(this.bikeDetails.lon), img[2]);
    } else if (this.bikeDetails.batteryPercentage < 25 && this.bikeDetails.batteryPercentage >= 0) {
      this.addMarker(Number(this.bikeDetails.lat), Number(this.bikeDetails.lon), img[3]);
    }
  }

137
  getReservedBike() {
138
    this.loadingService.showLoader();
139
140
141
142
143
144
    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) => {
145
        //console.log('Reserved Bike', resp);
146
147
        if (resp.data) {
          this.reservedBike = resp.data;
148
          this.isBikeHired = this.reservedBike.rented;
149
150
151
152
          //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) => {
153
            //console.log('Bike Details', resp);
154
            this.loadingService.hideLoader();
155
            this.bikeDetails = resp.data;
156
            this.distance = this.distanceService.getDistance();
157
            this.reverseGeocode(this.platform, this.bikeDetails.lat, this.bikeDetails.lon);
158
159
160
161
162
163
164
165
166
167
            this.isBikeReserved = true;
            this.addBikeOnMap();

            // set routing params
            this.routingParameters.waypoint1 = 'geo!' + this.bikeDetails.lat + ',' + this.bikeDetails.lon;
            this.routingParameters.waypoint0 = 'geo!' + this.currentUserPosition.lat + ',' + this.currentUserPosition.lng;

            // show route on map
            this.mapRouter.calculateRoute(this.routingParameters, this.onResult.bind(this),
              (error) => {
168
                //console.log(error.message);
169
170
              });
          }, (reservedBikeError) => {
171
            this.loadingService.hideLoader();
172
            //console.log(reservedBikeError);
173
174
            this.isBikeReserved = false;
          });
175
176
177
        } else {
          this.loadingService.hideLoader();
          this.isBikeReserved = false;
178
        }
179
      }, (bikeDetailsError) => {
180
        this.loadingService.hideLoader();
181
        //console.log(bikeDetailsError)
182
183
        this.isBikeReserved = false;
      });
184
185
186
187
188
189
190
191
192
    });
  }

  cancelReservation() {
    this.storage.get('token').then((token) => {
      let url = 'http://193.196.52.237:8081/reservation' + '?bikeId=' + this.bikeDetails.id;
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
      let bikeApi = this.httpClient.delete(url, { headers });
      bikeApi.subscribe((resp) => {
193
        //console.log('Reservation Cancelled: ', resp);
194
195
196
197
198
199
200
        this.toastService.showToast("Bike Reservation successfully cancelled.");
        this.router.navigateByUrl('/home');
      }, (error) => console.log(error));
    });
  }

  loadmap() {
201
    this.defaultLayers = this.platform.createDefaultLayers();
202
203
    this.map = new H.Map(
      this.mapElement.nativeElement,
204
      this.defaultLayers.raster.normal.map,
205
      {
206
        center: { lat: this.locationService.preiousUserPosition.lat, lng: this.locationService.preiousUserPosition.lng },
207
208
209
210
211
212
        zoom: 17,
        pixelRatio: window.devicePixelRatio || 1
      }
    );

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
213
214
    this.ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
    this.ui.removeControl("mapsettings");
215
    // create custom one
216
    var customMapSettings = new H.ui.MapSettingsControl({
217
      baseLayers: [{
218
        label: "3D", layer: this.defaultLayers.vector.normal.map
219
      }, {
220
        label: "Normal", layer: this.defaultLayers.raster.normal.map
221
      }, {
222
        label: "Satellite", layer: this.defaultLayers.raster.satellite.map
223
      }, {
224
        label: "Terrain", layer: this.defaultLayers.raster.terrain.map
225
226
227
      }
      ],
      layers: [{
228
        label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
229
230
      },
      {
231
        label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
232
233
234
      }
      ]
    });
235
236
237
    this.ui.addControl("custom-mapsettings", customMapSettings);
    var mapSettings = this.ui.getControl('custom-mapsettings');
    var zoom = this.ui.getControl('zoom');
238
    mapSettings.setAlignment('top-right');
239
    zoom.setAlignment('right-top');
240

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

243
    this.map.getViewPort().setPadding(30, 30, 30, 30);
244
245
  }

246
247
248
249
250
251
252
  //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 });
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  }

  moveMapToGiven(map, lat, lng) {
    var icon = new H.map.Icon('../../../assets/images/current_location.png');
    // 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:
    map.addObject(marker);
    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);
  }
271
272
273
274
275
276
277
278
279
280
281
  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 => {
282
      //console.log(result);
283
284
285
      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;
286

287
      this.address = streets;
288

289
290
291
292
293

    }, (error) => {
      alert(error);
    });
  }
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


  // Define a callback function to process the routing response:
  onResult(result) {
    var route,
      routeShape,
      startPoint,
      endPoint,
      linestring;
    if (result.response.route) {
      // Pick the first route from the response:
      route = result.response.route[0];
      // Pick the route's shape:
      routeShape = route.shape;

      // Create a linestring to use as a point source for the route line
      linestring = new H.geo.LineString();

      // Push all the points in the shape into the linestring:
      routeShape.forEach(function (point) {
        var parts = point.split(',');
        linestring.pushLatLngAlt(parts[0], parts[1]);
      });

      // Retrieve the mapped positions of the requested waypoints:
      startPoint = route.waypoint[0].mappedPosition;
      endPoint = route.waypoint[1].mappedPosition;

      // Create a polyline to display the route:
      var routeLine = new H.map.Polyline(linestring, {
        /* style: {
          lineWidth: 10,
          fillColor: 'white',
          strokeColor: 'rgba(255, 255, 255, 1)',
          lineDash: [0, 2],
          lineTailCap: 'arrow-tail',
          lineHeadCap: 'arrow-head' 
        } */
        style: {
333
334
          lineWidth: 6,
          strokeColor: 'rgba(0, 72, 255, 0.8)',
335
          lineDash: [0, 2]
336
        }
337
338
339
340
341
342
343
344
345
346
      });

      // Add the route polyline and the two markers to the map:
      this.map.addObjects([routeLine]);

      // Set the map's viewport to make the whole route visible:
      this.map.getViewModel().setLookAtData({ bounds: routeLine.getBoundingBox() });
      //this.map.setZoom(this.map.getZoom() - 4.3, true);
    }
  };
347

Priyanka Upadhye's avatar
Priyanka Upadhye committed
348
  hireBike() {
349
    if (this.isBikeHired)
350
      this.toastService.showToast("You already Hired this bike");
351
    else
352
      this.router.navigateByUrl('/hirebike');
Priyanka Upadhye's avatar
Priyanka Upadhye committed
353
  }
354
355
356

  ionViewDidLeave(){
    if(this.mapElement) {
357
      //this.mapElement.nativeElement.remove();
358
359
360
361
362
    }
    // if(this.locationService.liveLocationSubject) {
    //   this.locationService.liveLocationSubject.unsubscribe();
    // }
  }
363
}