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


Rron Jahja's avatar
Rron Jahja committed
9
declare var H: any;
10

Rron Jahja's avatar
Rron Jahja committed
11
12
13
14
15
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
16

Rron Jahja's avatar
Rron Jahja committed
17
export class HomePage {
Rron Jahja's avatar
Rron Jahja committed
18
  private platform: any;
19
  private map: any;
20
  bikes = [];
21
  streets = [];
22
23
  bikeApi: Observable<any>;

24

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

27
28
29
30
31
32
33
  public is3DChecked = false;

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

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


42
 
43

44
45
  constructor(private geolocation: Geolocation,
    public restService: RestService,
46
47
    public httpClient: HttpClient,
    private storage: Storage) {
48

Rron Jahja's avatar
Rron Jahja committed
49
50
51
52
    this.platform = new H.service.Platform({
      'apikey': 'tiVTgBnPbgV1spie5U2MSy-obhD9r2sGiOCbBzFY2_k'
    });
  }
53

54
55
56
  ngOnInit() {
    this.getBikesList();
  }
57

58
  ngAfterViewInit() {
Rron Jahja's avatar
Rron Jahja committed
59
    setTimeout(() => {
60
      this.loadmap("2D");
61
    }, 200);
62
63
64
65

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

66
  getBikesList() {
67
    this.geolocation.getCurrentPosition({
68
      maximumAge: 1000, timeout: 1000,
69
70
      enableHighAccuracy: true
    }).then((resp) => {
71
72
      this.currentLocation.lat = resp.coords.latitude;
      this.currentLocation.lng = resp.coords.longitude;
73

74
75
76
77
78
      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) => {
79
          console.log('my data: ', resp);
80
          this.bikes = resp;
81
82
83
84
85
86
87
88
          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);
          }
89
        }, (error) => console.log(error));
90
      });
91
92
93
94
95
96
97
    }, er => {
      alert('Can not retrieve Location')
    }).catch((error) => {
      alert('Error getting location - ' + JSON.stringify(error))
    });
  }

98
99
100
101




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

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

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


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

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

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

207

208

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

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

  enable3DMaps() {
    this.is3DChecked = true;
    setTimeout(() => {
      this.loadmap("3D");
    }, 100);
  }
233
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
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 => {
      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);
    });
  }









Rron Jahja's avatar
Rron Jahja committed
267
}