home.page.ts 8.27 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("bikes response", resp);
74
          this.bikes = resp;
75
          for (let i = 0; i < this.bikes.length; i++) {
76
            this.bikes[i].distance = this.bikes[i].distance.toFixed(2);;
77
78
            this.reverseGeocode(this.platform, this.bikes[i].lat, this.bikes[i].lon, i);
          }
79
        }, (error) => console.log(error));
80
      });
81
    }, er => {
82
      alert('Can not retrieve location');
83
    }).catch((error) => {
84
      alert('Error getting location - ' + JSON.stringify(error));
85
86
87
    });
  }

88
  loadmap() {
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
        zoom: 17,
96
97
98
        pixelRatio: window.devicePixelRatio || 1
      }
    );
99

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

    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 });
      }
138
    });
139
    this.getLocation(this.map);
140
141

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

155
    }
Rron Jahja's avatar
Rron Jahja committed
156
  }
157

158
  getCurrentPosition() {
159
    this.getLocation(this.map.setZoom(17));
160
  }
161

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

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

190
  addMarker(lat, lng, img) {
191
192
193
194
195
196
    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);
  }
197
198

  enable3DMaps() {
199
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
200
  }
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216

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

218
219
220
221
222
223
224
225
226
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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

227
  showBikeDetails(bike) {
228
    this.selectedBike = bike;
229
230
    this.isDetailsVisible = true;
  }
231

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

Rron Jahja's avatar
Rron Jahja committed
249
}