How to Show Multiple Annotation in MKMapView iOS?

試著忘記壹切 提交于 2019-12-12 09:45:48

问题


i am newbie in iOS Development i want to Show multiple Annotation in MKMapViewController in iOS for that i write a code as in my viewDidLoad method

- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate=self;
NSArray *name=[[NSArray alloc]initWithObjects:
               @"VelaCherry",
               @"Perungudi",
               @"Tharamani", nil];
self.annotation=[[NSMutableArray alloc]initWithCapacity:[name count]];
MKPointAnnotation *mappin=[[MKPointAnnotation alloc]init];

CLLocationCoordinate2D location;

location.latitude=(double)12.970760345459;
location.longitude=(double)80.2190093994141;
mappin.coordinate=location;
mappin.title=[name objectAtIndex:0];
[self.annotation addObject:mappin];

location.latitude=(double)12.9752297537231;
location.longitude=(double)80.2313079833984;
mappin.coordinate=location;
mappin.title=[name objectAtIndex:1];
[self.annotation addObject:mappin];

location.latitude=(double)12.9788103103638;
location.longitude=(double)80.2412414550781;
mappin.title=[name objectAtIndex:2];
[self.annotation addObject:mappin];

[self.mapView addAnnotations:self.annotation];
self.mapView.mapType = MKMapTypeStandard;
self.mapView.showsUserLocation = YES;
}

But it is not show any of annotation in MKMapViewController please give me Solution for this.


回答1:


I've written a demo app here which shows you one way to make your code a bit more cleaner and reusable, taking into account Paulw11's sugggestion.

Note, this method is purely done with code, no interface builder.

ViewController.h

#import <MapKit/MapKit.h>

@interface ViewController : UIViewController <MKMapViewDelegate>

@property (nonatomic, strong) MKMapView *mapView;

@end

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self initViews];
    [self initConstraints];

    [self addAllPins];
}

-(void)initViews
{
    self.mapView = [[MKMapView alloc] init];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;

    MKCoordinateRegion region = self.mapView.region;

    region.center = CLLocationCoordinate2DMake(12.9752297537231, 80.2313079833984);

    region.span.longitudeDelta /= 1.0; // Bigger the value, closer the map view
    region.span.latitudeDelta /= 1.0;
    [self.mapView setRegion:region animated:NO]; // Choose if you want animate or not

    [self.view addSubview:self.mapView];
}

-(void)initConstraints
{
    self.mapView.translatesAutoresizingMaskIntoConstraints = NO;

    id views = @{
                 @"mapView": self.mapView
                 };

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mapView]|" options:0 metrics:nil views:views]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[mapView]|" options:0 metrics:nil views:views]];
}

-(void)addAllPins
{
    self.mapView.delegate=self;

    NSArray *name=[[NSArray alloc]initWithObjects:
                   @"VelaCherry",
                   @"Perungudi",
                   @"Tharamani", nil];

    NSMutableArray *arrCoordinateStr = [[NSMutableArray alloc] initWithCapacity:name.count];

    [arrCoordinateStr addObject:@"12.970760345459, 80.2190093994141"];
    [arrCoordinateStr addObject:@"12.9752297537231, 80.2313079833984"];
    [arrCoordinateStr addObject:@"12.9788103103638, 80.2412414550781"];

    for(int i = 0; i < name.count; i++)
    {
        [self addPinWithTitle:name[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;

    [self.mapView addAnnotation:mapPin];
}

If you zoom out a little, you'll see all three pins:




回答2:


You should use the function CLLocationCoordinate2DMake to initialise your location objects in a single line. More importantly you need to allocate a new annotation object for each annotation -

- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView.delegate=self;
NSArray *name=[[NSArray alloc]initWithObjects:
               @"VelaCherry",
               @"Perungudi",
               @"Tharamani", nil];
self.annotation=[[NSMutableArray alloc]initWithCapacity:[name count]];

MKPointAnnotation *mappin;

CLLocationCoordinate2D location;

location = CLLocationCoordinate2DMake(12.970760345459,80.2190093994141);
mappin = [[MKPointAnnotation alloc]init];
mappin.coordinate=location;
mappin.title=[name objectAtIndex:0];
[self.annotation addObject:mappin];

mappin = [[MKPointAnnotation alloc]init];
location = CLLocationCoordinate2DMake(12.9752297537231,80.2313079833984);
mappin.coordinate=location;
mappin.title=[name objectAtIndex:1];
[self.annotation addObject:mappin];

mappin = [[MKPointAnnotation alloc]init];
location = CLLocationCoordinate2DMake(12.9788103103638,80.2412414550781);
mappin.coordinate=location;
mappin.title=[name objectAtIndex:2];
[self.annotation addObject:mappin];

[self.mapView addAnnotations:self.annotation];
self.mapView.mapType = MKMapTypeStandard;
self.mapView.showsUserLocation = YES;
}



回答3:


//
//  MyAnnotation.h
//  SimpleMapView
//
//  Created by Mayur Birari.

//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MyAnnotation : NSObject<MKAnnotation> {

    CLLocationCoordinate2D  coordinate;
    NSString*               title;
    NSString*               subtitle;
}

@property (nonatomic, assign)   CLLocationCoordinate2D  coordinate;
@property (nonatomic, copy)     NSString*               title;
@property (nonatomic, copy)     NSString*               subtitle;

@end




//
//  MyAnnotation.m
//  SimpleMapView
//
//  Created by Mayur Birari .

//

#import "MyAnnotation.h"


@implementation MyAnnotation

@synthesize title;
@synthesize subtitle;
@synthesize coordinate;

- (void)dealloc 
{
    [super dealloc];
    self.title = nil;
    self.subtitle = nil;
}
@end



//
//  RootViewController.h
//  SimpleMapView
//
//  Created by Mayur Birari.

//

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "UserProfileVC.h"

@interface RootViewController : UIViewController<MKMapViewDelegate> {

    IBOutlet MKMapView* mapView;
    IBOutlet UserProfileVC* userProfileVC; 

}
@property(nonatomic,retain) IBOutlet MKMapView* mapView;
@property(nonatomic,retain) IBOutlet UserProfileVC* userProfileVC; 
@end


//
//  RootViewController.m
//  SimpleMapView
//
//  Created by Mayur Birari.
//

#import "RootViewController.h"
#import "MyAnnotation.h"
#import "UserProfileVC.h"


@implementation RootViewController

@synthesize mapView,userProfileVC;


#pragma mark -
#pragma mark View lifecycle

- (void)gotoLocation
{
    // start off by default in San Francisco
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = 37.786996;
    newRegion.center.longitude = -122.440100;
    newRegion.span.latitudeDelta = 0.112872;
    newRegion.span.longitudeDelta = 0.109863;

    [self.mapView setRegion:newRegion animated:YES];
}


- (void)viewDidLoad {
    [super 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];

    CLLocationCoordinate2D theCoordinate1;
    theCoordinate1.latitude = 37.786996;
    theCoordinate1.longitude = -122.419281;

    CLLocationCoordinate2D theCoordinate2;
    theCoordinate2.latitude = 37.810000;
    theCoordinate2.longitude = -122.477989;

    CLLocationCoordinate2D theCoordinate3;
    theCoordinate3.latitude = 37.760000;
    theCoordinate3.longitude = -122.447989;

    CLLocationCoordinate2D theCoordinate4;
    theCoordinate4.latitude = 37.80000;
    theCoordinate4.longitude = -122.407989;

    MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];

    myAnnotation1.coordinate=theCoordinate1;
    myAnnotation1.title=@"Rohan";
    myAnnotation1.subtitle=@"in the city";

    MyAnnotation* myAnnotation2=[[MyAnnotation alloc] init];

    myAnnotation2.coordinate=theCoordinate2;
    myAnnotation2.title=@"Vaibhav";
    myAnnotation2.subtitle=@"on a Bridge";

    MyAnnotation* myAnnotation3=[[MyAnnotation alloc] init];

    myAnnotation3.coordinate=theCoordinate3;
    myAnnotation3.title=@"Rituraaj";
    myAnnotation3.subtitle=@"in the forest";

    MyAnnotation* myAnnotation4=[[MyAnnotation alloc] init];

    myAnnotation4.coordinate=theCoordinate4;
    myAnnotation4.title=@"Amit";
    myAnnotation4.subtitle=@"at Russian Hill";

    [mapView addAnnotation:myAnnotation1];
    [mapView addAnnotation:myAnnotation2];
    [mapView addAnnotation:myAnnotation3];
    [mapView addAnnotation:myAnnotation4];

    [annotations addObject:myAnnotation1];
    [annotations addObject:myAnnotation2];
    [annotations addObject:myAnnotation3];
    [annotations addObject:myAnnotation4];

    NSLog(@"%d",[annotations count]);
    //[self gotoLocation];//to catch perticular area on screen
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    // 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;



    UIBarButtonItem* temp=[[UIBarButtonItem alloc] init];
    temp.title=@"Back";
    self.navigationItem.backBarButtonItem=temp;
    [temp release];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/


 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationLandscapeLeft || UIInterfaceOrientationLandscapeRight);
}



#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


#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 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;
}

-(IBAction)showDetails:(id)sender{

    NSLog(@"Annotation Click");
    self.userProfileVC.title=((UIButton*)sender).currentTitle;
    [self.navigationController pushViewController:self.userProfileVC animated:YES];
}
- (void)dealloc {
    [super dealloc];
}


@end


来源:https://stackoverflow.com/questions/27163318/how-to-show-multiple-annotation-in-mkmapview-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!