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

25

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

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

  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 }]
38
  public arrayLanLon = { lat: 0, lng: 0 };
39
40
41
42
43
44
45
  @ViewChild("mapElement2d", { static: false })
  public mapElement2d: ElementRef;

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


46
 
47

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

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

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

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

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

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

79
80
81
82
83
      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) => {
84
          console.log('my data: ', resp);
85
          this.bikes = resp;
86
87
88
89
90
91
92
93
          for (let i = 0; i < this.bikes.length; i++) {
            var beforeDotStr = ''+this.bikes[i].distance;
            var beforeDot = beforeDotStr.split('.')[0];
            var afterDotArr = beforeDotStr.split('.')[1].split('');
            var afterDot = afterDotArr[0] + afterDotArr[1];
            this.bikes[i].distance = beforeDot + '.' + afterDot; 
            this.reverseGeocode(this.platform, this.bikes[i].lat, this.bikes[i].lon, i);
          }
94
        }, (error) => console.log(error));
95
      });
96
97
98
99
100
101
102
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }

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

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

148
    mapSettings.setAlignment('top-right');
149
    zoom.setAlignment('right-top');
150
151
    if (style === "3D") {
      this.map.getViewModel().setLookAtData({ tilt: 60 });
152
    }
153
    this.getLocation(this.map);
154
155
156


    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'];
157
    for (let i = 0; i < this.bikes.length; i++) {
158
      if (this.bikes[i].batteryPercentage < 100 && this.bikes[i].batteryPercentage >= 75) {
159
160
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[0]);
      }
161
      else if (this.bikes[i].batteryPercentage < 75 && this.bikes[i].batteryPercentage >= 50) {
162
163
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[1]);
      }
164
      else if (this.bikes[i].batteryPercentage < 50 && this.bikes[i].batteryPercentage >= 25) {
165
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[2]);
166
      } else if (this.bikes[i].batteryPercentage < 25 && this.bikes[i].batteryPercentage >= 0) {
167
168
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[3]);
      }
169
    
170
    }
Rron Jahja's avatar
Rron Jahja committed
171
  }
172
  getCurrentPosition() {
173
174
    this.getLocation(this.map.setZoom(17));
    
175
  }
176
  
Rron Jahja's avatar
Rron Jahja committed
177
178
179
  getLocation(map) {
    this.geolocation.getCurrentPosition(
      {
180
        maximumAge: 1000, timeout: 2000,
Rron Jahja's avatar
Rron Jahja committed
181
        enableHighAccuracy: true
182
        
Rron Jahja's avatar
Rron Jahja committed
183
184
185
186
      }
    ).then((resp) => {
      let lat = resp.coords.latitude
      let lng = resp.coords.longitude
187
188
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
Rron Jahja's avatar
Rron Jahja committed
189
190
191
192
193
194
195
      this.moveMapToGiven(map, lat, lng);
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }
196

Rron Jahja's avatar
Rron Jahja committed
197
  moveMapToGiven(map, lat, lng) {
198

199
    var icon = new H.map.Icon('../../../assets/images/current_location.png');
200
201
202
203
204
    // 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
205
206
    map.setCenter({ lat: lat, lng: lng });
  }
207

208

209

210
  addMarker(lat, lng, img) {
211
212
213
214
215
216
217
    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);
  }
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

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

  enable3DMaps() {
    this.is3DChecked = true;
    setTimeout(() => {
      this.loadmap("3D");
    }, 100);
  }
234

235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  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;
     
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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


262
  showBikeDetails(bike) {
263

264
    this.selectedBike=bike;
265
    this.selectedBike.id=bike.id;
266
267
    this.isDetailsVisible = true;
  }
268
  reserveBike() {
269
270
271
272
273
274
275
    //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);
276
277
278
279
280
281
        this.isBikeReserved=true;
        this.toastService.showToast("Reservation Successful!");
      }, (error) => {
        console.log(error)
        this.toastService.showToast("Only one bike may be reserved or rented at a time")
      });
282
283
    });
 
284

285
  }
Priyanka Upadhye's avatar
Priyanka Upadhye committed
286
 
287
  
288

Rron Jahja's avatar
Rron Jahja committed
289
}