How to show annotations randomly - ios

I want to show different annotations at each pin,with my image named "01.png" to "08.png".
I set integer a random number from 1~8
integer = arc4random() % 8 + 1;
then set the method -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation
if(annotation == mapView.userLocation){
return nil;
}
NSString *identifier = #"Store";
MKAnnotationView *result = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if(result == nil){
result = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
} else {
result.annotation = annotation;
}
NSString * imageName = [NSString stringWithFormat:#"0%i",integer];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",imageName]];
result.image = image;
return result;
but the mapView show the same annotations,it will show different annotations at each time I open the apps.
How to show different annotations at each pin?
Thank you very much!

You must put the randomization inside the annotation method. A variable has one value until it is changed, it does not get a new random value every time you read from it.

Related

Annotation map pin title showing wrongly

Annotation pin title shows same title for all pins. I have set label to show the title of each pin but I am getting same title for all labels. I did NSLog
of lbl.text and in NSLog it shows different title.
Why am I getting same title for all map pins.
-(void)maprequests
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *emailid = [prefs stringForKey:#"email"];
NSString *deviceid = [Request UDID];
//NSString * walkGUID=[prefs stringForKey:#"walkguid"];
//NSLog(#"walkGUID:%#",walkGUID);
NSString * walkguid=[prefs stringForKey:#"walkguid"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://10.0.0.28/web/ws/get_poilist_walks.php?strEmailID=%#&strDeviceID=%#&strWalkGuid=%#",emailid,deviceid,walkguid]];
NSLog(#"%#",url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
self.pointofintrests = [responseObject objectForKey:#"PointOfIntrests"];
NSIndexPath *indexpath;
NSDictionary *tempDictionary= [self.pointofintrests objectAtIndex:indexpath.row];
for (NSDictionary *dictionary in _pointofintrests)
{
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
NSString * latitude= [dictionary objectForKey:#"Latitude"];
NSString * longitude =[dictionary objectForKey:#"Longitude"];
double strlatitude = [latitude doubleValue];
double strlongitude = [longitude doubleValue];
region.center.latitude =strlatitude;
region.center.longitude = strlongitude;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[_mapview setRegion:region animated:YES];
[_mapview setDelegate:self];
DisplayMap *ann = [[DisplayMap alloc] init];
ann.coordinate = region.center;
[_mapview addAnnotation:ann];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Request Failed: %#, %#", error, error.userInfo);
}];
[operation start];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
MKPinAnnotationView *pinView = nil;
UILabel *label;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil ) pinView = [[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID];
if(![annotation isKindOfClass:[DisplayMap class]])
return nil;
DisplayMap *a = (DisplayMap *)annotation;
pinView.image=[UIImage imageNamed:#"push_pin#2x"];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 250, 30)];
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor whiteColor];
lbl.alpha = 0.5;
lbl.tag = 42;
for (int i=0; i<_pointofintrests.count; i++)
{
lbl.text = [[_pointofintrests valueForKey:#"title"] objectAtIndex:i];
}
[pinView addSubview:lbl];
[_mapview selectAnnotation:pinView animated:YES];
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
else
{
}
return pinView;
}
Your problem is you are looping over _pointofinterests
for (int i=0; i<_pointofintrests.count; i++)
{
lbl.text = [[_pointofintrests valueForKey:#"title"] objectAtIndex:i];
}
This isn't doing what you think. Its assigning the last title in the array to every pin.
Because the viewForAnnotation delegate method gives you the annotation that will display, I tend to keep an array of annotations to save the index, and therefore you can access your data correctly.
When you call [_mapview addAnnotation:ann]; also save ann into an array.
You should then be able todo something like:
[[_pointofintrests valueForKey:#"title"] objectAtIndex:[annArray indexOfObject:annotation]]
As a side note, if _pointofinterests is an NSDictionary I would use objectForKey instead.
The main reason you are getting the same label text on all pins is, as already pointed out in another answer, that for every pin, lbl.text is always set to the title of the last object in _pointofintrests.
The solution I would prefer however is to set the annotation's title and use that to set the label's text.
When creating the annotation and before calling addAnnotation, set its title property:
DisplayMap *ann = [[DisplayMap alloc] init];
ann.coordinate = region.center;
ann.title = [dictionary objectForKey:#"title"]; //<-- add this line
[_mapview addAnnotation:ann];
In viewForAnnotation, instead of the for loop, you can simply set the label's text to the annotation's title (no searching of arrays or looping):
//for (int i=0; i<_pointofintrests.count; i++)
//{
// lbl.text = [[_pointofintrests valueForKey:#"title"] objectAtIndex:i];
//}
lbl.text = annotation.title;
That technically fixes the problem of the same text appearing on all pins.
However, there are some other issues with the code in viewForAnnotation which will become apparent after the above fix:
The UILabel is being added to the annotation view even if the annotation view was dequeued (meaning a previously created view is being re-used). That dequeued view will already have a UILabel in it and the existing code will add another one on top. After panning and zooming the map for a while, you will notice overlapping labels for each pin.
The UILabel should only be added when a new view is created (when the dequeue returns nil and you alloc+init a new one).
Another problem is that since you are using a custom image for your annotations, you should create a plain MKAnnotationView instead of an MKPinAnnotationView. The MKPinAnnotationView class is designed for showing the standard, built-in pin image and although it still has an image property, it tends to sometimes ignore that and revert to showing its standard pin image.
Another problem is this line:
[_mapview selectAnnotation:pinView animated:YES];
The map view can only have one annotation "selected" at a time so if you were thinking that calling this in viewForAnnotation would show the callout for all the annotations at once, then that is mistaken.
The selectAnnotation method requires the annotation as the first parameter. The pinView is not the annotation -- it is the annotation's view (they are not the same thing). The compiler must be complaining about this line and at run-time, the system is probably showing an error in the console saying something like "Trying to select an annotation which has not been added". So technically, the line should be [_mapview selectAnnotation:annotation animated:YES];
Regardless, do not call selectAnnotation in the viewForAnnotation delegate method. Doing so may lead to recursion and a stack overflow (and an EXC_BAD_ACCESS) because the select causes the annotation's view to be updated which causes viewForAnnotation to be called, etc. Instead, call it in the didAddAnnotationViews delegate method for the one annotation you want to show the callout for.
Your revised viewForAnnotation delegate method might look like this:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if(! [annotation isKindOfClass:[DisplayMap class]])
{
return nil;
}
static NSString *defaultPinID = #"MyPin";
int lblTag = 42;
MKAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if (pinView == nil)
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID];
pinView.image = [UIImage imageNamed:#"push_pin#2x"];
pinView.canShowCallout = YES;
//Create and add the label to the view ONCE when creating the view...
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 250, 30)];
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor whiteColor];
lbl.alpha = 0.5;
lbl.tag = lblTag;
[pinView addSubview:lbl];
}
else
{
//If we are re-using a dequeued view
//update its annotation reference...
//(otherwise view will still be pointing to its previous annotation)
pinView.annotation = annotation;
}
//At this point, we have a new or dequeued view
//pointing to the current annotation.
//Now update the label that will already be there
//with the current annotation's title...
UILabel *lbl = (UILabel *)[pinView viewWithTag:lblTag];
lbl.text = annotation.title;
return pinView;
}
Remember you'll need to set the annotation's title as shown at the top of the answer as well.
There are also some things in the for loop in the maprequests method that I want to point out:
It's not necessary to create and set a region just to set the annotation's coordinate. Calling setRegion in the loop is pointless and inefficient since the user will only end up seeing the map positioned at the last annotation anyway. To set an annotation coordinate, just do:
ann.coordinate = CLLocationCoordinate2DMake(strlatitude, strlongitude);
You can call setRegion (once) after the for loop (or just call [_mapview showAnnotations:_mapview.annotations animated:YES]; so you don't have to yourself calculate the region that shows all the annotations).
You don't need to set the map view's delegate inside the for loop repeatedly. Set the delegate (once) before the for loop (though it should already have been set long before this method is called).

MKAnnotationView images has replaced after zoom or reopen tap

I am parse Json with coordinates and download individual profile image for each annotation view. When I do zoom or move on map I see what images replaced on wrong places. For example I have annotation view with coordinates 111.1111, 111.1111. First time image and coordinate is correct, but after moves/zoom/reopen tab with map I see other annotation view with coordinates 222.222, 222.222 with image which is suitable for 111.111, 111.1111.
(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *identifier = #"SYLocationItem";
if ([annotation isKindOfClass:[SYLocationItem class]]) {
MKAnnotationView *annotationView = (MKAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = NO;
SYJabberClient *client = [SYJabberClient sharedClient];
[client retrieveProfileForUserWithEmail:[(SYLocationItem*)annotation email]
withSuccessBlock:^(NSDictionary *dict, NSError *error) {
if (dict) {
UIImage *image = [dict objectForKey:#"imageFile"];
UIImage *displayImage = [UIImage circularScaleNCrop:image
withRect:
CGRectMake(0.0f,0.0f,30.0f,30.0f)];
annotationView.image = displayImage;
}
}];
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
In this code now I get image from local, but if downloading images I have same issue.

Building MapView Annotations is very slow

I have an application which shows something around 100 Annotations (with custom pin-images, callout accessories and annotation-images) in a MapView. While building the annotations I store a link between annotation and building so I can assign the right building and open the right segue afterwards.
In iOS 6 they get built really fast, I also enabled animation while adding them, so one pin got dropped after the other, but with apple maps in iOS7 this isn't possible anymore (?). Now building those 100 annotations takes over 1 second on my iPhone 4S and that's too long. Is there anyway to improve the code?
- (void)viewDidLoad
...
//creating annotations
annotationlink = [[NSMutableArray alloc] init];
for (int i = 0; i < data.count; i++) {
NSDictionary *dataItem = [data objectAtIndex:i];
//storing annotation in array for link
Annotation *buildingannotation = [[Annotation alloc] init];
NSNumber *index = [NSNumber numberWithInteger:i];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:index, indexKey, buildingannotation, annotationKey, nil];
[annotationlink addObject:dict];
buildingannotation.title = [dataItem objectForKey:#"Building"];
buildingannotation.subtitle = [dataItem objectForKey:#"Info"];
MKCoordinateRegion buildingcoordinates;
buildingcoordinates.center.latitude = [[dataItem objectForKey:#"Latitude"] floatValue];
buildingcoordinates.center.longitude = [[dataItem objectForKey:#"Longitude"] floatValue];
buildingannotation.coordinate = buildingcoordinates.center;
[self.mapView addAnnotation:buildingannotation];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]){
return nil;
}
MKAnnotationView *pinView = (MKAnnotationView *)
[self.mapView dequeueReusableAnnotationViewWithIdentifier:pinIdentifier];
MKAnnotationView *customAnnotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinIdentifier];
customAnnotationView.canShowCallout = YES;
//right button to detail view
UIButton* disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
customAnnotationView.rightCalloutAccessoryView = disclosureButton;
//left button for image
NSInteger *buildingindex = [self getIndex:annotation];
NSDictionary *dataItem = [data objectAtIndex:buildingindex];
NSString* filename = [dataItem objectForKey:#"Thumb"];
filename = [filename stringByAppendingString:#"#2x.jpg"];
NSString* resourceimagePath = [resourcePath stringByAppendingPathComponent:filename];
Image = [UIImage imageWithContentsOfFile:resourceimagePath];
UIImageView *AnnotationThumb = [[UIImageView alloc] initWithImage:Image];
AnnotationThumb.frame = CGRectMake(0, 0, 31, 31);
customAnnotationView.leftCalloutAccessoryView = AnnotationThumb;
//annotation image
customAnnotationView.image = [UIImage imageNamed:#"Annotation_white.png"];
return customAnnotationView;
return pinView;
}
the following function gets the index of the current annotation using nspredicate to filter the array with the dictionaries. the advantage of this is the fact, that i can also use it when calloutAccessoryControlTapped:
-(NSInteger*) getIndex:(Annotation*)searchannotation
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %#", annotationKey, searchannotation];
NSArray *filteredarray = [annotationlink filteredArrayUsingPredicate:predicate];
NSDictionary *building = [filteredarray objectAtIndex:0];
NSInteger *buildingIndex = [[building objectForKey:indexKey] integerValue];
return buildingIndex;
}
With an iPhone 4S the last pin is built 1.14 seconds after the view gets loaded.
if i search the annotation link array manually instead of using nspredicate function like this:
//left button for image
int buildingIndex;
for (int i = 0; i < annotationlink.count; i++) {
NSDictionary *annotationDict = [annotationlink objectAtIndex:i];
if ([[annotationDict objectForKey:annotationKey] isEqual:annotation]) {
buildingIndex= [[annotationDict objectForKey:indexKey] integerValue];
i = annotationlink.count;
}
}
NSDictionary *dataItem = [data objectAtIndex:buildingIndex];
the log says that the last pin is built 1.89 seconds after the viewDidLoad.
if i create the annotations in viewDidApper instead of viewDidLoad the View is shown off course immediately but the background takes some time to load so until the pins are dropped everything is gray which is also not very nice...
Thank you Anna for your suggestions! I implemented the improvements like this:
Annotation.h:
#import <MapKit/MKAnnotation.h>
#interface Annotation : NSObject <MKAnnotation> {}
#property(nonatomic, assign) CLLocationCoordinate2D coordinate;
#property(nonatomic, copy) NSString *title;
#property(nonatomic, copy) NSString *subtitle;
#property NSInteger *ID;
#end
Annotation.m:
#import "Annotation.h"
#implementation Annotation
#synthesize coordinate, title, subtitle, ID;
#end
ViewDidAppear:
//creating annotations
for (int i = 0; i < data.count; i++) {
NSDictionary *dataItem = [data objectAtIndex:i];
Annotation *buildingannotation = [[Annotation alloc] init];
buildingannotation.ID = i;
buildingannotation.title = [dataItem objectForKey:#"Building"];
buildingannotation.subtitle = [dataItem objectForKey:#"Subtitle"];
MKCoordinateRegion buildingcoordinates;
buildingcoordinates.center.latitude = [[dataItem objectForKey:#"Latitude"] floatValue];
buildingcoordinates.center.longitude = [[dataItem objectForKey:#"Longitude"] floatValue];
buildingannotation.coordinate = buildingcoordinates.center;
[self.mapView addAnnotation:buildingannotation];
}
viewForAnnotation:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]){
return nil;
}
MKAnnotationView *pinView = (MKAnnotationView *)
[self.mapView dequeueReusableAnnotationViewWithIdentifier:pinIdentifier];
if (pinView == nil) {
MKAnnotationView *customAnnotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinIdentifier];
customAnnotationView.canShowCallout = YES;
//right button to detail view
UIButton* disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
customAnnotationView.rightCalloutAccessoryView = disclosureButton;
//left button for image
Annotation *buildingAnnotation = (Annotation *)annotation;
NSInteger *buildingindex = buildingAnnotation.ID;
NSString *filePath = [thumbname objectAtIndex:buildingindex];
UIImageView *AnnotationThumb = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]];
AnnotationThumb.frame = CGRectMake(0, 0, 31, 31);
customAnnotationView.leftCalloutAccessoryView = AnnotationThumb;
//annotation image
customAnnotationView.image = [UIImage imageNamed:#"Annotation_white.png"];
return customAnnotationView;
} else {
pinView.annotation = annotation;
}
return pinView;
}
Callout:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
Annotation *buildingAnnotation = (Annotation *)view.annotation;
selectedbuilding = buildingAnnotation.ID;
[self performSegueWithIdentifier:#"DetailViewController" sender:self];
}
Takes still some time for showing all Annotations. Is there any chance to further improve the code?
I updated the vievForAnnotation function regarding to Anna's reply and the PhotosByLocation Sample Application. It works now and I hope it's the correct way to implement the reuse...
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]){
return nil;
}
MKAnnotationView *buildingAnnotationView = (MKAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:pinIdentifier];
if (buildingAnnotationView) {
[buildingAnnotationView prepareForReuse];
} else {
buildingAnnotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinIdentifier];
buildingAnnotationView.canShowCallout = YES;
//right button to detail view
UIButton* disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
buildingAnnotationView.rightCalloutAccessoryView = disclosureButton;
//annotation image
buildingAnnotationView.image = [UIImage imageNamed:#"Annotation_white.png"];
}
//left button for image
Annotation *buildingAnnotation = (Annotation *)annotation;
NSInteger *buildingindex = buildingAnnotation.ID;
NSString *filePath = [thumbname objectAtIndex:buildingindex];
UIImageView *AnnotationThumb = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]];
AnnotationThumb.frame = CGRectMake(0, 0, 31, 31);
buildingAnnotationView.leftCalloutAccessoryView = AnnotationThumb;
return buildingAnnotationView;
}

Display the different images for the annotation in mkMapview

Based on my different enum values, I need to display the different images in my mapview.
How I can do that ? I am new to iOS development. Please anybody help me.
You need to use "ViewForAnnotation" delegate method in your view Controller.
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation
{
if( [annotation isKindOfClass:[Annotation class] ] )
{
static NSString * AnnotationID = #"Annotation";
Annotation * pannotation = (Annotation *)annotation;
//if( pannotation == nil ) return nil;
MKAnnotationView *annotationView = nil;
annotationView = [self.mMapView dequeueReusableAnnotationViewWithIdentifier:AnnotationID];
if( annotationView == nil )
{
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation
reuseIdentifier:AnnotationID] autorelease];
}
UIImage * flagImage = nil;
if(Your enum Values)
flagImage = [UIImage imageNamed:#"darkgreendot.png"];
else if(....)
flagImage = [UIImage imageNamed:#"orangedot.png"];
else
flagImage = [UIImage imageNamed:#"bluedot.png"];
CGRect resizeRect;
resizeRect.size = flagImage.size;
resizeRect.origin = (CGPoint){0.0f, 0.0f};
UIGraphicsBeginImageContext(resizeRect.size);
[flagImage drawInRect:resizeRect];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
annotationView.image = resizedImage;
return annotationView;
}
}
Hope this helps you.

Plot two different color of mapview pin

I'm trying to display mapview with an array of coordinates. So, i load the latitudes and longitudes from array where those are contains. It is showing perfectly. Now, i want to display one paritcular latitude & longitude with different color pin. I've referred this answer no such different i can't see.
ViewController.m
-(void)showMap:
{
...
...
DataProvider *d = [DataProvider getInstance];
NSInteger numb = sender.view.tag;
d.colorlatitude = [[arraxy objectAtIndex:numb] objectForKey:#"lat"];
d.colorlongitude = [[arraxy objectAtIndex:numb] objectForKey:#"lng"];
[d._address removeAllObjects];
[arraxy removeObjectAtIndex:sender.view.tag];
d._address = arraxy;
MapViewController *map = [[MapViewController alloc]initWithNibName:#"MapViewController" bundle:nil];
[self.navigationController pushViewController:map animated:YES];
}
MapViewController.m
-(void)viewWillAppear:(BOOL)animated
{
DataProvider *d = [DataProvider getInstance];
[_mapView removeAnnotations:_mapView.annotations];
RegisterViewController *appDelegate = [[RegisterViewController alloc]init];
[_mapView setShowsUserLocation:YES];
[_mapView setRegion:MKCoordinateRegionMakeWithDistance([appDelegate.locationManager location].coordinate, 1000, 1000)];
[_mapView setUserTrackingMode:MKUserTrackingModeNone];
MKCoordinateRegion rregion = {{0.0,0.0},{0.0,0.0}};
rregion.center.latitude = [d.colorlatitude floatValue];
rregion.center.longitude = [d.colorlongitude floatValue];
rregion.span.latitudeDelta=0.001f;
rregion.span.longitudeDelta=0.001f;
[_mapView setRegion:rregion];
MapviewAnnotations *add = [[MapviewAnnotations alloc]init];
add.coordinate = rregion.center;
[_mapView addAnnotation:add];
if (d._address)
{
for (int i=0; i<[d._address count]; i++)
{
NSDictionary *dic=[d._address objectAtIndex:i];
MKCoordinateRegion region={{0.0,0.0},{0.0,0.0}};
region.center.latitude=[[dic objectForKey:#"lat"]floatValue];
region.center.longitude=[[dic objectForKey:#"lng"]floatValue];
region.span.latitudeDelta=0.001f;
region.span.longitudeDelta=0.001f;
[_mapView setRegion:region];
MapviewAnnotations *ann=[[MapviewAnnotations alloc]init];
ann.coordinate=region.center;
[_mapView addAnnotation:ann];
}
}
[super viewWillAppear:YES];
}
and my MKMapView's delegate method is
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (![annotation isKindOfClass:[MapviewAnnotations class]])
{
return nil;
}
static NSString *reuseId = #"currentloc";
MKPinAnnotationView *annView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (annView == nil)
{
annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
annView.animatesDrop = NO;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
}
else
{
annView.annotation = annotation;
}
DataProvider *mvAnn = [DataProvider getInstance];
if (mvAnn.colorlatitude) // here i'm checking the condition.
{
annView.pinColor = MKPinAnnotationColorGreen;
}
else
{
annView.pinColor = MKPinAnnotationColorRed;
}
return annView;
}
I'm just writting the condition if the co-ordinate is there i've to plot the green color pin to that particular coordinate only. How to achieve this?
The difference between your code and the one Hinata has referred you to is that the if statement in the other code uses a value (yesno) on the annotation it is currently drawing to decide what colour to use. You are getting a value from DataProvider but not telling it which annotation you are drawing, so the instance it gives you is just what ever the instance method feels like returning at the time the map is asking for the pin. You need to tell it what you're drawing for it to decide what to put into colorlatitude
I've done this through some flags like below inside of my - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
MapviewAnnotations *mvAnn = (MapviewAnnotations *)annotation;
if (mvAnn.flag == 1)
{
annView.pinColor = MKPinAnnotationColorGreen;
}
else if (mvAnn.flag == 10)
{
annView.pinColor = MKPinAnnotationColorPurple;
}
else
{
annView.pinColor = MKPinAnnotationColorRed;
}
In my viewWillAppear i received the coordinates from DataProvider and assigned with separate MapviewAnnotations with flags and differentiate it with three type of pins simply.
Cheers!

Resources