home.page.ts 10.3 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

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
38
  constructor(private geolocation: Geolocation,
    public restService: RestService,
39
    public httpClient: HttpClient,
40
41
    private storage: Storage,
    private toastService: ToastService) {
42

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

    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
57
  }
58

59
60
  ngOnInit() {
  }
61

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

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

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

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

    // Listen for base layer change event (eg. from satellite to 3D)
    this.map.addEventListener('baselayerchange', (evt) => {
119
120
121
122
123
124
      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 });
      }
125
    });
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
    // 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() {
168
    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'];
169
    for (let i = 0; i < this.bikes.length; i++) {
170
      if (this.bikes[i].batteryPercentage < 100 && this.bikes[i].batteryPercentage >= 75) {
171
172
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[0]);
      }
173
      else if (this.bikes[i].batteryPercentage < 75 && this.bikes[i].batteryPercentage >= 50) {
174
175
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[1]);
      }
176
      else if (this.bikes[i].batteryPercentage < 50 && this.bikes[i].batteryPercentage >= 25) {
177
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[2]);
178
      } else if (this.bikes[i].batteryPercentage < 25 && this.bikes[i].batteryPercentage >= 0) {
179
180
        this.addMarker(Number(this.bikes[i].lat), Number(this.bikes[i].lon), img[3]);
      }
181
    }
182
183
184

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

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

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

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

220
221
222
223
224
225
226
227
  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');
228
    // Create a marker using the previously instantiated icon:
229
    this.currentLocationMarker = new H.map.Marker({ lat: lat, lng: lng }, { icon: icon });
230
    // Add the marker to the map:
231
232
233
234
235
    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
236
  }
237

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

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

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

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

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

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

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

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

Rron Jahja's avatar
Rron Jahja committed
298
}