Subversion Repository Public Repository

Nextrek

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//
//  MapViewController.m
//  Location
//
//  Created by Fabrizio on 03/12/12.
//  Copyright (c) 2012 Odyssey. All rights reserved.
//

#import "MapViewController.h"
#import "MapAnnotation.h"
#import "MKCustomAnnotationView.h"
#import "MapItemDetailVC.h"
#import "NetService.h"
#import "TableCell.h"

#define METERS_PER_MILE 1609.344

@interface MapViewController () {
    MapItem *mapItem;
    
    UIImage *tableImage;
    UIImage *mapImage;
    
    NSTimer *routetimer;
}

@end

@implementation MapViewController

@synthesize mapItems;
@synthesize annotations;
@synthesize locateBtn;
@synthesize mapListBtn;
@synthesize nearestBtn;
@synthesize map;
@synthesize resultsTableView;
@synthesize waitingView;
@synthesize activityIndicator;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    nearestBtn.enabled = NO;
        
    if([DataManager getInstance].lastLocation) {
        
        nearestBtn.enabled = YES;
        
        CLLocationCoordinate2D coord = {.latitude = [DataManager getInstance].lastLocation.coordinate.latitude ,
                                    .longitude = [DataManager getInstance].lastLocation.coordinate.longitude};
        
        MKCoordinateSpan span = {.latitudeDelta = 0.05, .longitudeDelta = 0.05};
        MKCoordinateRegion region = {coord, span};
        [map setRegion:region];
    }
    else {
    
        [self activeLocationManager];
        [self doAddMapItems];
    }
}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:NO];
    
    if(!bannerView_){
        bannerView_ = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
    }
    
    bannerView_.adUnitID = BANNER_ID;
    bannerView_.rootViewController = self;
    [self.view addSubview:bannerView_];
    
    [bannerView_ setDelegate:self];
    
    [bannerView_ loadRequest:[GADRequest request]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
        
    tableImage = [UIImage imageNamed:@"menu.png"];
    mapImage = [UIImage imageNamed:@"map.png"];
    
    [mapListBtn setImage:tableImage forState:UIControlStateNormal];
	
	annotations = [NSMutableArray arrayWithCapacity:0];
   
    MKCoordinateSpan span = {.latitudeDelta = 11.984136506562237, .longitudeDelta = 14.0625};
	MKCoordinateRegion region;
	region.center.latitude = 42,98399427093392;
	region.center.longitude = 12,2607421875;
	region.span = span;
	[map setRegion:region animated:YES];
    
	firstTime = YES;
}

#pragma mark -
#pragma mark AdView Network handle

- (void)adViewDidReceiveAd:(GADBannerView *)bannerView {
    NSLog(@"adView:adViewDidReceiveAd");
    [UIView beginAnimations:@"BannerSlide" context:nil];

    bannerView.frame = CGRectMake(0.0, 0.0, bannerView.frame.size.width, bannerView.frame.size.height);
    
    map.frame = CGRectMake(0.0, 50.0, map.frame.size.width, map.frame.size.height);
    resultsTableView.frame = CGRectMake(0.0, 50.0, resultsTableView.frame.size.width, resultsTableView.frame.size.height);
    waitingView.frame = CGRectMake(0.0, 50.0, waitingView.frame.size.width, waitingView.frame.size.height);
    
    [UIView commitAnimations];
}

- (void)adView:(GADBannerView *)bannerView didFailToReceiveAdWithError:(GADRequestError *)error {
    NSLog(@"adView:didFailToReceiveAdWithError:%@", [error localizedDescription]);
    
    [UIView beginAnimations:@"BannerSlideOff" context:nil];

    bannerView.frame = CGRectMake(0.0, -70.0, bannerView.frame.size.width, bannerView.frame.size.height);

    map.frame = CGRectMake(0.0, -20.0, map.frame.size.width, map.frame.size.height);
    resultsTableView.frame = CGRectMake(0.0, 0.0, resultsTableView.frame.size.width, resultsTableView.frame.size.height);
    waitingView.frame = CGRectMake(0.0, -20.0, waitingView.frame.size.width, waitingView.frame.size.height);
    
    [UIView commitAnimations];
}

#pragma mark -
#pragma mark Waiting View Handle

- (void) startWaiting {
    waitingView.hidden = NO;
    [activityIndicator startAnimating];
}

- (void) stopWaiting {
    waitingView.hidden = YES;
    [activityIndicator stopAnimating];
}

#pragma mark -
#pragma mark locationManager methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

	lastLocation = newLocation;
	[DataManager getInstance].lastLocation = lastLocation;
	
	if(firstTime) {
		[self doAroundMe];
		firstTime = NO;
	}
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

    if (locationManager) {
		[locationManager stopUpdatingLocation];
		locationManager = nil;
	}
}

- (void)activeLocationManager {
	if (!locationManager) {
        [self startWaiting];
        
		locationManager = [[CLLocationManager alloc] init];
		locationManager.delegate = self;
		[locationManager startUpdatingLocation];
		
		map.showsUserLocation = YES;
	}
}

#pragma mark -
#pragma mark Add Map Items

- (void) doAddMapItems {
    
    NSMutableArray *tempMapItemsArray = [[NSMutableArray alloc] initWithArray:[DataManager getInstance].mapItems];
    
    mapItems = tempMapItemsArray;
    
    // ----- +++++ ***** +++++ -----
    //Calulate standard deviation
    float meanLat = 0.0;
    float meanLon = 0.0;
    
    for (MapItem *store in tempMapItemsArray) {
        meanLat += store.lat;
        meanLon += store.lon;
    }
    
    meanLat = meanLat / [tempMapItemsArray count];
    meanLon = meanLon / [tempMapItemsArray count];
    
    float tempLat = 0.0;
    float tempLon = 0.0;
    
    for (MapItem *store in tempMapItemsArray) {
        tempLat += pow((store.lat - meanLat), 2);
        tempLon += pow((store.lon - meanLon), 2);
    }
    
    float sdLat = sqrt(tempLat/[tempMapItemsArray count]);
    float sdLon = sqrt(tempLon/[tempMapItemsArray count]);
    float modSD = sqrt(pow(sdLat,2) + pow(sdLon,2));
    
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    
    for (MapItem *aMapItem in tempMapItemsArray) {
        float tempMod = sqrt(pow((aMapItem.lat - meanLat),2) + pow((aMapItem.lon - meanLon), 2));
        if (tempMod > 2 * modSD) {
            //Index set for Vodafone shops that are outside the Standard Deviation
            [indexSet addIndex:[tempMapItemsArray indexOfObject:aMapItem]];
        }
    }
    
    [tempMapItemsArray removeObjectsAtIndexes:indexSet];
    
    meanLat = 0.0;
    meanLon = 0.0;
    
    for (MapItem *store in tempMapItemsArray) {
        meanLat += store.lat;
        meanLon += store.lon;
    }
    
    meanLat = meanLat / [tempMapItemsArray count];
    meanLon = meanLon / [tempMapItemsArray count];
    
    // ----- +++++ ***** +++++ -----
    
    MapItem *mapItemMin = nil;
    
    [map removeAnnotations:annotations];
    
    float maxLat =- 100000;
    float maxLon =- 100000;
    float minLat =+ 100000;
    float minLon =+ 100000;
    
    for (MapItem *aMapItem in tempMapItemsArray) {
        if (aMapItem.distance>=0) {
            if ((!mapItemMin) || aMapItem.distance < mapItemMin.distance) {
                mapItemMin = aMapItem;
            }
        }
        
        if (aMapItem.lat > maxLat) {
            maxLat = aMapItem.lat;
        }
        if (aMapItem.lat < minLat) {
            minLat = aMapItem.lat;
        }
        if (aMapItem.lon > maxLon) {
            maxLon = aMapItem.lon;
        }
        if (aMapItem.lon < minLon) {
            minLon = aMapItem.lon;
        }
    }
    
    MKCoordinateRegion region;
    
    if (!mapItemMin) {
        mapItemMin = [mapItems objectAtIndex:0];
    }
    
    if (isSearchingAroundMe) {
        region.span.latitudeDelta = (maxLat-minLat);
        region.span.longitudeDelta = (maxLon-minLon);
        region.center.latitude =  meanLat; //lastLocation.coordinate.latitude;
        region.center.longitude = meanLon; //lastLocation.coordinate.longitude;
        isSearchingAroundMe = NO;
    }
    else {
        region.span.latitudeDelta =  (maxLat-minLat);
        region.span.longitudeDelta = (maxLon-minLon);
        region.center.latitude = meanLat;
        region.center.longitude = meanLon;
    }
    
    [map setRegion:region animated:YES];
    
    [NSTimer scheduledTimerWithTimeInterval: 1
                                     target: self
                                   selector: @selector(addAnnotations:)
                                   userInfo: mapItems
                                    repeats: NO];
}

#pragma mark -
#pragma mark IBActions

- (IBAction) pickOne:(id)sender {
	if (map.hidden) {
		map.hidden = NO;
		resultsTableView.hidden = YES;
        locateBtn.enabled = YES;
        [mapListBtn setImage:tableImage forState:UIControlStateNormal];
	}
	else {
        map.hidden = YES;
		resultsTableView.hidden = NO;
        locateBtn.enabled = NO;
        [mapListBtn setImage:mapImage forState:UIControlStateNormal];
	}
}

- (IBAction) doAroundMe {
    
    [self startWaiting];
    
	[self activeLocationManager];
	
	if (lastLocation) {		
		map.showsUserLocation = YES;
		isSearchingAroundMe = YES;
        
        [self doAddMapItems];
	}
}

- (IBAction) doSelectNearest {
    
    MapItem *mapItemForDetail = [[DataManager getInstance].mapItems objectAtIndex:0];
    
    [self goToDetail:mapItemForDetail origin:3];
}

#pragma mark -
#pragma mark MapItemDetail

- (void) goToDetail:(MapItem*)aMapItem origin:(int)aOrigin{
    
    if (! mapItemDetailVC) {
		mapItemDetailVC = [[MapItemDetailVC alloc] initWithMapItem:aMapItem];
	}
    else {
    	mapItemDetailVC.mapItem = aMapItem;
    }

    mapItemDetailVC.origin = aOrigin;
	[self.navigationController pushViewController:mapItemDetailVC animated:YES];
}

#pragma mark -
#pragma mark MapView methods

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    
    NSMutableArray *sortedArray = [NSMutableArray array];
    
    for (MKAnnotationView *annotationView in views) {
        if (annotationView.annotation == mapView.userLocation) {
            
            nearestBtn.enabled = YES;
            
            CLLocationDegrees latitude = mapView.userLocation.coordinate.latitude;
            CLLocationDegrees longitude = mapView.userLocation.coordinate.longitude;
            
            CLLocation *locA = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
            CLLocation *locB;
            
            MapItem *itemToUse;
            
            for(MapItem *item in [DataManager getInstance].mapItems) {
                
                locB = [[CLLocation alloc] initWithLatitude:item.lat longitude:item.lon];
                CLLocationDistance distance = [locA distanceFromLocation:locB];
                
                itemToUse = ((MapItem*)[[DataManager getInstance].mapItems objectAtIndex:[[DataManager getInstance].mapItems indexOfObject:item]]);
                
                itemToUse.distance = distance;
                
                [sortedArray addObject:itemToUse];
                
            }
            
            NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:true];
            NSArray *sa = [sortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
            
            [[DataManager getInstance].mapItems removeAllObjects];
            
            [DataManager getInstance].mapItems = [sa mutableCopy];
            
            [resultsTableView reloadData];
            
            // 1.0 == 111Km
            MKCoordinateSpan span = MKCoordinateSpanMake(0.05, 0.05);
            MKCoordinateRegion region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span);
            [mapView setRegion:region animated:YES];
            
            
            [NSTimer scheduledTimerWithTimeInterval: 5
                                             target: self
                                           selector: @selector(addAnnotations:)
                                           userInfo: mapItems
                                            repeats: NO];
        }
    }
}

- (void)addAnnotations:(NSTimer*)theTimer {
    
	for (MapItem *aMapItem in theTimer.userInfo) {
		CLLocationCoordinate2D coord = {.latitude = aMapItem.lat , .longitude = aMapItem.lon};
        		
        MapAnnotation *mapItemAnnotation = [[MapAnnotation alloc] initWithCoordinate:coord  item:aMapItem];
		[map addAnnotation:mapItemAnnotation];
		[annotations addObject:mapItemAnnotation];
	}
    
    [NSTimer scheduledTimerWithTimeInterval: 2
                                     target: self
                                   selector: @selector(stopWaiting)
                                   userInfo: nil
                                    repeats: NO];
}

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation {
	
	if (! [annotation isKindOfClass:[MapAnnotation class]]) {
		return nil;
	}
    
	MKCustomAnnotationView *annView = [[MKCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
	
	annView.frame = CGRectMake(0, 0, 38, 37);
	annView.canShowCallout = YES;

	NSString *imgName = @"map_ico.png";
	
    annView.image = [UIImage imageNamed:imgName];
	annView.rightCalloutAccessoryView = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
    
	return annView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView calloutAccessoryControlTapped:(UIControl *)control {
    
	MapItem *mapItemForDetail = ((MapAnnotation *)(annotationView.annotation)).mapItem;
	
    [self goToDetail:mapItemForDetail origin:1];
}

#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[DataManager getInstance].mapItems count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"TableCell";
	
	TableCell *cell = (TableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	if (cell == nil)	{
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:MyIdentifier owner:self options:nil];
		cell = [topLevelObjects objectAtIndex:0];
	}

    [cell setGrayAndWhiteAlternateRow:indexPath.row];

    MapItem *mapItemForCell = [[DataManager getInstance].mapItems objectAtIndex:indexPath.row];
    cell.indirizzoLabel.text = [NSString stringWithFormat:@"%@, %@", mapItemForCell.indirizzo, mapItemForCell.numero];
    
    
	if (mapItemForCell.distance >= 0) {
		cell.distanzaLabel.text = [NSString stringWithFormat:@"%0.1f Km",(mapItemForCell.distance / 1000.0f)];
	}
	else {
		cell.distanzaLabel.text = @"";
	}
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MapItem *mapItemForDetail = [[DataManager getInstance].mapItems objectAtIndex:indexPath.row];
    
    [self goToDetail:mapItemForDetail origin:2];
	
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

}

@end

Commits for Nextrek/iOS/Location/Location/VC/MapViewController.m

Diff revisions: vs.
Revision Author Commited Message
63 FAquili picture FAquili Sat 18 Jan, 2014 16:59:40 +0000

Parcheggio Roma 1.0