How to detect another MKAnnotaion pin when touch - ios

I have multiple annotation pin in map(place1,place2)
I want user touch pin to go to new Viewcontroller to get description of place
it have function to detect in pin to touch it to go to descriptionViewController?
This is my code
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MKCoordinateRegion place1 = { {0.0, 0.0} , {0.0, 0.0} };
place1.center.latitude = 34.7037755;
place1.center.longitude = 137.7345882;
place1.span.longitudeDelta = 0.02f;
place1.span.latitudeDelta = 0.02f;
[mapView setRegion:place1 animated:YES];
Newclass *ann1 = [[Newclass alloc] init];
ann1.title = #"Place1";
ann1.subtitle = #"subtitle";
ann1.coordinate = place1.center;
[mapView addAnnotation: ann1];
MKCoordinateRegion place2 = { {0.0, 0.0} , {0.0, 0.0} };
place2.center.latitude = 34.7024461;
place2.center.longitude = 137.7297572;
place2.span.longitudeDelta = 0.02f;
place2.span.latitudeDelta = 0.02f;
[mapView setRegion:place2 animated:YES];
Newclass *ann2 = [[Newclass alloc] init];
ann2.title = #"place2";
ann2.subtitle = #"subtitle";
ann2.coordinate = place2.center;
[mapView addAnnotation:ann2];
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
MKPinAnnotationView *myPin = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:#"current"];
myPin.pinColor = MKPinAnnotationColorGreen;
UIButton *advertButtom = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[advertButtom addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
myPin.rightCalloutAccessoryView = advertButtom;
myPin.draggable =NO;
myPin.animatesDrop =true;
myPin.canShowCallout=YES;
return myPin;
}
-(void)button:(id)sender{
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
UIStoryboard *storyboard = [self storyboard];
descriptionViewController *description = [storyboard instantiateViewControllerWithIdentifier:#"des"];
[self presentModalViewController:description animated:YES];
NSLog(#"touched");
NSLog(#"data %#");
}

You need to use mapView method
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
NSUserDefaults *defults = [NSUserDefaults standardUserDefaults];
UIStoryboard *storyboard = [self storyboard];
descriptionViewController *description = [storyboard instantiateViewControllerWithIdentifier:#"des"];
[self presentModalViewController:description animated:YES];
NSLog(#"touched");
NSLog(#"data %#");
}

Related

How to add annotation pin as custom image in Mapview ios 8

I am using mapview and want to add custom image to show the location in map view , how to add image i am not able to add. this code i have used.
-(void)addAllPins
{
self.mapView.delegate=self;
for(int i = 0; i < name1.count; i++)
{
[self addPinWithTitle:name1[i] AndCoordinate:arrCoordinateStr[i]];
}
}
-(void)addPinWithTitle:(NSString *)title AndCoordinate:(NSString *)strCoordinate
{
MKPointAnnotation *mapPin = [[MKPointAnnotation alloc] init];
// clear out any white space
strCoordinate = [strCoordinate stringByReplacingOccurrencesOfString:#" " withString:#""];
// convert string into actual latitude and longitude values
NSArray *components = [strCoordinate componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
// setup the map pin with all data and add to map view
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
mapPin.title = title;
mapPin.coordinate = coordinate;
// UIImage *image = [UIImage imageNamed:#"hover.9.png"];
// [[self.mapView viewForAnnotation:mapPin] setImage:image];
[self.mapView addAnnotation:mapPin];
}
i want to set zoom in scale also . can some help me to solve this.
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];
// NSLog(#"%#", [self deviceLocation]);
//View Area
MKCoordinateRegion region = self.mapView.region;
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.015;
region.span.longitudeDelta = 0.015;
[mapView setRegion:region animated:YES];
[self addAllPins];
}
My code is help you.You can put custom pin annotation
- (MKAnnotationView *)mapView:(MKMapView *)sender viewForAnnotation:(id < MKAnnotation >)annotation
{
static NSString *reuseId = #"StandardPin";
MKAnnotationView *aView = (MKAnnotationView *)[sender
dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (aView == nil)
{
aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
aView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
aView.canShowCallout = YES;
}
aView.image = [UIImage imageNamed : #"Location_OnMap"];
aView.annotation = annotation;
aView.calloutOffset = CGPointMake(0, -5);
aView.draggable = YES;
aView.enabled = YES;
return aView;
}
You need to use mapView Delegate Method
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation)
{
MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:#"MKPinAnnotationView"];
if (pinView ==nil) {
pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:#"MKPinAnnotationView"];
pinView.animatesDrop = YES;
}
pinView.canShowCallout = YES;
pinView.pinColor = MKPinAnnotationColorGreen;//if you want
return pinView;
}
else
{
static NSString *viewId = #"MKAnnotationView";
MKAnnotationView *annotationView = (MKAnnotationView*)
[mapView dequeueReusableAnnotationViewWithIdentifier:viewId];
if (annotationView == nil) {
annotationView = [[MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:viewId];
}
annotationView.canShowCallout=YES;
annotationView.image = [UIImage imageNamed:#"yourImage"];//set your image here
return annotationView;
}
}
2.) to zoom
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(yourLocation.coordinate, 100, 100);
MKCoordinateRegion adjustedRegion = [self.mapView regionThatFits:viewRegion];
[self.mapView setRegion:adjustedRegion animated:YES];
It will help.Thank you.

Changing pin color when selecting annotation pin

My app is a map view where the user can enter an address which will put a purple pin on the map for the HQ. Secondly, the user can enter any address, which will put a red pin on the map. I would like to be able to change the pin color of the red pins to either red, green, or purple.
I stumbled across a tutorial that will allow the user to select an annotation pin and change its pin color by displaying a modal view. I followed the tutorial meticulously, but for some reason, it is not working correctly. The modal view with the pin selection is displayed, but when a pin color is selected, the pin color on the map view is not updated. Additionally, instead of using "png" images to display custom pins, I would like to use the built-in standard pins (since that's all I need). How can I adjust my code below to achieve this? I added my entire code.
FieldMapController.m
#import "FieldMapController.h"
#import "CustomAnnotation.h"
#define HQ_latitude #"headquarters_latitude"
#define HQ_longitude #"headquarters_longitude"
#define HQ_coordinates #"headquarters_coordinates"
#import "PinSelectionViewController.h"
#interface FieldMapController ()
#end
#implementation FieldMapController
#synthesize mapView;
#synthesize searchBar;
#synthesize geocoder = _geocoder;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//ACCESS SAVED DATA FROM NSUSERDEFAULTS
-(void)viewWillAppear:(BOOL)animated{
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];
if ([uDefaults boolForKey:#"headquarters_coordinates"])
{
CLLocationCoordinate2D savedCoordinate;
savedCoordinate.latitude = [uDefaults doubleForKey:#"headquarters_latitude"];
savedCoordinate.longitude = [uDefaults doubleForKey:#"headquarters_longitude"];
NSLog(#"Your HQ is at coordinates %f and %f",savedCoordinate.latitude, savedCoordinate.longitude);
CustomAnnotation *annHq =[[CustomAnnotation alloc] init];
annHq.title=#"HQ";
annHq.subtitle=#"";
annHq.coordinate= savedCoordinate;
[mapView addAnnotation:annHq];
MKCoordinateRegion viewRegion = {{0.0, 0.0}, {0.0, 0.0}};
viewRegion.center.latitude = savedCoordinate.latitude;
viewRegion.center.longitude = savedCoordinate.longitude;
viewRegion.span.longitudeDelta = 0.5f;
viewRegion.span.latitudeDelta = 0.5f;
[self.mapView setRegion:viewRegion animated:YES];
[self.mapView setDelegate:self];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.mapView.delegate = self;
self.searchBar.delegate = self;
//SEARCH BAR TOOLBAR WITH "DONE" AND "CANCEL" BUTTON
UIToolbar* searchToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
searchToolbar.barStyle = UIBarStyleBlackTranslucent;
searchToolbar.items = [NSArray arrayWithObjects:
[[UIBarButtonItem alloc]initWithTitle:#"Cancel" style:UIBarButtonItemStyleBordered target:self action:#selector(cancelSearchBar)],
[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
nil];
[searchToolbar sizeToFit];
searchBar.inputAccessoryView = searchToolbar;
}
//WHEN PUSHING THE "CANCEL" BUTTON IN THE SEARCH BAR
-(void)cancelSearchBar
{
[searchBar resignFirstResponder];
searchBar.text = #"";
}
//PREPARE SEGUE FOR THE PIN SELECTOR VIEW
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"ShowPinChoicesSegue"])
{
PinSelectionViewController *pinVC = [segue destinationViewController];
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)sender;
pinVC.currentPinType = selectedAnnotation.pinType;
pinVC.delegate = self;
}
}
//WHAT HAPPENS WHEN THE "SEARCH" BUTTON AT THE SEARCH BAR KEYBOARD IS TAPPED
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
//Forward Geocoder
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *address = [NSString stringWithFormat:#"%#", self.searchBar.text];
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
//Display Coordinates in Console
NSLog (#"%f %f", coordinate.latitude, coordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = coordinate;
//Create Annotation with Callout Bubble that displays "No Information"
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
[annotation setCoordinate:coordinate];
[annotation setTitle:#"No Information"];
[[self mapView] addAnnotation:annotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
//Dismiss the Search Bar Keyboard
[self.searchBar resignFirstResponder];
//Delete text in Search Bar
self.searchBar.text = #"";
}
}];
}
//CUSTOM ANNOTATION VIEW
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
if ([annotation isKindOfClass:[CustomAnnotation class]])
{
MKPinAnnotationView *annotationView =
(MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:((CustomAnnotation *)annotation).annotationViewImageName];
if(annotationView == nil)
{
MKPinAnnotationView *customPinView =
[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:((CustomAnnotation *)annotation).annotationViewImageName];
if([[customPinView.annotation title] isEqualToString:#"HQ"])
{
//The pin for the HQ should be purple
customPinView.pinColor = MKPinAnnotationColorPurple;
}
else
{
//All other new pins should be "red" by default
customPinView.image = [UIImage imageNamed:((CustomAnnotation *)annotation).annotationViewImageName];
}
customPinView.canShowCallout = YES;
customPinView.animatesDrop = YES;
//Right Callout Accessory Button
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
customPinView.rightCalloutAccessoryView = rightButton;
return customPinView;
}
else
{
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
//SHOW ACCESSORY VIEW WHEN BUTTON ON CALLOUT BUBBLE IS TAPPED
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
if (![view.annotation isKindOfClass:[CustomAnnotation class]])
return;
CustomAnnotation *customAnnotation = (CustomAnnotation *)view.annotation;
if (control.tag == 0)
{
[self performSegueWithIdentifier:#"ShowPinChoicesSegue" sender:customAnnotation];
}
else
{
[self onRightCalloutAccessoryViewTouched:control];
}
}
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if(![view.annotation isKindOfClass:[CustomAnnotation class]])
return;
if (!view.rightCalloutAccessoryView)
{
UIButton *rightViewButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 48.0, 32.0)];
[rightViewButton addTarget:self action:#selector(onRightCalloutAccessoryViewtouched:) forControlEvents:UIControlEventTouchUpInside];
rightViewButton.tag = 1;
view.rightCalloutAccessoryView = rightViewButton;
}
}
-(void)onRightCalloutAccessoryViewTouched:(id)sender
{
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)[mapView.selectedAnnotations objectAtIndex:0];
[self performSegueWithIdentifier:#"ShowPinChoicesSegue" sender:selectedAnnotation];
}
- (void)viewDidUnload
{
self.mapView = nil;
self.searchBar = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//BUTTON TO SELECT NEW HQ
- (IBAction)selectHq:(UIBarButtonItem *)sender
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Select Headquarters"
message:#"Enter Address"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeDefault];
[alert show];
}
//REMOVING ALL PINS EXCEPT USER LOCATION
- (IBAction)resetPins:(UIBarButtonItem *)sender
{
id userLocation = [mapView userLocation];
NSMutableArray *pins = [[NSMutableArray alloc] initWithArray:[mapView annotations]];
if ( userLocation != nil )
{
[pins removeObject:userLocation]; //avoid removing user location
}
[mapView removeAnnotations:pins];
pins = nil;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_coordinates];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_longitude];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:HQ_latitude];
}
//ALERT VIEW TO ENTER ADDRESS OF HQ
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter HQ Address";
if (!self.geocoder)
{
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *hqAddress = [NSString stringWithFormat:#"%#", field.text];
[self.geocoder geocodeAddressString:hqAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D hqCoordinate = location.coordinate;
NSLog (#"Your new HQ is at coordinates %f and %f", hqCoordinate.latitude, hqCoordinate.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
region.span = span;
region.center = hqCoordinate;
MKPointAnnotation *hqAnnotation = [[MKPointAnnotation alloc] init];
[hqAnnotation setCoordinate:hqCoordinate];
[hqAnnotation setTitle:#"HQ"];
[[self mapView] addAnnotation:hqAnnotation];
[self.mapView setRegion:region animated:TRUE];
[self.mapView regionThatFits:region];
//Save to NSUserDefaults
NSUserDefaults *uDefaults = [NSUserDefaults standardUserDefaults];
[uDefaults setDouble:hqCoordinate.latitude forKey:HQ_latitude];
[uDefaults setDouble:hqCoordinate.longitude forKey:HQ_longitude];
[uDefaults setBool:YES forKey:HQ_coordinates];
[uDefaults synchronize];
}
}];
}
else
{
//any actions for "Cancel"
}
}
//DEFINES WHAT SELECTING THE NEW PIN COLOR DOES
-(void)userDidSelectPinType:(AnnotationPinType)aPinType
{
CustomAnnotation *selectedAnnotation = (CustomAnnotation *)[mapView.selectedAnnotations objectAtIndex:0];
selectedAnnotation.pinType = aPinType;
[mapView removeAnnotation:selectedAnnotation];
[mapView addAnnotation:selectedAnnotation];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#end
CustomAnnotation.m
#import "CustomAnnotation.h"
#import <CoreLocation/CoreLocation.h>
#implementation CustomAnnotation
#synthesize title, subtitle, coordinate;
#synthesize pinType;
-(id) initWithCoordinate:(CLLocationCoordinate2D)aCoordinate title:(NSString *)aTitle subtitle:(NSString *)aSubtitle
{
if ((self = [super init]))
{
self.title = aTitle;
self.coordinate = aCoordinate;
self.subtitle = aSubtitle;
}
return self;
}
- (NSString *)annotationViewImageName
{
switch (self.pinType)
{
case 0:
return #"Red_Pin.png";
break;
case 1:
return #"Green_Pin.png";
break;
case 2:
return #"Purple_Pin.png";
break;
default:
break;
}
}
- (NSString *)title
{
return title;
}
- (NSString *)subtitle
{
return subtitle;
}
#end
PinSelectionViewController.m
#import "PinSelectionViewController.h"
#interface PinSelectionViewController ()
#end
#implementation PinSelectionViewController
#synthesize delegate;
#synthesize currentPinType;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (void)tableView:(UITableView *) tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row ==currentPinType)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.delegate userDidSelectPinType:indexPath.row];
}
#end
PinSelectionDelegateProtocol.h
#import <Foundation/Foundation.h>
typedef enum
{
RED_PIN,
GREEN_PIN,
PURPLE_PIN
} AnnotationPinType;
#protocol PinSelectionDelegate <NSObject>
#required
-(void)userDidSelectPinType:(AnnotationPinType)aPinType;
#end
The problem I see is early on in your viewForAnnotation method. You correctly reuse annotationviews but incorrectly assume that the reused view is configured properly. When you check if the view is nil you only configure brand new ones to have the pin colour that matches the annotation's name. What you need to do is check if it is nil, if is then make a new one and close that if. Then make sure both new and reused annotationviews have their pin colour, title, accessory view etc set up as you want it for that annotation.
Also you can't set the .image of an MKPinAnnotationView, it'll just get overwritten. If you really want to set a custom image you have to use a regular MKAnnotationView. If you are ok with using the standard red, green and blue pins then just set the .pinColor to whatever you want.

Annotated pins are not getting loaded during reloading of map

I have used apple maps in my application for implementing maps.I used the following code for that.
My problem is that,It is showing the pins only when it is loading for the first time.
I have written the code like this
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Locate Engineer";
[worldView setMapType:MKMapTypeStandard];
[worldView setShowsUserLocation:YES];
worldView.delegate = self;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self)
{
i=0;
locationManager = [[CLLocationManager alloc]init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
}
return self;
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[locationManager startUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"%#",newLocation);
}
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
pinView = nil;
if(annotation != mapView.userLocation)
{
NSString * defaultPinID = #"aa";
//removed autorelease from the code below by coder
pinView = (MKPinAnnotationView *) [worldView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if(pinView == nil)
{
pinView .tag =i;
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] ;
//pinView.image = [UIImage imageNamed:#"serviceengineer.png"];
NSLog(#"pnID is %d",i);
NSLog(#"value of i is %d",i);
if ([[pinView.annotation title] isEqualToString:#"Levitton"]) {
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.draggable = NO;
} else {
pinView.pinColor = MKPinAnnotationColorGreen;
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:#selector(mapAction:) forControlEvents:UIControlEventTouchUpInside];
rightButton.tag =i;
pinView.rightCalloutAccessoryView = rightButton;
// pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.draggable = NO;
}
}
else {
[worldView.userLocation setTitle:#"Title here"]; }
i++;
}
return pinView;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
ServiceEngineersList *engList = [ServiceEngineers findAll];
MKCoordinateSpan spans;
spans.latitudeDelta = 0.5;
spans.longitudeDelta = 0.5;
ServiceEngineers *obj1= [engList objectAtIndex:0];
// location1.latitude = 40.728224000000;
//location1.longitude =-73.794852000000;
location1.latitude = [obj1.LATITUDE doubleValue];
location1.longitude =[obj1.LONGITUDE doubleValue];
ad1 = [[annotationTest alloc] init];
ad1.pinColor = MKPinAnnotationColorGreen;
MKCoordinateRegion regions =
MKCoordinateRegionMakeWithDistance(location1, 250,250);
regions.span = spans;
[worldView setRegion:regions animated:YES];
[worldView setZoomEnabled:YES];
[worldView addAnnotation:ad1];
ServiceEngineers *obj2= [engList objectAtIndex:1];
ad2 = [[annotationTest2 alloc] init];
ad2.pinColor = MKPinAnnotationColorGreen;
//location2.latitude = 40.710841000000;
//location2.longitude=-73.897769000000;
location2.latitude = [obj2.LATITUDE doubleValue];
location2.longitude =[obj2.LONGITUDE doubleValue];
MKCoordinateRegion region1 =
MKCoordinateRegionMakeWithDistance(location2, 250, 250);
region1.span = spans;
[worldView setRegion:region1 animated:YES];
[worldView setZoomEnabled:YES];
[worldView addAnnotation:ad2];
ServiceEngineers *obj3= [engList objectAtIndex:2];
ad3 = [[annotationTest3 alloc] init];
ad3.pinColor = MKPinAnnotationColorGreen;
//location3.latitude = 40.726768000000;
//location3.longitude=-73.634295000000;
location3.latitude = [obj3.LATITUDE doubleValue];
location3.longitude =[obj3.LONGITUDE doubleValue];
MKCoordinateRegion region2 =
MKCoordinateRegionMakeWithDistance(location3, 250, 250);
region2.span = spans;
[worldView setRegion:region2 animated:YES];
[worldView setZoomEnabled:YES];
[worldView addAnnotation:ad3];
ServiceEngineers *obj4= [engList objectAtIndex:3];
ad4 = [[annotationTest4 alloc] init];
ad4.pinColor = MKPinAnnotationColorGreen;
//location4.latitude = 40.702677000000;
//location4.longitude=-73.788969000000;
location4.latitude = [obj4.LATITUDE doubleValue];
location4.longitude =[obj4.LONGITUDE doubleValue];
MKCoordinateRegion region3 =
MKCoordinateRegionMakeWithDistance(location4, 250, 250);
region3.span = spans;
[worldView setRegion:region3 animated:YES];
[worldView setZoomEnabled:YES];
[worldView addAnnotation:ad4];
ad5 = [[annotationTest5 alloc] init];
ad5.pinColor = MKPinAnnotationColorRed;
location5.latitude = 40.7258;
location5.longitude= -73.5147;
MKCoordinateRegion region4 =
MKCoordinateRegionMakeWithDistance(location5, 250, 250);
region4.span = spans;
[worldView setRegion:region4 animated:YES];
[worldView setZoomEnabled:YES];
[worldView addAnnotation:ad5];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"Couldnot find location: %#",error);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight)
return YES;
return NO;
}
Please help me to find out the issue.I put breakpoints.Second time it is coming only upto
worldView.delegate = self;
Just place in the viewWillAppear and remove in the viewDidLoad
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
locationManager = [[CLLocationManager alloc]init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
}

iOS Displaying annotations from an array

I am trying to display multiple annotations on my mapView from an array. The annotation coordinates are parsed from an XML file and stored in the array as [currentCall longitude] and [currentCall latitude]. My question is, what is the syntax for "calling" the array? (I don't know if that's how you say it). In another part of my application, I display the parsed XML results in a table and use "JointCAD *currentCall = [[xmlParser calls] objectAtIndex:indexPath.row];" to "call" the array. How do I do it for displaying my annotations? Everything else works fine except that little part.
Here is the implementation file:
#implementation SecondViewController
#synthesize mapView;
XMLParser *xmlParser;
-(IBAction)getlocation {
mapView.showsUserLocation = YES;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView commitAnimations];
}
-(IBAction)changeSeg:(id)sender {
if (segment.selectedSegmentIndex == 0) {
mapView.mapType = MKMapTypeStandard;
}
if (segment.selectedSegmentIndex == 1) {
mapView.mapType = MKMapTypeSatellite;
}
if (segment.selectedSegmentIndex == 2) {
mapView.mapType = MKMapTypeHybrid;
}
}
-(void)viewDidLoad {
JointCAD *currentCall = [[xmlParser calls] objectAtIndex:indexPath.row];
mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
[self.view insertSubview:mapView atIndex:0];
[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
[mapView setDelegate:self];
MKCoordinateRegion WCCCA = { {0.0, 0.0} , {0.0, 0.0} };
WCCCA.center.latitude = 45.53540820864449;
WCCCA.center.longitude = -122.86178648471832;
WCCCA.span.longitudeDelta = 0.02f;
WCCCA.span.latitudeDelta = 0.02f;
[mapView setRegion:WCCCA animated:YES];
Annotation *ann1 = [[Annotation alloc] init];
ann1.title = #"WCCCA";
ann1.subtitle = #"Washington County Consolidated Communications Agency";
ann1.coordinate = WCCCA.center;
[mapView addAnnotation: ann1];
MKCoordinateRegion CALL = { {0.0, 0.0} , {0.0, 0.0} };
CALL.center.latitude = [currentCall.latitude doubleValue];
CALL.center.longitude = [currentCall.longitude doubleValue];
CALL.span.longitudeDelta = 0.02f;
CALL.span.latitudeDelta = 0.02f;
[mapView setRegion:WCCCA animated:YES];
Annotation *ann2 = [[Annotation alloc] init];
ann2.title = [currentCall currentCallType];
ann2.subtitle = [currentCall location];
ann2.coordinate = CALL.center;
[mapView addAnnotation: ann1];
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorRed;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
#end
If I am understanding your code properly, you should be able to just iterate through your parsed XML (it appears that the output the from your xmlParser object is an NSArray) and add the annotations to the mapView within the loop.
You can use the C function CLLocationCoordinate2DMake() to create the coordinate data structure for your annotation.
NSArray *callsArray = [xmlParser calls];
for (JointCAD *call in callsArray) {
Annotation *ann = [[Annotation alloc] init];
ann.title = [call currentCallType];
ann.subtitle = [call location];
ann.coordinate = CLLocationCoordinate2DMake([call latitude], [call longitude]);
[mapView addAnnotation:ann];
}

TableView & MapView same Detail View

I have a table view that load the data from an xml in a array and show it, every cell point to the same detail view repopulated.
In the same view i have a hidden map view, the map view show the same array of the table in the map, every annotation have a disclosure button that point to the same detail view of the table, but i don't understand how i can pass the data from the map view to the detail view...
for the disclosure button i use this code
-(IBAction)showDetails:(id)sender{
DettMercatiViewController *dettMercatiViewController = [[DettMercatiViewController alloc] initWithNibName:#"DettMercatiViewController" bundle:nil];
dettMercatiViewController.mieiMercati = [table objectAtIndex:????];
[self.navigationController pushViewController:dettMercatiViewController animated:YES];
[dettMercatiViewController release];
}
table is the name of the nsmutablearray created from the xml but i don't know what objectIndex use... any idea?
ok, here the viewdidload and the creation of pin, please help me and explain because i am desolate:
- (void)viewDidLoad
{
pp =0;
//Colore NavigationBar
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:33.0f/255.0f green:89.0f/255.0f blue:50.0f/255.0f alpha:1.0f];
//Font Navigation Bar
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 45)];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:#"Museo700-Regular" size:20];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor =[UIColor whiteColor];
label.text=[self.title uppercaseString];
self.navigationItem.titleView = label;
[label release];
//creazione nome XML
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *nomeXML = [NSString stringWithFormat: #"%#_%#_%#",[defaults stringForKey:#"interesse"],[defaults stringForKey:#"provincia"],[defaults stringForKey:#"giorno"]];
NSLog(#"%#", nomeXML);
//Caricamento XML
table = [[NSMutableArray alloc] init];
NSString *url = [[NSBundle mainBundle] pathForResource:nomeXML ofType:#"xml"];
XMLParser *myParser = [[[XMLParser alloc]autorelease] parseXMLAtURL:url toObject:#"Mercato" parseError:nil];
for(int i = 0; i < [[myParser items] count]; i++) {
Mercato *new = [[myParser items] objectAtIndex:i];
[table addObject:new];
///////////////////////////////////////////
//definizione posizione utente
AppDelegate *appDelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
CLLocation *userLoc = appDelegate.locationManager.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
mapView.delegate=self;
//Pin Mappa
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = [new.latitudine doubleValue];
theCoordinate.longitude = [new.longitudine doubleValue];
myAnnotation=[[MyAnnotation alloc] init];
myAnnotation.coordinate=theCoordinate;
myAnnotation.title=[NSString stringWithFormat:#"%#", new.ubicazione];
myAnnotation.subtitle=[NSString stringWithFormat:#"%#, %#, %#",new.comune, new.giorno, new. orario];
[mapView addAnnotation:myAnnotation];
[annotations addObject:myAnnotation];
if([new.latitudine doubleValue] == 0) {
[mapView removeAnnotation:myAnnotation];
myAnnotation = nil;
}
// Inizializza mappa al Centro della Provincia
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"bergamo"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.6982642;
newRegion.center.longitude = 9.6772698;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"brescia"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.5411875;
newRegion.center.longitude = 10.2194437;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"como"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.8080597;
newRegion.center.longitude = 9.0851765;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"cremona"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.133249;
newRegion.center.longitude = 10.0226511;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"lecco"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.8565698;
newRegion.center.longitude = 9.3976704;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"lodi"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.3138041;
newRegion.center.longitude = 9.5018274;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"mantova"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.1564168;
newRegion.center.longitude = 10.7913751;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"milano"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.4654542;
newRegion.center.longitude = 9.186516;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.512872;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"monza e brianza"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.623599;
newRegion.center.longitude = 9.2588015;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"pavia"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.1847248;
newRegion.center.longitude = 9.1582069;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"sondrio"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 46.1698583;
newRegion.center.longitude = 9.8787674;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
if (([[defaults stringForKey:#"provincia"] isEqualToString:#"varese"])) {
MKCoordinateRegion newRegion;
newRegion.center.latitude = 45.8205989;
newRegion.center.longitude = 8.8250576;
newRegion.span.latitudeDelta = 0.512872;
newRegion.span.longitudeDelta = 0.509863;
[mapView setRegion:newRegion animated:YES];
}
}
////////////////////////////
[super viewDidLoad];
}
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
NSLog(#"welcome into the map view annotation");
pp++;
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]]){
return nil;
}
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:myAnnotation reuseIdentifier:AnnotationIdentifier]autorelease];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorGreen;
pinView.tag = pp;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:myAnnotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
return pinView;
}
////////////////
-(IBAction)showDetails:(id)sender{
NSLog(#"%i", pp);
DettMercatiViewController *dettMercatiViewController = [[DettMercatiViewController alloc] initWithNibName:#"DettMercatiViewController" bundle:nil];
dettMercatiViewController.mieiMercati = [table objectAtIndex:[sender tag]];
[self.navigationController pushViewController:dettMercatiViewController animated:YES];
[dettMercatiViewController release];
}
I suggest to give every disclosure button in your map view a tag and you can use this tag than
so
[table objectAtIndex:[sender tag]];

Resources