home.page.ts 10.9 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
12
import { DistanceService } from '../services/distance.service';

13

Rron Jahja's avatar
Rron Jahja committed
14
declare var H: any;
15

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

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

29
30
31
  bikes = [];
  bikeApi: Observable<any>;

32
  public isDetailsVisible = false;
33
  public selectedBike:any = { id: 0 };
34
  public distance="";
35
  public isBikeReserved = false;
36

37
38
  public currentLocationMarker: any;

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

42
  constructor(private geolocation: Geolocation,
43
    private router: Router,
44
    public restService: RestService,
45
    public httpClient: HttpClient,
46
    private storage: Storage,
47
    private toastService: ToastService,
48
    public distanceService: DistanceService,
49
50
    public locationService: LocationService,
    public loadingService: LoadingService) {
51

Rron Jahja's avatar
Rron Jahja committed
52
53
54
55
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
  }
56

57
  ngOnInit() {
58
    
59
  }
60

61
  ngAfterViewInit() {
62
    window.addEventListener('resize', () => this.map.getViewPort().resize());
63
64
65
66
67
68
69
70
71
72
73
  }

  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);
    }
74
    this.getBikesList();
75
76

    this.locationService.liveLocationSubject.subscribe((position) => {
77
      //console.log('got location inside home subscription');
78
79
80
81
82
83
84
85
      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);
      }
    });
86
87
  }

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

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

132
133
134
135
    this.map.getViewPort().setPadding(30, 30, 30, 30);

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

144
    // listen for map click event
145
    this.map.addEventListener('tap', (event) => {
146
      //console.log(event.type, event.currentPointer.type);
147
148
149
150
151
152
    });

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

  getBikesList() {
153
    this.loadingService.showLoader();
154
155
156
157
158
    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) => {
159
        //console.log("bikes response", resp);
160
161
162
163
164
165
        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();
166
        this.loadingService.hideLoader();
167
      }, (error) => {console.log(error)
168
        this.loadingService.hideLoader();
169
      });
170
171
172
173
    });
  }

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

189
    //this.map.addObject(this.locationsGroup);
190
    this.setZoomLevelToPointersGroup();
Rron Jahja's avatar
Rron Jahja committed
191
  }
192

193
  //TODO change this logic
194
  getCurrentPosition() {
195
196
    this.map.setZoom(17);
    this.map.setCenter({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng });
197
  }
198

199
200
201
202
203
204
205
206
  setZoomLevelToPointersGroup() {
    this.map.getViewModel().setLookAtData({
      bounds: this.locationsGroup.getBoundingBox()
    });
  }

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

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

224
  addMarker(lat, lng, img) {
225
226
227
228
    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:
229
230
231
    //this.map.addObject(marker);

    this.locationsGroup.addObjects([marker]);
232
  }
233
234
235
236
  navigatetoBikeList() {
    this.isDetailsVisible = false;
    this.ionViewWillEnter();
  }
237
238

  enable3DMaps() {
239
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
240
  }
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

  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;
256

257
258
259
260
261
262
263
264
265
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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

266
  showBikeDetails(bike) {
267
    this.selectedBike = bike;
268
269
    this.distance= bike.distance;
    this.distanceService.setDistance(this.distance);
270
271
    this.isDetailsVisible = true;
  }
272

273
  reserveBike() {
274
    //this.selectedBike=bikeS;
275
    this.loadingService.showLoader();
276
277
278
279
280
    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) => {
281
        //console.log('my data: ', resp);
282
        this.isBikeReserved = true;
283
        this.toastService.showToast("Reservation Successful!");
284
        this.router.navigateByUrl('/myreservation');
285
        this.loadingService.hideLoader();
286
        this.isDetailsVisible = false;
287
      }, (error) => {
288
        //console.log(error);
289
        this.loadingService.hideLoader();
290
        this.toastService.showToast("Only one bike may be reserved or rented at a time");
291
        this.isDetailsVisible = false;
292
      });
293
294
    });
  }
295

296
  ngOnDestroy(){
297
    //this.locationService.liveLocationSubject.unsubscribe();
298
299
  }

300
301
  ionViewDidLeave(){
    if(this.mapElement) {
302
      //this.mapElement.nativeElement.remove();
303
304
305
306
307
    }
    // if(this.locationService.liveLocationSubject) {
    //   this.locationService.liveLocationSubject.unsubscribe();
    // }
  }
308
  
309

Rron Jahja's avatar
Rron Jahja committed
310
}