home.page.ts 9.36 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
  bikes = [];
23
  streets = [];
24
25
  bikeApi: Observable<any>;

26

27
  private currentLocation = { lat: 0, lng: 0 };
28

29
  public is3DChecked = false;
30
  public isDetailsVisible = false;
31
32
  public selectedBike = { id: 0 };
  public isBikeReserved = false;
33
34
35
36
37
38

  public tempArr = [1, 2];
  public locationArr = [{ lat: 48.778409, lng: 9.179252 },
  { lat: 48.780926, lng: 9.173456 },
  { lat: 48.775174, lng: 9.175459 },
  { lat: 48.793704, lng: 9.191112 }]
39
  public arrayLanLon = { lat: 0, lng: 0 };
40
41
42
43
44
45
46
  @ViewChild("mapElement2d", { static: false })
  public mapElement2d: ElementRef;

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


47

48

49
50
  constructor(private geolocation: Geolocation,
    public restService: RestService,
51
    public httpClient: HttpClient,
52
53
    private storage: Storage,
    private toastService: ToastService) {
54

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

60
61
62
  ngOnInit() {
    this.getBikesList();
  }
63

64
  ngAfterViewInit() {
Rron Jahja's avatar
Rron Jahja committed
65
    setTimeout(() => {
66
      this.loadmap("2D");
67
    }, 700);
68
69
70
71

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

72
  getBikesList() {
73
    this.geolocation.getCurrentPosition({
74
      maximumAge: 1000, timeout: 4000,
75
76
      enableHighAccuracy: true
    }).then((resp) => {
77
78
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
79

80
81
82
83
84
      this.storage.get('token').then((token) => {
        let url = 'http://193.196.52.237:8081/bikes' + '?lat=' + this.currentLocation.lat + '&lng=' + this.currentLocation.lng;
        const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
        this.bikeApi = this.httpClient.get(url, { headers });
        this.bikeApi.subscribe((resp) => {
85
          console.log('my data: ', resp);
86
          this.bikes = resp;
87
          for (let i = 0; i < this.bikes.length; i++) {
88
            var beforeDotStr = '' + this.bikes[i].distance;
89
90
91
            var beforeDot = beforeDotStr.split('.')[0];
            var afterDotArr = beforeDotStr.split('.')[1].split('');
            var afterDot = afterDotArr[0] + afterDotArr[1];
92
            this.bikes[i].distance = beforeDot + '.' + afterDot;
93
94
            this.reverseGeocode(this.platform, this.bikes[i].lat, this.bikes[i].lon, i);
          }
95
        }, (error) => console.log(error));
96
      });
97
98
99
100
101
102
103
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }

104
  loadmap(style) {
105
    // Obtain the default map types from the platform object
106
107
108
109
110
111
    var mapStyle = "raster";
    var mapElement = "mapElement2d";
    if (style === "3D") {
      mapStyle = "vector";
      mapElement = "mapElement3d";
    }
112
    this.defaultLayers = this.platform.createDefaultLayers();
113
    this.map = new H.Map(
114
      this[mapElement].nativeElement,
115
      this.defaultLayers[mapStyle].normal.map,
116
      {
117
        zoom: 17,
118
119
120
        pixelRatio: window.devicePixelRatio || 1
      }
    );
121

122
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
123
    var ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
124
125
126
127
    ui.removeControl("mapsettings");
    // create custom one
    var ms = new H.ui.MapSettingsControl({
      baseLayers: [{
128
        label: "3D", layer: this.defaultLayers.vector.normal.map
129
      }, {
130
        label: "Normal", layer: this.defaultLayers.raster.normal.map
131
      }, {
132
        label: "Satellite", layer: this.defaultLayers.raster.satellite.map
133
      }, {
134
        label: "Terrain", layer: this.defaultLayers.raster.terrain.map
135
136
137
      }
      ],
      layers: [{
138
        label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
139
140
      },
      {
141
        label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
142
143
144
145
146
      }
      ]
    });
    ui.addControl("customized", ms);
    var mapSettings = ui.getControl('customized');
147
    var zoom = ui.getControl('zoom');
148

149
    mapSettings.setAlignment('top-right');
150
    zoom.setAlignment('right-top');
151
152
    if (style === "3D") {
      this.map.getViewModel().setLookAtData({ tilt: 60 });
153
    }
154
155
156
157
158
159
160
161
162
163
164
165

    this.map.addEventListener('baselayerchange', (data) => {
      //let mapState = this.map.getBaseLayer().getProvider().getStyleInternal().getState();
      let mapConfig = this.map.getBaseLayer().getProvider().getStyleInternal().getConfig();
      console.log(JSON.stringify(mapConfig));
      //console.log(this.map.getLayers().asArray());
      if (mapConfig === null || (mapConfig && mapConfig.sources && mapConfig.sources.omv)) {
        this.map.getViewModel().setLookAtData({ tilt: 60 });
      } else {
        this.map.getViewModel().setLookAtData({ tilt: 0 });
      }
    })
166
    this.getLocation(this.map);
167
168
169


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

183
    }
Rron Jahja's avatar
Rron Jahja committed
184
  }
185
  getCurrentPosition() {
186
    this.getLocation(this.map.setZoom(17));
187

188
  }
189

Rron Jahja's avatar
Rron Jahja committed
190
191
192
  getLocation(map) {
    this.geolocation.getCurrentPosition(
      {
193
        maximumAge: 1000, timeout: 2000,
Rron Jahja's avatar
Rron Jahja committed
194
        enableHighAccuracy: true
195

Rron Jahja's avatar
Rron Jahja committed
196
197
198
199
      }
    ).then((resp) => {
      let lat = resp.coords.latitude
      let lng = resp.coords.longitude
200
201
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
Rron Jahja's avatar
Rron Jahja committed
202
203
204
205
206
207
208
      this.moveMapToGiven(map, lat, lng);
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }
209

Rron Jahja's avatar
Rron Jahja committed
210
  moveMapToGiven(map, lat, lng) {
211

212
    var icon = new H.map.Icon('../../../assets/images/current_location.png');
213
214
215
216
217
    // 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
218
219
    map.setCenter({ lat: lat, lng: lng });
  }
220

221

222

223
  addMarker(lat, lng, img) {
224
225
226
227
228
229
230
    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);
  }
231
232
233
234
235
236
237
238
239
240
241

  toggle3DMaps() {
    console.log(this.is3DChecked);
    if (!this.is3DChecked) {
      setTimeout(() => {
        this.loadmap("3D");
      }, 1000);
    }
  }

  enable3DMaps() {
242
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
243
  }
244

245

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
  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;
261

262
263
264
265
266
267
268
269
270
271
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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


272
  showBikeDetails(bike) {
273

274
275
    this.selectedBike = bike;
    this.selectedBike.id = bike.id;
276
277
    this.isDetailsVisible = true;
  }
278
  reserveBike() {
279
280
281
282
283
284
285
    //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);
286
        this.isBikeReserved = true;
287
288
289
290
291
        this.toastService.showToast("Reservation Successful!");
      }, (error) => {
        console.log(error)
        this.toastService.showToast("Only one bike may be reserved or rented at a time")
      });
292
293
    });
  }
Rron Jahja's avatar
Rron Jahja committed
294
}