home.page.ts 10.6 KB
Newer Older
1
import { Component, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
Rron Jahja's avatar
Rron Jahja committed
2
import { Geolocation } from '@ionic-native/geolocation/ngx';
3
4
5
import { RestService } from '../rest.service';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
6
import { Storage } from '@ionic/storage';
7
import { ToastService } from '../services/toast.service';
8
import { Router } from '@angular/router';
9
10
import { LocationService } from '../services/location.service';
import { LoadingService } from '../services/loading.service';
11

Rron Jahja's avatar
Rron Jahja committed
12
declare var H: any;
13

Rron Jahja's avatar
Rron Jahja committed
14
15
16
17
18
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
19

20
export class HomePage implements OnInit, OnDestroy {
Rron Jahja's avatar
Rron Jahja committed
21
  private platform: any;
22
  private map: any;
23
  private defaultLayers: any;
24
  private locationsGroup: any;
25
  private currentUserPosition = { lat: 48.783480, lng: 9.180319 };
26

27
28
29
  bikes = [];
  bikeApi: Observable<any>;

30
  public isDetailsVisible = false;
31
32
  public selectedBike = { id: 0 };
  public isBikeReserved = false;
33

34
35
  public currentLocationMarker: any;

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

39
  constructor(private geolocation: Geolocation,
40
    private router: Router,
41
    public restService: RestService,
42
    public httpClient: HttpClient,
43
    private storage: Storage,
44
45
46
    private toastService: ToastService,
    public locationService: LocationService,
    public loadingService: LoadingService) {
47

Rron Jahja's avatar
Rron Jahja committed
48
49
50
51
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
  }
52

53
  ngOnInit() {
54
    
55
  }
56

57
  ngAfterViewInit() {
58
    window.addEventListener('resize', () => this.map.getViewPort().resize());
59
60
61
62
63
64
65
66
67
68
69
  }

  ionViewWillEnter() {
    this.currentUserPosition.lat = this.locationService.currentUserPosition.lat;
    this.currentUserPosition.lng = this.locationService.currentUserPosition.lng;
    this.initializeMap();
    if (this.currentLocationMarker) {
      this.currentLocationMarker.setGeometry({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng })
    } else {
      this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
    }
70
    this.getBikesList();
71
72
73
74
75
76
77
78
79
80
81

    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);
      }
    });
82
83
  }

84
  initializeMap() {
85
    // Obtain the default map types from the platform object
86
    this.defaultLayers = this.platform.createDefaultLayers();
87
    this.map = new H.Map(
88
89
      this.mapElement.nativeElement,
      this.defaultLayers.raster.normal.map,
90
      {
91
        center: { lat: this.locationService.preiousUserPosition.lat, lng: this.locationService.preiousUserPosition.lng },
92
        zoom: 17,
93
94
95
        pixelRatio: window.devicePixelRatio || 1
      }
    );
96

97
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
98
    var ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
99
    ui.removeControl("mapsettings");
100
101
    // create custom map settings (icons on map)
    var customMapSettings = new H.ui.MapSettingsControl({
102
103
104
105
106
107
108
109
110
111
      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
        }
112
      ],
113
114
115
116
117
118
119
      layers: [
        {
          label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
        },
        {
          label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
        }
120
121
      ]
    });
122
123
124
    ui.addControl("custom-mapsettings", customMapSettings);
    var mapSettings = ui.getControl('custom-mapsettings');
    var zoom = ui.getControl('zoom');
125
    mapSettings.setAlignment('top-right');
126
    zoom.setAlignment('right-top');
127

128
129
130
131
    this.map.getViewPort().setPadding(30, 30, 30, 30);

    // Listen for base layer change event (eg. from satellite to 3D)
    this.map.addEventListener('baselayerchange', (evt) => {
132
133
134
135
136
137
      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 });
      }
138
    });
139

140
    // listen for map click event
141
    this.map.addEventListener('tap', (event) => {
142
143
144
145
146
147
148
      console.log(event.type, event.currentPointer.type);
    });

    this.locationsGroup = new H.map.Group();
  }

  getBikesList() {
149
    this.loadingService.showLoader();
150
151
152
153
154
155
156
157
158
159
160
161
    this.storage.get('token').then((token) => {
      let url = 'http://193.196.52.237:8081/bikes' + '?lat=' + this.currentUserPosition.lat + '&lng=' + this.currentUserPosition.lng;
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
      this.bikeApi = this.httpClient.get(url, { headers });
      this.bikeApi.subscribe((resp) => {
        console.log("bikes response", resp);
        this.bikes = resp;
        for (let i = 0; i < this.bikes.length; i++) {
          this.bikes[i].distance = this.bikes[i].distance.toFixed(2);;
          this.reverseGeocode(this.platform, this.bikes[i].lat, this.bikes[i].lon, i);
        }
        this.showBikesOnMap();
162
        this.loadingService.hideLoader();
163
      }, (error) => {console.log(error)
164
        this.loadingService.hideLoader();
165
      });
166
167
168
169
    });
  }

  showBikesOnMap() {
170
    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'];
171
    for (let i = 0; i < this.bikes.length; i++) {
172
      if (this.bikes[i].batteryPercentage < 100 && this.bikes[i].batteryPercentage >= 75) {
173
174
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[0]);
      }
175
      else if (this.bikes[i].batteryPercentage < 75 && this.bikes[i].batteryPercentage >= 50) {
176
177
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[1]);
      }
178
      else if (this.bikes[i].batteryPercentage < 50 && this.bikes[i].batteryPercentage >= 25) {
179
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[2]);
180
      } else if (this.bikes[i].batteryPercentage < 25 && this.bikes[i].batteryPercentage >= 0) {
181
182
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[3]);
      }
183
    }
184

185
    //this.map.addObject(this.locationsGroup);
186
    this.setZoomLevelToPointersGroup();
Rron Jahja's avatar
Rron Jahja committed
187
  }
188

189
  //TODO change this logic
190
  getCurrentPosition() {
191
192
    this.map.setZoom(17);
    this.map.setCenter({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng });
193
  }
194

195
196
197
198
199
200
201
202
  setZoomLevelToPointersGroup() {
    this.map.getViewModel().setLookAtData({
      bounds: this.locationsGroup.getBoundingBox()
    });
  }

  showUserLocationOnMap(lat, lng) {
    let svgMarkup = '<svg width="24" height="24" ' +
203
204
      'xmlns="http://www.w3.org/2000/svg">' +
      '<circle cx="10" cy="10" r="10" ' +
205
      'fill="#007cff" stroke="white" stroke-width="2"  />' +
206
      '</svg>';
207
208
    let icon = new H.map.Icon(svgMarkup);
    //let icon = new H.map.Icon('../../../assets/images/current_location.png');
209
    // Create a marker using the previously instantiated icon:
210
    this.currentLocationMarker = new H.map.Marker({ lat: lat, lng: lng }, { icon: icon });
211
    // Add the marker to the map:
212
    this.locationsGroup.addObjects([this.currentLocationMarker]);
213
    this.map.addObject(this.locationsGroup);
214
215
216
217
    this.setZoomLevelToPointersGroup();

    //this.map.addObject(marker);
    //this.map.setCenter({ lat: lat, lng: lng });
Rron Jahja's avatar
Rron Jahja committed
218
  }
219

220
  addMarker(lat, lng, img) {
221
222
223
224
    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:
225
226
227
    //this.map.addObject(marker);

    this.locationsGroup.addObjects([marker]);
228
  }
229
230
231
232
  navigatetoBikeList() {
    this.isDetailsVisible = false;
    this.ionViewWillEnter();
  }
233
234

  enable3DMaps() {
235
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
236
  }
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

  reverseGeocode(platform, lat, lng, index) {
    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;
252

253
254
255
256
257
258
259
260
261
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

    }, (error) => {
      alert(error);
    });
  }

262
  showBikeDetails(bike) {
263
    this.selectedBike = bike;
264
265
    this.isDetailsVisible = true;
  }
266

267
  reserveBike() {
268
    //this.selectedBike=bikeS;
269
    this.loadingService.showLoader();
270
271
272
273
274
275
    this.storage.get('token').then((token) => {
      let url = 'http://193.196.52.237:8081/reservation' + '?bikeId=' + this.selectedBike.id;
      const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
      this.bikeApi = this.httpClient.get(url, { headers });
      this.bikeApi.subscribe((resp) => {
        console.log('my data: ', resp);
276
        this.isBikeReserved = true;
277
        this.toastService.showToast("Reservation Successful!");
278
        this.router.navigateByUrl('/myreservation');
279
        this.loadingService.hideLoader();
280
      }, (error) => {
281
        console.log(error);
282
        this.loadingService.hideLoader();
283
        this.toastService.showToast("Only one bike may be reserved or rented at a time");
284
      });
285
286
    });
  }
287

288
  ngOnDestroy(){
289
    //this.locationService.liveLocationSubject.unsubscribe();
290
291
  }

292
293
294
295
296
297
298
299
300
  ionViewDidLeave(){
    if(this.mapElement) {
      this.mapElement.nativeElement.remove();
    }
    // if(this.locationService.liveLocationSubject) {
    //   this.locationService.liveLocationSubject.unsubscribe();
    // }
  }

Rron Jahja's avatar
Rron Jahja committed
301
}