home.page.ts 10.4 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
import { Router } from '@angular/router';
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

18
export class HomePage implements OnInit {
Rron Jahja's avatar
Rron Jahja committed
19
  private platform: any;
20
  private map: any;
21
  private defaultLayers: any;
22
  private locationsGroup: any;
23
  private currentUserPosition = {lat: 48.783480, lng: 9.180319};
24

25
26
27
  bikes = [];
  bikeApi: Observable<any>;

28
  public isDetailsVisible = false;
29
30
  public selectedBike = { id: 0 };
  public isBikeReserved = false;
31

32
33
  public currentLocationMarker: any;

34
35
  @ViewChild("mapElement", { static: false })
  public mapElement: ElementRef;
36

37
  constructor(private geolocation: Geolocation,
38
    private router: Router,
39
    public restService: RestService,
40
    public httpClient: HttpClient,
41
42
    private storage: Storage,
    private toastService: ToastService) {
43

Rron Jahja's avatar
Rron Jahja committed
44
45
46
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
47
48
49
50
51
52
53
54
55
56
57

    let watch = this.geolocation.watchPosition({ enableHighAccuracy: true, maximumAge: 10000 });
    watch.subscribe((position) => {
      console.log(position.coords.latitude);
      console.log(position.coords.longitude);
      this.currentUserPosition.lat = position.coords.latitude;
      this.currentUserPosition.lng = position.coords.longitude;
      this.currentLocationMarker.setGeometry( {lat:position.coords.latitude, lng:position.coords.longitude})
    }, (errorObj) => {
      console.log(errorObj.code + ": " + errorObj.message);
    });
Rron Jahja's avatar
Rron Jahja committed
58
  }
59

60
61
  ngOnInit() {
  }
62

63
  ngAfterViewInit() {
64
    this.initializeMap();
65
    window.addEventListener('resize', () => this.map.getViewPort().resize());
66
67
68
69
70
    setTimeout(() => {
      window.dispatchEvent(new Event('resize'));  
    },100);
    this.getUserLocation();
    this.getBikesList();
71
72
  }

73
  initializeMap() {
74
    // Obtain the default map types from the platform object
75
    this.defaultLayers = this.platform.createDefaultLayers();
76
    this.map = new H.Map(
77
78
      this.mapElement.nativeElement,
      this.defaultLayers.raster.normal.map,
79
      {
80
        zoom: 17,
81
82
83
        pixelRatio: window.devicePixelRatio || 1
      }
    );
84

85
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));
86
    var ui = H.ui.UI.createDefault(this.map, this.defaultLayers);
87
    ui.removeControl("mapsettings");
88
89
    // create custom map settings (icons on map)
    var customMapSettings = new H.ui.MapSettingsControl({
90
91
92
93
94
95
96
97
98
99
      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
        }
100
      ],
101
102
103
104
105
106
107
      layers: [
        {
          label: "layer.traffic", layer: this.defaultLayers.vector.normal.traffic
        },
        {
          label: "layer.incidents", layer: this.defaultLayers.vector.normal.trafficincidents
        }
108
109
      ]
    });
110
111
112
    ui.addControl("custom-mapsettings", customMapSettings);
    var mapSettings = ui.getControl('custom-mapsettings');
    var zoom = ui.getControl('zoom');
113
    mapSettings.setAlignment('top-right');
114
    zoom.setAlignment('right-top');
115

116
117
118
119
    this.map.getViewPort().setPadding(30, 30, 30, 30);

    // Listen for base layer change event (eg. from satellite to 3D)
    this.map.addEventListener('baselayerchange', (evt) => {
120
121
122
123
124
125
      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 });
      }
126
    });
127

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    // listen for map click event
    this.map.addEventListener('tap', (event) =>{
      console.log(event.type, event.currentPointer.type);
    });

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

  getBikesList() {
    this.geolocation.getCurrentPosition({
      maximumAge: 1000, timeout: 4000,
      enableHighAccuracy: true
    }).then((resp) => {
      let lat = resp.coords.latitude;
      let lng = resp.coords.longitude;

      this.currentUserPosition.lat = resp.coords.latitude;
      this.currentUserPosition.lng = resp.coords.longitude;

      this.storage.get('token').then((token) => {
        let url = 'http://193.196.52.237:8081/bikes' + '?lat=' + lat + '&lng=' + lng;
        const headers = new HttpHeaders().set("Authorization", "Bearer " + token);
        this.bikeApi = this.httpClient.get(url, { headers });
        this.bikeApi.subscribe((resp) => {
          console.log("bikes response", resp);
          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();
        }, (error) => console.log(error));
      });
    }, er => {
      //alert('Can not retrieve location');
    }).catch((error) => {
      //alert('Error getting location - ' + JSON.stringify(error));
    });
  }

  showBikesOnMap() {
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
184
185

    this.map.addObject(this.locationsGroup);
    this.setZoomLevelToPointersGroup();
Rron Jahja's avatar
Rron Jahja committed
186
  }
187

188
  //TODO change this logic
189
  getCurrentPosition() {
190
191
    this.map.setZoom(17);
    this.map.setCenter({ lat: this.currentUserPosition.lat, lng: this.currentUserPosition.lng });
192
  }
193

194
195
196
197
198
199
200
  setZoomLevelToPointersGroup() {
    this.map.getViewModel().setLookAtData({
      bounds: this.locationsGroup.getBoundingBox()
    });
  }

  getUserLocation() {
Rron Jahja's avatar
Rron Jahja committed
201
202
    this.geolocation.getCurrentPosition(
      {
203
        maximumAge: 1000, timeout: 4000,
Rron Jahja's avatar
Rron Jahja committed
204
205
206
        enableHighAccuracy: true
      }
    ).then((resp) => {
207
208
      let lat = resp.coords.latitude;
      let lng = resp.coords.longitude;
209
210
      this.currentUserPosition.lat = resp.coords.latitude;
      this.currentUserPosition.lng = resp.coords.longitude;
211
      this.showUserLocationOnMap(lat, lng);
Rron Jahja's avatar
Rron Jahja committed
212
    }, er => {
213
214
      //alert('Can not retrieve Location')
      this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
Rron Jahja's avatar
Rron Jahja committed
215
    }).catch((error) => {
216
217
      this.showUserLocationOnMap(this.currentUserPosition.lat, this.currentUserPosition.lng);
      //alert('Error getting location - ' + JSON.stringify(error))
Rron Jahja's avatar
Rron Jahja committed
218
219
    });
  }
220

221
222
223
224
225
226
227
228
  showUserLocationOnMap(lat, lng) {
    let svgMarkup = '<svg width="24" height="24" ' +
    'xmlns="http://www.w3.org/2000/svg">' +
    '<circle cx="10" cy="10" r="10" ' +
      'fill="#007cff" stroke="white" stroke-width="2"  />' +
    '</svg>';
    let icon = new H.map.Icon(svgMarkup);
    //let icon = new H.map.Icon('../../../assets/images/current_location.png');
229
    // Create a marker using the previously instantiated icon:
230
    this.currentLocationMarker = new H.map.Marker({ lat: lat, lng: lng }, { icon: icon });
231
    // Add the marker to the map:
232
233
234
235
236
    this.locationsGroup.addObjects([this.currentLocationMarker]);
    this.setZoomLevelToPointersGroup();

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

239
  addMarker(lat, lng, img) {
240
241
242
243
    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:
244
245
246
    //this.map.addObject(marker);

    this.locationsGroup.addObjects([marker]);
247
  }
248
249

  enable3DMaps() {
250
    this.map.setBaseLayer(this.defaultLayers.vector.normal.map);
251
  }
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266

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

268
269
270
271
272
273
274
275
276
      this.bikes[index].address = streets;
      this.bikes[index].HouseNumber = houseNumber;
      this.bikes[index].PostalCode = zipcode;

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

277
  showBikeDetails(bike) {
278
    this.selectedBike = bike;
279
280
    this.isDetailsVisible = true;
  }
281

282
  reserveBike() {
283
284
285
286
287
288
289
    //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);
290
        this.isBikeReserved = true;
291
        this.toastService.showToast("Reservation Successful!");
292
        this.router.navigateByUrl('/myreservation');
293
294
295
296
      }, (error) => {
        console.log(error)
        this.toastService.showToast("Only one bike may be reserved or rented at a time")
      });
297
298
    });
  }
299

Rron Jahja's avatar
Rron Jahja committed
300
}