-
Notifications
You must be signed in to change notification settings - Fork 1
/
MappaAPI.m
executable file
·2043 lines (1392 loc) · 67.4 KB
/
MappaAPI.m
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Mappa.m
// Acqualta VE
//
// Created by Francesco Piero Paolicelli on 11/04/11.
// Copyright 2011 piersoft.it. All rights reserved.
//
#import "MyAnnotation.h"
#import "UserProfileVC.h"
#import "MappaAPI.h"
#import "shopPoint.h"
#import "ViewArticolo.h"
#import "asyncimageview.h"
#import "NSString+SBJSON.h"
#import "TileOverlay.h"
#import "TileOverlayView.h"
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
@implementation MappaAPI
//@synthesize window=_window;
@synthesize mapView,userProfileVC;
@synthesize segmentposizione,cmdMiaPosizione,indirizzoshare,feed,feedsubtit,feedlat,feedlon,titlemap,toolbar,barra,linkdapassare,overlay,tracks;
@synthesize lineColor, origine, destinazione;
- (IBAction)osmclass
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.openstreetmap.org/copyright"]];
}
- (IBAction)gestioneZoom:(id)sender{
//if (switchZoom.on){
mapView.zoomEnabled=TRUE;
/*} else {
mapView.zoomEnabled=FALSE;
}*/
}
- (IBAction)gestioneScroll:(id)sender{
//if (switchScroll.on){
mapView.scrollEnabled=TRUE;
/*} else {
mapView.scrollEnabled=FALSE;
}*/
}
#pragma mark -
#pragma mark View lifecycle
+ (CGFloat)annotationPadding;
{
return 10.0f;
}
+ (CGFloat)calloutHeight;
{
return 40.0f;
}
-(IBAction) scegliPercorso
{
//NSLog(@"ActionSheetViewController::alert");
// appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
UIActionSheet *actionsheet = [[UIActionSheet alloc]
initWithTitle:@"Vuoi calcolare il percorso? Verrà attivato il GPS"
delegate:self
cancelButtonTitle:@"Annulla"
destructiveButtonTitle:nil
otherButtonTitles: @"Percorso in macchina",@"Percorso a piedi",
nil
];
//[actionsheet showInView:[self view]];
[actionsheet showInView:self.view];
[actionsheet release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"button %li clicked", (long)buttonIndex );
self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
_hud.labelText = @"";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self performSelector:@selector(timeout:) withObject:nil afterDelay:10];
segmentposizione.selectedSegmentIndex=1;
mapView.showsUserLocation = YES;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//calcolo il percorso
switch (buttonIndex) {
case 0: {
mytimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(macchina) userInfo:nil repeats:NO];
break;
}
case 1:{
mytimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(piedi) userInfo:nil repeats:NO];
break;
}
default: break;
}
}
-(void)macchina{
[self showRouteFrom:origine to:destinazione typePath:nil];
}
-(void)piedi{
[self showRouteFrom:origine to:destinazione typePath:@"w"];
}
- (void)dismissHUD:(id)arg {
[MBProgressHUD hideHUDForView:self.view animated:YES];
self.hud = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)timeout:(id)arg {
_hud.labelText = nil;
_hud.detailsLabelText = nil;
_hud.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
_hud.mode = MBProgressHUDModeCustomView;
[self performSelector:@selector(dismissHUD:) withObject:nil afterDelay:0.5];
// [self.tableView reloadData];
}
- (void)gotoLocation
{
// start off by default in Venezia
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.4301;
newRegion.center.longitude = 12.3260;
//MKCoordinateSpan span;
//span.latitudeDelta=0.3;
//span.longitudeDelta=0.3;
newRegion.span.latitudeDelta = 0.2;
newRegion.span.longitudeDelta = 0.2;
[self.mapView setRegion:newRegion animated:YES];
}
-(void)gotoosm{
overlay = [[TileOverlay alloc] initOverlay];
[mapView addOverlay:overlay];
MKMapRect visibleRect = [mapView mapRectThatFits:overlay.boundingMapRect];
visibleRect.size.width /= 2;
visibleRect.size.height /= 2;
visibleRect.origin.x += visibleRect.size.width / 2;
visibleRect.origin.y += visibleRect.size.height / 2;
mapView.visibleMapRect = visibleRect;
// start off by default in Venezia
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.4301;
newRegion.center.longitude = 12.3260;
//MKCoordinateSpan span;
//span.latitudeDelta=0.3;
//span.longitudeDelta=0.3;
newRegion.span.latitudeDelta = 0.2;
newRegion.span.longitudeDelta = 0.2;
[self.mapView setRegion:newRegion animated:YES];
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)ovl
{
TileOverlayView *view = [[TileOverlayView alloc] initWithOverlay:ovl];
view.tileAlpha = 1.0; // e.g. 0.6 alpha for semi-transparent overlay
return [view autorelease];
}
#pragma mark ADBannerViewDelegate
- (void)parseXMLFileAtURL:(NSString *)URL {
// inizializziamo la lista degli elementi
elencoFeed = [[NSMutableArray alloc] init];
// dobbiamo convertire la stringa "URL" in un elemento "NSURL"
NSURL *xmlURL = [NSURL URLWithString:URL];
// inizializziamo il nostro parser XML
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
// settiamo alcune proprietà
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
// avviamo il parsing del feed RSS
[rssParser parse];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:@"item"]) {
// inizializza tutti gli elementi
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentCategory = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentLink = [[NSMutableString alloc] init];
currentImage = [[NSMutableString alloc] init];
currentLat= [[NSMutableString alloc] init];
currentLong= [[NSMutableString alloc] init];
currentCheck =[[NSMutableString alloc] init];
currentAddr =[[NSMutableString alloc] init];
currentWWW = [[NSMutableString alloc] init];
currentEmail = [[NSMutableString alloc] init];
}
else if ([currentElement isEqualToString:@"enclosure"])
{
currentImage = [[NSMutableString alloc] init];
[currentImage appendString:[attributeDict objectForKey:@"url"]];
}
/*
else if ([currentElement isEqualToString:@"media:content"])
{
[currentImage appendString:[attributeDict objectForKey:@"url"]];
}
*/
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"item"]) {
/* salva tutte le proprietà del feed letto nell'elemento "item", per
poi inserirlo nell'array "elencoFeed" */
[item setObject:currentTitle forKey:@"title"];
[item setObject:currentLink forKey:@"link"];
[item setObject:currentSummary forKey:@"summary"];
[item setObject:currentCheck forKey:@"phone"];
[item setObject:currentCategory forKey:@"category"];
[item setObject:currentAddr forKey:@"addr"];
[item setObject:currentImage forKey:@"image"];
[item setObject:currentWWW forKey:@"www"];
[item setObject:currentEmail forKey:@"email"];
[item setObject:currentLong forKey:@"longitudine"];
[item setObject:currentLat forKey:@"latitudine"];
// par=par+1;
// _hud.labelText = [NSString stringWithFormat: @"%f", (float)par/ (float) 150*100];
// NSLog(@"textperce %@",_hud.labelText);
[elencoFeed addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { ;
// salva i caratteri per l'elemento corrente
if ([currentElement isEqualToString:@"title"]){
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:@"link"]) {
[currentLink appendString:string];
} else if ([currentElement isEqualToString:@"description"])
{
[currentSummary appendString:string];
}else if ([currentElement isEqualToString:@"indirizzo"])
{
[currentAddr appendString:string];
} else if ([currentElement isEqualToString:@"category"]) {
[currentCategory appendString:string];
//NSCharacterSet* charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@" \n"];
//[self.currentImage setString: [currentImage stringByTrimmingCharactersInSet: charsToTrim]];
}
else if ([currentElement isEqualToString:@"content:encoded"])
{
// [currentImage appendString:string];
}else if ([currentElement isEqualToString:@"website"])
{
[currentWWW appendString:string];
} else if ([currentElement isEqualToString:@"email"])
{
[currentEmail appendString:string];
}
else if ([currentElement isEqualToString:@"latitudine"])
{
[currentLat appendString:string];
}
else if ([currentElement isEqualToString:@"longitudine"])
{
[currentLong appendString:string];
}
else if ([currentElement isEqualToString:@"telefono"])
{
[currentCheck appendString:string];
}
}
-(void)stophud{
// [self performSelectorInBackground:@selector(dismissHUD:) withObject:nil];
mytimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissHUD:) userInfo:nil repeats:NO];
}
- (void) parserDidEndDocument:(NSXMLParser *)parser {
// [MBProgressHUD hideHUDForView:self.view animated:YES];
// self.hud = nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// [self performSelector:@selector(timeout:) withObject:nil afterDelay:2];
[UIApplication sharedApplication].statusBarStyle=UIBarStyleDefault;
// [self performSelector:@selector(zoom) withObject:nil afterDelay:0];
// destinazione = [[Place alloc] init];
shopPoints = [[NSMutableArray alloc] init];
shopPoint *myAnnotation;
for (int i=0; i<=[elencoFeed count]-1; i++) {
// [MBProgressHUD hideHUDForView:self.view animated:YES];
// self.hud = nil;
// self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
par=i;
_hud.labelText = [NSString stringWithFormat: @"%f", (float)par/ (float)[elencoFeed count]*100];
// NSLog(@"textperce %@",_hud.labelText);
// NSLog(@"float %f",(float)par/ (float)[elencoFeed count]*100);
// if (i==[elencoFeed count]-1 && [feed rangeOfString:@"cat=-5%2C16,-19,-21"].length==0) {
if (i==[elencoFeed count]-1 ) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
// self.hud = nil;
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in shopPoints) {
// NSLog(@"Vai verso l'insieme dei POI centrando la mappa");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
//NSLog(@"else-%@",annotationPoint.x);
}
}
/*
mapView.visibleMapRect = flyTo;
MKCoordinateRegion region;
//Set Zoom level using Span
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
MKCoordinateSpan span;
region.center=mapView.region.center;
span.latitudeDelta=mapView.region.span.latitudeDelta *1.2;
span.longitudeDelta=mapView.region.span.longitudeDelta *1.2;
region.span=span;
[UIView setAnimationDuration:0.50];
[mapView setRegion:region animated:YES];
[UIView commitAnimations];
*/
// [self performSelector:@selector(zoom) withObject:nil afterDelay:2];
// [self performSelector:@selector(timeout:) withObject:nil afterDelay:2];
}
NSString *title=[[elencoFeed objectAtIndex:i] objectForKey:@"title"];
NSString *addr=[[elencoFeed objectAtIndex:i] objectForKey:@"addr"];
addr=[addr stringByReplacingOccurrencesOfRegex:@"\n" withString:@""];
/*
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
title = [title stringByReplacingOccurrencesOfString:@" " withString:@""];
*/
title= [title stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSString *link=[[elencoFeed objectAtIndex:i] objectForKey:@"link"];
link=[link stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// NSString *check=[[elencoFeed objectAtIndex:i] objectForKey:@"descrizione"];
// check=[check stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *subtitle=[[elencoFeed objectAtIndex:i] objectForKey:@"category"];
subtitle=[subtitle stringByReplacingOccurrencesOfRegex:@"\n" withString:@""];
// if ([subtitle rangeOfString:@"Sede"].length != 0 )
// {
subtitle=addr;
// }
/*
NSString *linkimg1 =[[elencoFeed objectAtIndex:i] objectForKey:@"summary"];
linkimg1 = [linkimg1 stringByReplacingOccurrencesOfString:@"Rating: " withString:@"<rate>Rating:"];
linkimg1 = [linkimg1 stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
linkimg1 = [linkimg1 stringByReplacingOccurrencesOfString:@"</strong>" withString:@"</rate>"];
linkimg1=[linkimg1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"linkimg: %@", linkimg1);
NSString * foo1 = linkimg1;
// vecchio reg
// NSString * regex2 = @"^(.+?)</image>";
NSString * regex1 = @"<rate>(.*?)</rate>";
NSString *image1 = [foo1 stringByMatching:regex1 capture:1];
image1 = [image1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
image1=[image1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"Match Rating: %@", image1);
*/
NSString *image =[[elencoFeed objectAtIndex:i] objectForKey:@"image"];
NSString *idsens =[[elencoFeed objectAtIndex:i] objectForKey:@"www"];
idsens=[NSString stringWithFormat:@"ID: %@",idsens];
image=[image stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//image=[image stringByReplacingOccurrencesOfString:@".jpg" withString:@"-150x150.jpg"];
NSString *checklat=[[elencoFeed objectAtIndex:i] objectForKey:@"latitudine"] ;
// NSLog (@"chcklat =%@",checklat);
NSString *checklng=[[elencoFeed objectAtIndex:i] objectForKey:@"longitudine"] ;
// NSLog (@"chcklnd =%@",checklng);
checklat=[checklat stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([checklat rangeOfString:@"."].length == 0){
checklat=@"40.665568";
checklng=@"16.601111";
}
// if (checklat !=@"0") {
myAnnotation = [[[shopPoint alloc] init] autorelease];
myAnnotation.latitude = [checklat floatValue];
myAnnotation.longitude = [checklng floatValue];
myAnnotation.title = [title
copy] ;
// myAnnotation.subtitle = [image1 copy] ;
// myAnnotation.subtitle = [subtitle copy] ;
myAnnotation.link = [link
copy] ;
myAnnotation.immagine = [image
copy] ;
// myAnnotation.pin = [check
//copy] ;
// if ([idsens rangeOfString:@"nessuna"].length == 0) {
myAnnotation.subtitle =[idsens
copy] ;
// }
// NSLog(@"links =%@",myAnnotation.link);
// NSLog(@"Immagini =%@",myAnnotation.immagine);
// NSLog(@"pin =%@",myAnnotation.pin);
// NSLog(@"lat =%f",myAnnotation.latitude);
// NSLog(@"Iong =%f",myAnnotation.longitude);
// NSLog(@"subtitile =%@",myAnnotation.subtitle);
// NSLog(@"title =%@",myAnnotation.title);
[shopPoints addObject:myAnnotation];
[mapView addAnnotations:shopPoints];
}
// destinazione.name = myAnnotation.title;
// destinazione.description = myAnnotation.subtitle;
// destinazione.latitude = myAnnotation.latitude;
// destinazione.longitude = myAnnotation.longitude;
// [self showMap:destinazione];
// per ora non serve usando il performbackground mytimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(zoom) userInfo:nil repeats:NO];
mytimer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(zoom) userInfo:nil repeats:NO];
}
-(void)zoom{
// NSLog(@"Numero POI =%d",[shopPoints count]);
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in shopPoints) {
// NSLog(@"Vai verso l'insieme dei POI centrando la mappa");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
//NSLog(@"else-%@",annotationPoint.x);
}
// Position the map so that all overlays and annotations are visible on screen.
[self performSelector:@selector(timeout:) withObject:nil afterDelay:0.1];
}
mapView.visibleMapRect = flyTo;
MKCoordinateRegion region;
//Set Zoom level using Span
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
MKCoordinateSpan span;
region.center=mapView.region.center;
span.latitudeDelta=mapView.region.span.latitudeDelta *2;
span.longitudeDelta=mapView.region.span.longitudeDelta *2;
region.span=span;
[UIView setAnimationDuration:0.30];
[mapView setRegion:region animated:YES];
[UIView commitAnimations];
}
- (void)viewDidLoad {
[super viewDidLoad];
par=0;
chiese=0;
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
mapView.frame=CGRectMake(0, 20, mapView.frame.size.width, mapView.frame.size.height+44);
}
percorsobutton.enabled=NO;
percorsotextview.hidden=YES;
routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
routeView.userInteractionEnabled = NO;
// mapView.showsUserLocation = YES;
[mapView addSubview:routeView];
self.lineColor = [UIColor colorWithRed:0 green:0 blue:255 alpha:1.0];
/*
[self.mapView.userLocation addObserver:self
forKeyPath:@"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:NULL];
*/
//Recupero la posizione corrente con il LOCATION MANAGER (vedi il metodo didUpdateLocation)
[mapView setDelegate:self];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(inizioAPI) userInfo:nil repeats:NO];
self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
// _hud.labelText = @"";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self performSelector:@selector(timeout:) withObject:nil afterDelay:45];
}
-(void)inizioAPI{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *data = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:[prefs objectForKey:@"apimappa"]]];
NSError *jsonError = nil;
NSJSONSerialization *jsonResponse = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&jsonError];
self.tracks = (NSDictionary *)jsonResponse ;
// tracks =[[NSDictionary alloc] init];
shopPoints = [[NSMutableArray alloc] init];
shopPoint *myAnnotation;
// NSLog(@"tracks %@",self.tracks);
NSArray *monday = tracks[@"data"];
for ( NSDictionary *jj in monday )
{/*
NSMutableArray* annotations=[[NSMutableArray alloc] init];
CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = [jj[@"latitude"] floatValue];
theCoordinate1.longitude = [jj[@"longitude"]floatValue];
MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];
myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=jj[@"location"];
myAnnotation1.subtitle=jj[@"alias"];
*/
NSString *title=jj[@"location"];
// NSLog (@"location =%@",title);
NSString *idsens =jj[@"id"];
// idsens=[NSString stringWithFormat:@"ID: %@",idsens];
// NSLog (@"alias =%@",idsens);
NSString *checklat=jj[@"latitude"];
// NSLog (@"chcklat =%@",checklat);
NSString *checklng=jj[@"longitude"];
// NSLog (@"chcklnd =%@",checklng);
// checklat=[checklat stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([checklng intValue] == 0) {
if ([title isEqualToString:@"Ruga Due Pozzi"]){
checklat=@"45.44146";
checklng=@"12.33633";
}
if ([title isEqualToString:@"Ognissanti"]){
checklat=@"45.43008";
checklng=@"12.32591";
}
}
// if (checklat !=@"0") {
myAnnotation = [[[shopPoint alloc] init] autorelease];
myAnnotation.latitude = [checklat floatValue];
myAnnotation.longitude = [checklng floatValue];
myAnnotation.title = [title
copy] ;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *livelli=[prefs objectForKey:@"apilivelli"];
NSString *jsoni=[NSString stringWithFormat:@"%@%@?limit=1&offset=0",livelli,idsens];
//NSLog(@"jsonio %@",jsoni);
NSData *data = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:jsoni]];
NSError *jsonError = nil;
NSJSONSerialization *jsonResponse = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&jsonError];
NSDictionary *jinc=(NSDictionary *)jsonResponse;
NSArray *monday = jinc[@"data"];
NSLog(@"monday %@",monday);
if (![monday count]) {
myAnnotation.subtitle =[[NSString stringWithFormat:@"Ultimo livello: %@",@"non pervenuto"]
copy];
}else{
NSDictionary *item1=[[NSDictionary alloc] initWithDictionary:[monday objectAtIndex:0]];
// NSLog(@"item1 level %d",[item1[@"level"] intValue]);
int livello= [item1[@"level"] intValue];
NSString *link = item1[@"date_sent"];
link = [link stringByReplacingOccurrencesOfString:@" " withString:@""];
[link stripHtml];
link = [link stringByReplacingOccurrencesOfString:@".000" withString:@""];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat : @"yyyy-MM-dd'T'HH:mm:ss'Z'"];
// [dateFormatter1 setDateStyle:NSDateFormatterFullStyle];
[dateFormatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"eeee, dd-MMM-yy HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:[dateFormatter1 dateFromString:link]];
// NSString *dateString=[NSString stringWithFormat:@"%@",AppointmentDate];
dateString=[dateString stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
// NSLog(@"DATE--> %@",dateString);
NSDate *now = [NSDate date];
// NSLog(@"now: %@", now); //2012-04-25 07:00:30 +0000
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:[dateFormatter1 dateFromString:link]];
double secondsInAnHour = 720;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
// NSLog(@"hoursBetweenDates: %ld", (long)hoursBetweenDates);
if (hoursBetweenDates>=1) {
myAnnotation.subtitle =[[NSString stringWithFormat:@"Livello: non pervenuto ultimi 12 min."]
copy];
}else myAnnotation.subtitle =[[NSString stringWithFormat:@"Livello: %d cm.",livello]
copy];
}
[shopPoints addObject:myAnnotation];
// NSLog(@"my annotation %@",shopPoints);
[mapView addAnnotations:shopPoints];
// mytimer = [NSTimer scheduledTimerWithTimeInterval:0.6 target:self selector:@selector(inizio) userInfo:nil repeats:NO];
}
// NSLog(@"mapview annotations %@ ",mapView.annotations);
[self performSelector:@selector(timeout:) withObject:nil afterDelay:0];
[NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(zoom) userInfo:nil repeats:NO];
}
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
printf("[%f,", [latitude doubleValue]);
printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
[array addObject:loc];
}
return array;
}
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t typePath:(NSString*)type{
NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];
//type=h (percorso in macchina-evita strade principali "Avoid Highways")
//type=t (percorso in macchina-evita pedaggi "Avoid Tolls")
//type=w (percorso a piedi)
//type=null (nil) (percorso in macchina)
NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?dirflg=%@&output=dragdir&saddr=%@&daddr=%@", type, saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
// NSLog(@"api url: %@", apiUrl);
NSError *error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
// NSLog(@"apiResponse: %@", apiResponse);
//Recupero la distanza in metri
NSString *tooltip = [apiResponse stringByMatching:@"tooltipHtml:\\\" ([^\\\"]*)\\\"" capture:1L];
tooltip = [tooltip stringByReplacingOccurrencesOfString:@"\\x26#160;"
withString:@" "];
//visualizzo a video la distanza e il tempo di percorrenza
//stampo il risultato a video
if(tooltip!=nil){
UIFont *customFont = [UIFont fontWithName:@"HiraKakuProN-W6" size:12];
UILabel *distanceLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 44, 320, 24)] autorelease];
distanceLabel.font=customFont;
// distanceLabel.font = [UIFont fontWithName:@"Helvetica" size: 12.0];
//distanceLabel.shadowColor = [UIColor blackColor];
distanceLabel.shadowOffset = CGSizeMake(1,1);
distanceLabel.textColor = [UIColor whiteColor];
distanceLabel.text = [NSString stringWithFormat:@"Distanza/Tempo: %@", tooltip];
distanceLabel.backgroundColor = [UIColor colorWithRed:0.0/255.0 green:169.0/255.0 blue:208.0/255.0 alpha:0.7];
distanceLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:distanceLabel];
}
NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
if(encodedPoints!=nil && [encodedPoints length] > 0){
NSMutableString *encodedPointsMutable = [[NSMutableString alloc] initWithString:encodedPoints];
NSArray * array = [self decodePolyLine:encodedPointsMutable];
[encodedPointsMutable release];
return array;
}
else
{
return nil;
}
}
-(void) centerMap1 {
MKCoordinateRegion region;
CLLocationDegrees maxLat = -90;
CLLocationDegrees maxLon = -180;
CLLocationDegrees minLat = 90;
CLLocationDegrees minLon = 180;
// NSLog(@"contiamo i percorsi %i",[routes count]);
for(int idx = 0; idx < routes.count; idx++)
{
CLLocation* currentLocation = [routes objectAtIndex:idx];
if(currentLocation.coordinate.latitude > maxLat)
maxLat = currentLocation.coordinate.latitude;
if(currentLocation.coordinate.latitude < minLat)
minLat = currentLocation.coordinate.latitude;
if(currentLocation.coordinate.longitude > maxLon)
maxLon = currentLocation.coordinate.longitude;
if(currentLocation.coordinate.longitude < minLon)
minLon = currentLocation.coordinate.longitude;
}
region.center.latitude = (maxLat + minLat) / 2;
region.center.longitude = (maxLon + minLon) / 2;
region.span.latitudeDelta = maxLat - minLat;
region.span.longitudeDelta = maxLon - minLon;
[mapView setRegion:region animated:TRUE];
}
-(void) centerMap {
// NSLog(@"Numero POI =%d",[shopPoints count]);
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in shopPoints) {
// NSLog(@"Vai verso l'insieme dei POI centrando la mappa");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
//NSLog(@"else-%@",annotationPoint.x);
}
// Position the map so that all overlays and annotations are visible on screen.
// [self performSelector:@selector(timeout:) withObject:nil afterDelay:0.1];
}
mapView.visibleMapRect = flyTo;
MKCoordinateRegion region;
//Set Zoom level using Span
MKCoordinateSpan span;
region.center=mapView.region.center;
span.latitudeDelta=mapView.region.span.latitudeDelta *1.5;
span.longitudeDelta=mapView.region.span.longitudeDelta *1.5;
region.span=span;
[mapView setRegion:region animated:TRUE];
}
/*
questa funzione disegna un solo punto (la destinazione) sulla mappa