Subversion Repository Public Repository

Nextrek

Diff Revisions 659 vs 660 for /Android/SmartCharging/SmartCharging_WP/SmartCharging/MapPage.xaml.cs

Diff revisions: vs.
  @@ -1,5 +1,6 @@
1 1 using SmartCharging.Common;
2 2 using SmartCharging.DataModel;
3 + using SmartCharging.Net;
3 4 using System;
4 5 using System.Collections.Generic;
5 6 using System.Collections.ObjectModel;
  @@ -15,6 +16,7 @@
15 16 using Windows.Graphics.Display;
16 17 using Windows.Services.Maps;
17 18 using Windows.Storage.Streams;
19 + using Windows.System;
18 20 using Windows.UI.Core;
19 21 using Windows.UI.Popups;
20 22 using Windows.UI.ViewManagement;
  @@ -41,12 +43,17 @@
41 43 {
42 44 private NavigationHelper navigationHelper;
43 45 private ObservableDictionary defaultViewModel = new ObservableDictionary();
44 - double lat, lon;
45 - int zoom;
46 + private SmartChargeAPI SMA;
47 + private ResourceLoader resourceLoader;
48 + private Config config;
49 + private ErrorHandler errorHandler;
50 + double defaultLat, defaultLon;
51 + int defaultZoom;
46 52
47 53 public event PropertyChangedEventHandler PropertyChanged;
48 -
54 + private SiteType selectedSiteType;
49 55 private Site _selectedSite;
56 +
50 57 Site selectedSite
51 58 {
52 59 get { return _selectedSite; }
  @@ -67,10 +74,10 @@
67 74 this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
68 75 this.navigationHelper.SaveState += this.NavigationHelper_SaveState;
69 76
70 - var resourceLoader = ResourceLoader.GetForCurrentView("Resources");
71 - lat = double.Parse(resourceLoader.GetString("DefaultMapCenterLat"));
72 - lon = double.Parse(resourceLoader.GetString("DefaultMapCenterLon"));
73 - zoom = int.Parse(resourceLoader.GetString("DefaultMapZoom"));
77 + resourceLoader = ResourceLoader.GetForCurrentView("Resources");
78 + config = Config.Instance;
79 + errorHandler = new ErrorHandler();
80 + this.SMA = SmartChargeAPI.Instance;
74 81 }
75 82
76 83 /// <summary>
  @@ -103,46 +110,81 @@
103 110 /// session. The state will be null the first time a page is visited.</param>
104 111 private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
105 112 {
106 - await AskForGps();
107 - //Default : Roma
108 - Geopoint center = new Geopoint(new BasicGeoposition()
113 +
114 + defaultLat = double.Parse(await config.getConfigValueByKey("DefaultMapCenterLat"));
115 + defaultLon = double.Parse(await config.getConfigValueByKey("DefaultMapCenterLon"));
116 + defaultZoom = int.Parse(await config.getConfigValueByKey("DefaultMapZoom"));
117 + SiteType selected = e.NavigationParameter != null ? e.NavigationParameter as SiteType : this.selectedSiteType;
118 + this.selectedSiteType = selected;
119 + Geopoint center = new Geopoint(new BasicGeoposition()
109 120 {
110 - Latitude = lat,
111 - Longitude = lon
121 + Latitude = defaultLat,
122 + Longitude = defaultLon
112 123 });
113 124 MapControl.LandmarksVisible = true;
114 - MapItemsControl.ItemsSource = GetSiteList();
115 - MapControl.Center = center;
116 - MapControl.ZoomLevel = zoom;
125 +
117 126
127 + MapControl.Center = center;
128 + MapControl.ZoomLevel = defaultZoom;
129 + this.showLoading();
118 130 Geopoint userLocation = await GetUserLocation();
119 131 if (userLocation != null)
120 132 {
121 133
122 - zoom = 15;
134 + List<Site> sitesList = await GetSiteList(userLocation, selected);
135 + MapItemsControl.ItemsSource = sitesList;
136 +
137 +
138 + int zoom = 15;
123 139 MapIcon MapIcon1 = new MapIcon();
124 140 MapIcon1.Location = userLocation;
125 141 MapIcon1.NormalizedAnchorPoint = new Point(1.0, 0.5);
126 - MapIcon1.Title = "La tua posizione";
142 + MapIcon1.Title = resourceLoader.GetString("YourPositionMessage");
127 143 MapIcon1.Visible = true;
128 144 MapIcon1.ZIndex = int.MaxValue;
129 145 MapIcon1.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/position.png"));
130 146 MapControl.MapElements.Add(MapIcon1);
131 147 MapControl.Center = userLocation;
132 148 MapControl.ZoomLevel = zoom;
149 + List<Site> ordered = new List<Site>(sitesList.OrderBy( s =>
150 + {
151 + double d = Math.Pow(userLocation.Position.Latitude - s.Position.Position.Latitude, 2) + Math.Pow(userLocation.Position.Longitude - s.Position.Position.Longitude, 2);
152 + return d;
153 + }));
154 +
155 + if (ordered.Count >= 1)
156 + {
157 + await this.setSelectedSite(ordered[0]);
158 + }
159 +
133 160
134 161 }
135 -
136 -
162 + else
163 + {
164 + await this.AskForGps();
165 +
166 + }
167 +
168 + this.hideLoading();
137 169
138 170
139 171 }
140 172
141 173
142 - private List<Site> GetSiteList()
174 + private async Task<List<Site>> GetSiteList(Geopoint position, SiteType type)
143 175 {
144 176
145 - string lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
177 + if (type == null)
178 + {
179 + List<SiteType> sts = await this.SMA.getSiteTypesList();
180 + type = sts[0];
181 + }
182 +
183 +
184 +
185 + return await this.SMA.GetSites(position.Position, 500000, type);
186 +
187 + /*string lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
146 188 ObservableCollection<Review> reviews = new ObservableCollection<Review>();
147 189 reviews.Add(new Review() { ReviewerName = "Fabio", Chargers = 3, Description = lorem });
148 190 reviews.Add(new Review() { ReviewerName = "Marco", Chargers = 4, Description = lorem });
  @@ -157,7 +199,7 @@
157 199 Id = "1",
158 200 Name = "Locale1",
159 201 Chargers = 1,
160 - TypeLabel = "Bar",
202 + Type = new SiteType() { Id = "0", Label = "Bar" },
161 203 Address = "Via di casa mia 54",
162 204 IconImageUrl = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRJJkFIfxS2b_x3Zhv-rcBY3xpnVIdmdaPQ4lIjzpXxWPOLSaHx0GDif9s",
163 205 SiteImageUrls = new List<string>(){"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRJJkFIfxS2b_x3Zhv-rcBY3xpnVIdmdaPQ4lIjzpXxWPOLSaHx0GDif9s",
  @@ -177,7 +219,7 @@
177 219 Id = "2",
178 220 Name = "Locale2",
179 221 Chargers = 3,
180 - TypeLabel = "Ristorante",
222 + Type = new SiteType() { Id = "0", Label = "Ristorante" },
181 223 Address = "Via di casa mia 55",
182 224 IconImageUrl = "http://www.lagrottadiscoteca.it/DISCOTECA/FUMATORI/Grotta8.jpg",
183 225 SiteImageUrls = new List<string>() { "http://www.lagrottadiscoteca.it/DISCOTECA/FUMATORI/Grotta8.jpg" },
  @@ -196,7 +238,7 @@
196 238 Id = "3",
197 239 Name = "Locale3",
198 240 Chargers = 5,
199 - TypeLabel = "Birreria",
241 + Type = new SiteType() { Id = "0", Label = "Birreria" },
200 242 Address = "Via di casa mia 56",
201 243 IconImageUrl = "http://www.lagrottadiscoteca.it/DISCOTECA/FUMATORI/Grotta8.jpg",
202 244 SiteImageUrls = new List<string>(){"http://www.lagrottadiscoteca.it/DISCOTECA/FUMATORI/Grotta8.jpg",
  @@ -216,7 +258,7 @@
216 258 Id = "4",
217 259 Name = "Locale4",
218 260 Chargers = 2,
219 - TypeLabel = "Pizzeria",
261 + Type = new SiteType() { Id = "0", Label = "Pizzeria" },
220 262 Address = "Via di casa mia 57",
221 263 Description = "Locale dove si fuma",
222 264 ReviewList = new ObservableCollection<Review>(reviews.Take(4)),
  @@ -239,7 +281,7 @@
239 281 Name = "Locale5",
240 282 Chargers = 4,
241 283 Address = "Via di casa mia 58",
242 - TypeLabel = "Pub",
284 + Type = new SiteType() { Id = "0", Label = "Pub" },
243 285 IconImageUrl = "http://static.bakeca.it/immagini/641/6414e0e166f53ff07fff82985582a64f.jpg",
244 286 SiteImageUrls = new List<string>(){"http://static.bakeca.it/immagini/641/6414e0e166f53ff07fff82985582a64f.jpg",
245 287 "http://static.bakeca.it/immagini/641/6414e0e166f53ff07fff82985582a64f.jpg","http://static.bakeca.it/immagini/641/6414e0e166f53ff07fff82985582a64f.jpg"},
  @@ -253,7 +295,7 @@
253 295 NormalizedPoint = new Point(.5, .5)
254 296 });
255 297
256 - return POIs;
298 + return POIs;*/
257 299 }
258 300
259 301 /// <summary>
  @@ -296,47 +338,40 @@
296 338 #endregion
297 339
298 340 private async Task<bool> AskForGps(){
299 - var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
300 - if (localSettings.Values.ContainsKey("LocationConsent"))
301 - {
302 - return false;
303 - }
304 - else
305 - {
306 - MessageDialog dialogbox = new MessageDialog("Questa applicazione utilizza il GPS. Desideri consentirne l'uso?");
341 +
342 + MessageDialog dialogbox = new MessageDialog(resourceLoader.GetString("GPSRequestMessage"));
307 343
308 344
309 345 //OK Button
310 - UICommand okBtn = new UICommand("Si");
311 - okBtn.Invoked = (s) => {
312 - localSettings.Values["LocationConsent"] = true; };
346 + UICommand okBtn = new UICommand(resourceLoader.GetString("OK"));
347 + okBtn.Invoked = (s) => {
348 + Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
349 + };
313 350 dialogbox.Commands.Add(okBtn);
314 351
315 - //Cancel Button
316 - UICommand cancelBtn = new UICommand("No");
317 - cancelBtn.Invoked = (s) => {
318 - localSettings.Values["LocationConsent"] = false;
319 - };
320 - dialogbox.Commands.Add(cancelBtn);
321 352
322 353 //Show message
323 354 await dialogbox.ShowAsync();
324 355 return true;
325 - }
356 +
326 357 }
327 358
328 359 private async Task<Geopoint> GetUserLocation()
329 - {
360 + {
361 + /*get user's position;
362 + * if this operation succeeds
363 + * save the position and continue
364 + * else
365 + * retrieve the last save position
366 + * if no last saved position
367 + * show error message
368 + * else
369 + * continue
370 + */
330 371 var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
331 - if (localSettings.Values["LocationConsent"] == null || !(bool)localSettings.Values["LocationConsent"])
332 - {
333 - // The user has opted out of Location.
334 - return null;
335 - }
336 -
337 372 Geolocator geolocator = new Geolocator();
373 + Geopoint ret;
338 374 geolocator.DesiredAccuracyInMeters = 50;
339 -
340 375 try
341 376 {
342 377 Geoposition geoposition = await geolocator.GetGeopositionAsync(
  @@ -344,17 +379,60 @@
344 379 timeout: TimeSpan.FromSeconds(6)
345 380 );
346 381
347 - return new Geopoint(new BasicGeoposition()
382 + ret = new Geopoint(new BasicGeoposition()
348 383 {
349 384 Latitude = geoposition.Coordinate.Point.Position.Latitude,
350 385 Longitude = geoposition.Coordinate.Point.Position.Longitude
351 386 });
387 + this.SavePosition(ret);
352 388
353 389 }
354 - catch (Exception ex)
390 + catch
355 391 {
356 - return null;
392 + ret = this.GetLastSavedPosition();
357 393 }
394 +
395 +
396 + return ret;
397 + }
398 +
399 + private Geopoint GetLastSavedPosition()
400 + {
401 + var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
402 + string toBeParsed = (string)localSettings.Values["LastSavedPostition"];
403 + Geopoint ret = null;
404 + if (toBeParsed != null && !toBeParsed.Equals(""))
405 + {
406 + ret = new Geopoint(new BasicGeoposition() {
407 + Latitude = double.Parse(toBeParsed.Split('|')[0]),
408 + Longitude = double.Parse(toBeParsed.Split('|')[1])
409 + });
410 + }
411 + return ret;
412 + }
413 +
414 + private void SavePosition(Geopoint position)
415 + {
416 + var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
417 +
418 + localSettings.Values["LastSavedPostition"] = position.Position.Latitude + "|" + position.Position.Longitude;
419 +
420 +
421 +
422 + }
423 +
424 + /*load data for the selected site and apply it as datacontext for ui binding*/
425 + private async Task setSelectedSite(Site site){
426 + /*load details only once*/
427 + if (site.Description == null )
428 + {
429 + this.showLoading();
430 + await this.SMA.GetSiteDetailsAndReviews(site, 10);
431 + this.hideLoading();
432 + }
433 +
434 + this.selectedSite = site;
435 + LayoutRoot.DataContext = this.selectedSite;
358 436 }
359 437
360 438 public void NotifyPropertyChanged(string propertyName)
  @@ -376,9 +454,7 @@
376 454
377 455 var data = ((Control)sender).DataContext;
378 456 Site s = (Site)data;
379 - this.selectedSite = s;
380 -
381 - LayoutRoot.DataContext = this.selectedSite;
457 + await this.setSelectedSite(s);
382 458 bool res = await MapControl.TrySetViewAsync(s.Position, MapControl.ZoomLevel, 0, 0, MapAnimationKind.Linear);
383 459 }
384 460
  @@ -392,5 +468,25 @@
392 468 var aw = Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
393 469 () => this.Frame.Navigate(typeof(NewReviewPage), this.selectedSite));
394 470 }
471 +
472 + private void Image_Tapped(object sender, TappedRoutedEventArgs e)
473 + {
474 + FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
475 + }
476 +
477 + private void Image_Flyout_Tapped(object sender, TappedRoutedEventArgs e)
478 + {
479 + this.ImagePreviewFlyout.Hide();
480 + }
481 +
482 + private void showLoading()
483 + {
484 + this.Loader.Visibility = Visibility.Visible;
485 + }
486 +
487 + private void hideLoading()
488 + {
489 + this.Loader.Visibility = Visibility.Collapsed;
490 + }
395 491 }
396 492 }