home.page.ts 8.46 KB
Newer Older
Rron Jahja's avatar
Rron Jahja committed
1
2
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
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
9


Rron Jahja's avatar
Rron Jahja committed
10
declare var H: any;
11

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

Rron Jahja's avatar
Rron Jahja committed
18
export class HomePage {
Rron Jahja's avatar
Rron Jahja committed
19
  private platform: any;
20
  private map: any;
21
  private defaultLayers:any;
22

23
24
25
  bikes = [];
  bikeApi: Observable<any>;

26
  private currentLocation = { lat: 0, lng: 0 };
27
  public isDetailsVisible = false;
28
29
  public selectedBike = { id: 0 };
  public isBikeReserved = false;
30

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

34
35
  constructor(private geolocation: Geolocation,
    public restService: RestService,
36
    public httpClient: HttpClient,
37
38
    private storage: Storage,
    private toastService: ToastService) {
39

Rron Jahja's avatar
Rron Jahja committed
40
41
42
43
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
  }
44

45
46
47
  ngOnInit() {
    this.getBikesList();
  }
48

49
  ngAfterViewInit() {
Rron Jahja's avatar
Rron Jahja committed
50
    setTimeout(() => {
51
      this.loadmap();
52
    }, 700);
53
54
55
56

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

57
  getBikesList() {
58
    this.geolocation.getCurrentPosition({
59
      maximumAge: 1000, timeout: 4000,
60
61
      enableHighAccuracy: true
    }).then((resp) => {
62
63
64
      let lat = resp.coords.latitude;
      let lng = resp.coords.longitude;

65
66
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
67

68
      this.storage.get('token').then((token) => {
69
        let url = 'http://193.196.52.237:8081/bikes' + '?lat=' + lat + '&lng=' + lng;
70
71
72
        const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
        this.bikeApi = this.httpClient.get(url, { headers });
        this.bikeApi.subscribe((resp) => {
73
          console.log('my data: ', resp);
74
          this.bikes = resp;
75
          for (let i = 0; i < this.bikes.length; i++) {
76
            var beforeDotStr = '' + this.bikes[i].distance;
77
78
79
            var beforeDot = beforeDotStr.split('.')[0];
            var afterDotArr = beforeDotStr.split('.')[1].split('');
            var afterDot = afterDotArr[0] + afterDotArr[1];
80
            this.bikes[i].distance = beforeDot + '.' + afterDot;
81
82
            this.reverseGeocode(this.platform, this.bikes[i].lat, this.bikes[i].lon, i);
          }
83
        }, (error) => console.log(error));
84
      });
85
86
87
88
89
90
91
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }

92
  loadmap() {
93
    // Obtain the default map types from the platform object
94
    this.defaultLayers = this.platform.createDefaultLayers();
95
    this.map = new H.Map(
96
97
      this.mapElement.nativeElement,
      this.defaultLayers.raster.normal.map,
98
      {
99
        zoom: 17,
100
101
102
        pixelRatio: window.devicePixelRatio || 1
      }
    );
103

104
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
105
    var ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
106
    ui.removeControl("mapsettings");
107
108
    // create custom map settings (icons on map)
    var customMapSettings = new H.ui.MapSettingsControl({
109
      baseLayers: [{
110
        label: "3D", layer: this.defaultLayers.vector.normal.map
111
      }, {
112
        label: "Normal", layer: this.defaultLayers.raster.normal.map
113
      }, {
114
        label: "Satellite", layer: this.defaultLayers.raster.satellite.map
115
      }, {
116
        label: "Terrain", layer: this.defaultLayers.raster.terrain.map
117
118
119
      }
      ],
      layers: [{
120
        label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
121
122
      },
      {
123
        label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
124
125
126
      }
      ]
    });
127
    ui.addControl("custom-mapsettings", customMapSettings);
128

129
130
    var mapSettings = ui.getControl('custom-mapsettings');
    var zoom = ui.getControl('zoom');
131
    mapSettings.setAlignment('top-right');
132
    zoom.setAlignment('right-top');
133
    
134
135
136
137
138
139
140
141

    this.map.addEventListener('baselayerchange', (data) => {
      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
    this.getLocation(this.map);
144
145
146


    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'];
147
    for (let i = 0; i < this.bikes.length; i++) {
148
      if (this.bikes[i].batteryPercentage < 100 && this.bikes[i].batteryPercentage >= 75) {
149
150
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[0]);
      }
151
      else if (this.bikes[i].batteryPercentage < 75 && this.bikes[i].batteryPercentage >= 50) {
152
153
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[1]);
      }
154
      else if (this.bikes[i].batteryPercentage < 50 && this.bikes[i].batteryPercentage >= 25) {
155
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[2]);
156
      } else if (this.bikes[i].batteryPercentage < 25 && this.bikes[i].batteryPercentage >= 0) {
157
158
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[3]);
      }
159

160
    }
Rron Jahja's avatar
Rron Jahja committed
161
  }
162

163
  getCurrentPosition() {
164
    this.getLocation(this.map.setZoom(17));
165
  }
166

Rron Jahja's avatar
Rron Jahja committed
167
168
169
  getLocation(map) {
    this.geolocation.getCurrentPosition(
      {
170
        maximumAge: 1000, timeout: 2000,
Rron Jahja's avatar
Rron Jahja committed
171
172
173
        enableHighAccuracy: true
      }
    ).then((resp) => {
174
175
      let lat = resp.coords.latitude;
      let lng = resp.coords.longitude;
176
177
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
Rron Jahja's avatar
Rron Jahja committed
178
179
180
181
182
183
184
      this.moveMapToGiven(map, lat, lng);
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }
185

Rron Jahja's avatar
Rron Jahja committed
186
  moveMapToGiven(map, lat, lng) {
187
    var icon = new H.map.Icon('../../../assets/images/current_location.png');
188
189
190
191
    // 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);
Rron Jahja's avatar
Rron Jahja committed
192
193
    map.setCenter({ lat: lat, lng: lng });
  }
194

195
  addMarker(lat, lng, img) {
196
197
198
199
200
201
    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);
  }
202
203

  enable3DMaps() {
204
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
205
  }
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

  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 => {
      console.log(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;
222

223
224
225
226
227
228
229
230
231
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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

232
  showBikeDetails(bike) {
233
    this.selectedBike = bike;
234
235
    this.isDetailsVisible = true;
  }
236

237
  reserveBike() {
238
239
240
241
242
243
244
    //this.selectedBike=bikeS;
    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);
245
        this.isBikeReserved = true;
246
247
248
249
250
        this.toastService.showToast("Reservation Successful!");
      }, (error) => {
        console.log(error)
        this.toastService.showToast("Only one bike may be reserved or rented at a time")
      });
251
252
    });
  }
253

Rron Jahja's avatar
Rron Jahja committed
254
}