Show multiple pins on MKMap iPhone - iphone

Hello friend in my application i am showing multiple pins on mapview. I have two mutablearray first for latitude and second for longitude each array have 10 values as i am showing bellow code in my method:
- (void)showAddressAllBusiness {
annotationsarray=[[NSMutableArray alloc] init];
NSLog(#"%d",[listOfLatitude count]);
NSLog(#"%d",[listOfLongitude count]);
NSLog(#"%d",[listOfPlaceName count]);
for (int i =0;i < [listOfLatitude count]; i++) {
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = [[listOfLatitude objectAtIndex:i] doubleValue];
region.center.longitude = [[listOfLongitude objectAtIndex:i] doubleValue];
region.span.longitudeDelta = 0.1f;
region.span.latitudeDelta = 0.1f;
[self.mapViewCityGuide setRegion:region animated:YES];
[self.mapViewCityGuide setZoomEnabled:YES];
addAnnotation = [[AddressAnnotation alloc]init];
addAnnotation.mTitle = [NSString stringWithFormat:#"%#",[listOfPlaceName objectAtIndex:i]];
addAnnotation.coordinate = region.center;
[self.mapViewCityGuide addAnnotation:addAnnotation];
[annotationsarray addObject:addAnnotation];
}
NSLog(#"%d",[self.mapViewCityGuide.annotations count]);
[self centerMap];
}
when i am using latitude and longitude array values which is appear from webservice then
this code is not working fine and i am debugg the code then mapViewCityGuide getting nil or 0x0.
If i am using hard code latitude and longitude value as mention bellow in the array and call this method then it will show all pins on map how can i solve this problem
listOfPlaceName = [[NSMutableArray alloc] initWithObjects:#"test",#"test",#"test",#"pithempur",#"test",#"test",#"test",#"test", nil];
listOfLatitude = [[NSMutableArray alloc] initWithObjects:#"22.71957",#"23.17930",#"22.96123",#"22.60987",#"22.45260",#"22.55244",#"22.60000",#"22.68330", nil];
listOfLongitude = [[NSMutableArray alloc] initWithObjects:#"75.85773",#"75.78491",#"76.05141",#"75.69644",#"75.94197",#"75.75653",#"75.30000",#"75.61670", nil];
[self showAddressAllBusiness];

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
mapView.delegate=self;
[mapView removeAnnotations:mapView.annotations];
NSMutableArray* annotations=[[NSMutableArray alloc] init];
for (int j=0; j<10; j++)
{
CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = [[NSString stringWithFormat:#"%i",10+j]doubleValue];
theCoordinate1.longitude = [[NSString stringWithFormat:#"%i",72+j]doubleValue];
//my annotation is mkannotation class
MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];
myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=[NSString stringWithFormat:#"locatiion %i",j];
[mapView addAnnotation:myAnnotation1];
[annotations addObject:myAnnotation1];
}
NSLog(#"%d",[annotations count]);
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations) {
NSLog(#"fly to on");
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
if (MKMapRectIsNull(flyTo)) {
flyTo = pointRect;
} else {
flyTo = MKMapRectUnion(flyTo, pointRect);
}
}
mapView.visibleMapRect = flyTo;
}
#pragma mark MKMapViewDelegate
/*
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
return [kml viewForOverlay:overlay];
}
*/
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
if ([annotation isKindOfClass:[MyAnnotation class]])
{
static NSString *AnnotationIdentifier = #"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
if (!pinView)
{
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
}
else
{
pinView.annotation = annotation;
pinView.tag=((MyAnnotation *)annotation).tag;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame=CGRectMake(0, 0, 14, 16);
[rightButton setBackgroundImage:[UIImage imageNamed:#"arrow_s5.png"] forState:UIControlStateNormal];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
rightButton.tag=((MyAnnotation *)annotation).tag;
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
return pinView;
}
return nil;
}

*Please try this code:-*
-(void)viewDidLoad
{
CLLocation *userLoc = mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
mapView.delegate=self;
NSMutableArray* annotations=[[NSMutableArray alloc] init];
MyAnnotation* myAnnotation;
for (int i = 0; i<[DataArr count]; i++)
{
CLLocationCoordinate2D theCoordinate;
double a = [[[DataArr objectAtIndex:i] valueForKey:#"lat"] doubleValue];
double b =[[[DataArr objectAtIndex:i] valueForKey:#"lon"] doubleValue];
theCoordinate.latitude = a;
theCoordinate.longitude =b;
myAnnotation=[[MyAnnotation alloc] init];
NSString *str=[NSString stringWithFormat:#"%d",i];
[myAnnotation indexOfAccessibilityElement:str];
myAnnotation.coordinate=theCoordinate;
myAnnotation.title=[[DataArr objectAtIndex:i] valueForKey:#"name"];
myAnnotation.ID_map=i;
[annotations addObject:myAnnotation];
}
for (int i =0; i<[annotations count]; i++)
{
[mapView addAnnotation:[annotations objectAtIndex:i]];
}
// Walk the list of overlays and annotations and create a MKMapRect that
// bounds all of them and store it into flyTo.
MKMapRect flyTo = MKMapRectNull;
for (id <MKAnnotation> annotation in annotations)
{
NSLog(#"fly to on");
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.
mapView.visibleMapRect = flyTo;
}
#pragma mark MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
NSLog(#"didSelectAnnotationView");
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"welcome into the map view annotation");
// 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";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.animatesDrop=YES;
pinView.canShowCallout=YES;
pinView.pinColor=MKPinAnnotationColorPurple;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"profile.png"]];
pinView.leftCalloutAccessoryView = profileIconView;
[profileIconView release];
return pinView;
}

Related

MKAnnotationView issue where my pins show up initially then disappear?

I am attempting to debug an issue with my code where the pins on my MKAnnotationView initially show up on first call for a second, but when the map zooms in on the location, all the annotations except for the user location disappears. Can someone point me to a flaw in my logic?
Below is the code being used. AddPlacemark is used to get the locations of all my annotations then the MKAnnotationView should show them all on the map. Like I said, when the map first appears the annotations all show, but when the map zooms in on the location of the user, all my other annotations disappear. I believe this issue only started occurring when I updated my Xcode so that I could test on iOS 6 and get the simulator for the iPhone 5.
- (void)AddPlacemark {
if([allplacemarkarray count]>0) {
[mapView removeAnnotations:allplacemarkarray];
[allplacemarkarray removeAllObjects];
}
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
CLLocationCoordinate2D location1;
location1.latitude = appdel.MyCurrentLocation.latitude;
location1.longitude = appdel.MyCurrentLocation.longitude;
region.span = span;
region.center = location1;
Placemark *addAnnotation = [[[Placemark alloc] initWithCoordinate:location1] retain];
[mapView addAnnotation:addAnnotation];
[allplacemarkarray addObject:addAnnotation];
[addAnnotation release];
if(alllocationArray) {
for(int i=0;i<[alllocationArray count];i++) {
NSDictionary *locationdict=[alllocationArray objectAtIndex:i];
CLLocationCoordinate2D location;
location.latitude = [[locationdict objectForKey:#"VLATITUDE"] floatValue];
location.longitude =[[locationdict objectForKey:#"LONGITUDE"]floatValue];
region.span=span;
region.center=location;
Placemark *addAnnotation = [[[Placemark alloc] initWithCoordinate:location] retain];
[allplacemarkarray addObject:addAnnotation];
addAnnotation.titletext = [locationdict objectForKey:#"NAME"];
addAnnotation.logoText = [locationdict objectForKey:#"LOGO"];
NSString *add1=[locationdict objectForKey:#"ADDR1"];
NSString *add2=[locationdict objectForKey:#"ADDR2"];
NSString *city=[locationdict objectForKey:#"CITY"];
NSString *state=[locationdict objectForKey:#"STATE"];
NSString *zip =[locationdict objectForKey:#"ZIP"];
addAnnotation.subtitletext=[NSString stringWithFormat:#"%# %# %#, %# %#",add1,add2,city,state,zip];
[addAnnotation setPlacemarkId:[NSNumber numberWithInt:i]];
[mapView addAnnotation:addAnnotation];
[addAnnotation release];
}
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(Placemark *) annotation {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"MyPin"];
annView.animatesDrop = TRUE;
annView.canShowCallout = YES;
[annView setSelected:YES];
UIImage *pinImage = [UIImage imageNamed:annotation.logoText];
UIImageView *logoView = [[UIImageView alloc] initWithImage:pinImage];
logoView.frame = CGRectMake(-23, -6, 63, 48);
UIButton *myDetailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
myDetailButton.frame = CGRectMake(0, 0, 23, 23);
myDetailButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myDetailButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[myDetailButton addTarget:self action:#selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[myDetailButton setTag:[annotation.placemarkId intValue]];
annView.rightCalloutAccessoryView=myDetailButton;
if(annotation.coordinate.latitude == appdel.MyCurrentLocation.latitude && annotation.coordinate.longitude == appdel.MyCurrentLocation.longitude) {
annView.pinColor = MKPinAnnotationColorRed;
} else if ([annotation.logo isEqualToString:#""]) {
annView.pinColor = MKPinAnnotationColorPurple;
} else {
[annView addSubview:logoView];
}
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
This question is actually not due to bad code in the app. Sorry about that! It turns out my backend code that feeds information to this logic was bad.

How to add ModelView Controller on Annotation Pin for showing detail UI view

I want to add detail view having Two buttons and three labels for information by taping on annotation pin. Is there any tutorial or sample code link for this. I have search but get only canShowCallout sub title which is old ways.
Edited:- I have parsed URL then on success condition I have put this code to put annotation. What should I make change in MKAnnotation view also tell me.....
for (int i = 0; i < [appDelegate.markers count]; i++)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
location.latitude = [aMarker.lat floatValue];
location.longitude =[aMarker.lng floatValue];
AddressAnnotation *annobj = [[AddressAnnotation alloc] initWithCoordinate:location];
//[annobj setAnnotationType:AddressAnnotationTypeHettich];
//annobj.title = aMarker.name;
//annobj.subTitle = aMarker.address;
[mapView addAnnotation:annobj];
[annobj release];
CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude};
//for zoom in the showroom results region
MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
NSLog(#"No Errors");
mapView.region = ausRegion;
}
indexRow = 0;
mapAnnonations = [[[NSMutableArray alloc] init] retain];
for (int i = indexRow; i<[lat ,longi count]; i++)
{
region.center.latitude = [[lat objectAtIndex:indexRow] floatValue];
region.center.longitude = [[longi objectAtIndex:indexRow] floatValue];
region.span.longitudeDelta = 0.04f;
region.span.latitudeDelta = 0.04f;
[mymapView setRegion:region animated:YES];
coordinate.latitude = [[lat objectAtIndex:indexRow] floatValue];
coordinate.longitude = [[longi objectAtIndex:indexRow]floatValue];
NSLog(#"Latitude & Longitude:---->%f,%f",coordinate.latitude,coordinate.longitude);
mapAnnotation = [[AllMapAnnotation alloc] initWithCoordinate:coordinate];
NSString *title = [[[resData valueForKey:#"name"] mutableCopy] objectAtIndex:indexRow];
NSString *titleStr = [title stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"Pin Title:--->%#",titleStr);
[mapAnnotation setTitle:titleStr];
//[mapAnnotation setSubtitle:[NSString stringWithFormat:#"Ph: %#",pantries.phone]];
mapAnnotation.coordinate = region.center;
[mapAnnonations insertObject:mapAnnotation atIndex:indexRow];
[mymapView addAnnotations:mapAnnonations];
//[mymapView addAnnotation:mapAnnotation];
indexRow+= 1;
}
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *pinView = nil;
if(annotation!= mymapView.userLocation)
{
static NSString *defaultPinID = #"pantryIdentifier";
pinView = (MKPinAnnotationView *)[mymapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
NSInteger annotationValue = [mapAnnonations indexOfObject:annotation];
NSLog(#"Annotation Value:--->%d",annotationValue);
rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame = CGRectMake(40, 5, 20, 22);
[rightButton setBackgroundImage:[UIImage imageNamed:#"listtab_arrow.png"] forState:UIControlStateNormal];
rightButton.tag = annotationValue;
[rightButton addTarget:self action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
}
else
{
[mymapView.userLocation setTitle:#"I am here"];
}
return pinView;
}
- (IBAction)showDetails:(UIView *)sender
{
NSInteger selectedIndex = sender.tag;
list = [[ListView alloc] initWithNibName:#"ListView" bundle:nil];
details = [[resData valueForKey:#"reference"] mutableCopy];
NSLog(#"Reference:--->%#",details);
list.refernceIndex = [NSString stringWithFormat:#"%#",[details objectAtIndex:selectedIndex]];
[appDelegate.navigationController pushViewController:list animated:YES];
}

viewForAnnotation Not Called Until Map is Moved

viewForAnnotation is not being called until I move or zoom in on the map. Because of this, my annotations do not show until the map is touched. Any idea why?
NSString *incident;
for (incident in weekFeed) {
NSString *finalCoordinates = [[NSString alloc] initWithFormat:#"%#", [incident valueForKey:#"coordinates"]];
NSArray *coordinatesArray = [finalCoordinates componentsSeparatedByString:#","];
latcoord = (#"%#", [coordinatesArray objectAtIndex:0]);
longcoord = (#"%#", [coordinatesArray objectAtIndex:1]);
// Final Logs
NSLog(#"Coordinates in NSString: [%#] - [%#]", latcoord, longcoord);
CLLocationCoordinate2D coord;
coord.latitude = [latcoord doubleValue];
coord.longitude = [longcoord doubleValue];
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [incident valueForKey:#"incident_type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [incident valueForKey:#"note"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
[ann release];
}
// Custom Map Markers
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil; //return nil to use default blue dot view
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.canShowCallout = YES;
if ([annotationView.annotation.title isEqualToString:#"one"]) {
UIImage *pinImage = [UIImage imageNamed:#"marker_1.png"];
[annotationView setImage:pinImage];
}
if ([annotationView.annotation.title isEqualToString:#"two"]) {
UIImage *pinImage = [UIImage imageNamed:#"marker_2.png"];
[annotationView setImage:pinImage];
}
annotationView.annotation = annotation;
return annotationView;
}
- (void) mapView:(MKMapView *)mapV didAddAnnotationViews:(NSArray *)views {
CGRect visibleRect = [mapV annotationVisibleRect];
for (MKAnnotationView *view in views) {
CGRect endFrame = view.frame;
CGRect startFrame = endFrame; startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
view.frame = startFrame;
[UIView beginAnimations:#"drop" context:NULL];
[UIView setAnimationDuration:0.4];
view.frame = endFrame;
[UIView commitAnimations];
}
}
I solved it by using [self performSelectorInBackground:#selector(loadEverything) withObject:self]; instead of detachThreadSelector. That code (in viewDidLoad) wasn't originally posted.
Thanks for helping everyone!

impossible to show 2 colors in mapkit

ok desperation. This is killing me.. I totally do not understand MapKit at all.. Despite reading so many tutorial.. =(
For more information, I have 2 annotation classes - MyAnnotation and MyAnnotation2, it doesnt seems to work too.. Somebody plz help.. I am afraid I have no hair left soon =(
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
_annotations = [[NSMutableArray alloc] init];
_annotation2 = [[NSMutableArray alloc] init];
CLLocation *userLoc = _mapView.userLocation.location;
CLLocationCoordinate2D userCoordinate = userLoc.coordinate;
NSLog(#"user latitude = %f",userCoordinate.latitude);
NSLog(#"user longitude = %f",userCoordinate.longitude);
_listOfPolyClinics = [[NSMutableArray alloc] init];
_listOfPatients = [[NSMutableArray alloc] init ];
for (PolyClinics *polyclinics in [[PatientDatabase database]
polyClinics]){
[_listOfPolyClinics addObject:polyclinics];
}
NSLog(#"%i", [_listOfPolyClinics count]);
for (PatientDetails *patientDetails in [[PatientDatabase database]
patientCategoryList:_category]){
[_listOfPatients addObject:patientDetails];
}
NSLog(#"%i", [_listOfPatients count]);
for (PolyClinics *polyclinics in _listOfPolyClinics){
MyAnnotation * myAnnotation =[[MyAnnotation alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.longitude = polyclinics.longtitude;
theCoordinate.latitude = polyclinics.latitude;
myAnnotation.pinColor = MKPinAnnotationColorPurple;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = polyclinics.name;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",polyclinics.telephone];
//myAnnotation.annotationsPatients =
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}
for(PatientDetails *patientDetails in _listOfPatients){
MyAnnotation2 * myAnnotation =[[MyAnnotation2 alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.longitude = patientDetails.longitude;
theCoordinate.latitude = patientDetails.latitude;
myAnnotation.pinColor = MKPinAnnotationColorGreen;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = patientDetails.nric;
myAnnotation.subtitle = [NSString stringWithFormat:#"%i",patientDetails.category];
[_mapView addAnnotation:myAnnotation];
[_annotation2 addObject:myAnnotation];
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(#"%i", [_annotation2 count]);
MKPinAnnotationView *pinView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:[annotation title]];
for(id <MKAnnotation> a in _annotation2){
if([a isKindOfClass:[MyAnnotation class]]){
pinView.pinColor = MKPinAnnotationColorPurple;
}
else{
pinView.pinColor = MKPinAnnotationColorGreen;
}
pinView.animatesDrop=NO;
pinView.canShowCallout=YES;
return [pinView autorelease];
}
return pinView;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation;
is called every time the MKMapView needs to show a view for an annotation, it passes you that annotation for a reason. So instead of iterating through them and returning only the color for the first one in your array (you need to understand that returning from a function/method doesn't let the loop iterate more), use the parameter instead.
Also a good practice is to use
- (MKAnnotationView *)dequeueReusableAnnotationViewWithIdentifier:(NSString *)identifier;
so the AnnotationViews don't get created again from scratch, especially memory-wise!
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
BOOL isGreen = YES;
if([annotation isKindOfClass:[MyAnnotation class]])
isGreen = NO;
MKPinAnnotationView *pinView = nil;
if (isGreen) {
static NSString *greenPin = #"greenPin";
pinView = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:greenPin];
if (!pinView) {
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:greenPin] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.animatesDrop = NO;
pinView.canShowCallout = YES;
}
else
pinView.annotation = annotation;
}
else {
static NSString *purplePin = #"purplePin";
pinView = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:purplePin];
if (!pinView) {
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:purplePin] autorelease];
pinView.pinColor = MKPinAnnotationColorPurple;
pinView.animatesDrop = NO;
pinView.canShowCallout = YES;
}
else
pinView.annotation = annotation;
}
return pinView;
}

- (MKAnnotationView *)mapView not getting called

In my code, the - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation method is not getting called. I don know why. Can anyone please help me?
Below is my code:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:#","];
NSLog(#"pin map");
if(pinView == nil)
{
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#""];
pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
UIImage *image = [UIImage imageNamed:#"ann.png"];
CGRect resizeRect;
resizeRect.size = image.size;
CGSize maxSize = CGRectInset(self.view.bounds,
[map annotationPadding],
[map annotationPadding]).size;*/
maxSize.height -= self.navigationController.navigationBar.frame.size.height + [map calloutHeight];
if (resizeRect.size.width > maxSize.width)
resizeRect.size = CGSizeMake(maxSize.width, resizeRect.size.height / resizeRect.size.width * maxSize.width);
if (resizeRect.size.height > maxSize.height)
resizeRect.size = CGSizeMake(resizeRect.size.width / resizeRect.size.height * maxSize.height, maxSize.height);
resizeRect.origin = (CGPoint){0.0f, 0.0f};
UIGraphicsBeginImageContext(resizeRect.size);
[image drawInRect:resizeRect];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
pinView.image = resizedImage;
pinView.opaque = NO;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
if (annotation == mapView.userLocation)
{
return nil;
}
return pinView;
}
else
{
pinView.annotation = annotation;
}
return pinView;
}
This is how I am adding the annotations to the map:
-(void) Annotations:(int)i
{
/*NSString* address = [mpartyDetail objectAtIndex:i];
address = [[address componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: #""];
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv", address];
NSLog(#"nsstring %#",urlString);
NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
NSLog(#"location string %#",locationString);
NSArray *latlng = [locationString componentsSeparatedByString:#","];
NSLog(#"the latlng %#",latlng);
float lat = [[latlng objectAtIndex:2] floatValue];
float lng = [[latlng objectAtIndex:3] floatValue]; */
NSLog(#"ann");
lat = [[latiArray objectAtIndex:i]floatValue];
lng = [[longiArray objectAtIndex:i]floatValue];
CLLocationCoordinate2D newCoord = {lat,lng};
mapAnnotations* annotation = [[mapAnnotations alloc] initWithCoordinate:newCoord];
[mapView addAnnotation:annotation];
}
mapAnnotations is another class. The below code shows the method of that class which is getting called:
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate{
NSLog(#"the cor");
self = [super init];
if (self != nil) {
NSLog(#"in");
_coordinate = coordinate;
}
return self;
}
The idea is that I add annotations when the user presses on the map and the user can give any title to that pin. I need a callout to show the title entered by the user. The annotations are getting added. But I am not able to get the callout as this method is not getting called.
Did you assign the class containing that method as the delegate for your map view, did you actually add any annotations to the map view, and are the locations for those annotations actually visible in the portion of the map currently displayed on-screen?
as someone rightly pointed out the delegate wasnt set to the same class in my case
all i did was in the code where i add annotation i wrote the code:
mapView.delegate=self;
and it worked great for me.
if you didnt do that do it and it might work for you also droid.
How are you adding annotations to your map? I use the following
while(some condition){
MapAnnotation *annotation = [[MapAnnotation alloc] initWithLatitude:(float)goLat Longitude:(float)goLng title:(NSString*)recallTask.blurb subtitle:(NSString*)recallTask.location];
[appDelegate.annArray addObject:annotation];
[annotation release];
annotation = nil;
}
[self.mapView addAnnotations:appDelegate.annArray];