我是iOS开发中的新手我想在iOS中的MKMapViewController中显示多个注释,因为我在viewDidLoad方法中编写代码
- (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;
}
但它没有在MKMapViewController中显示任何注释,请给我解决方案。
答案 0 :(得分:8)
我已经在这里编写了一个演示应用程序,它会向您展示一种方法,使您的代码更加清洁和可重复使用,同时考虑到Paulw11的建议。
注意,这个方法完全是用代码完成的,没有接口构建器。
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController <MKMapViewDelegate>
@property (nonatomic, strong) MKMapView *mapView;
@end
- (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];
}
如果你缩小一点,你会看到所有三个引脚:
答案 1 :(得分:1)
您应该使用函数CLLocationCoordinate2DMake
在一行中初始化您的位置对象。更重要的是,您需要为每个注释分配一个新的注释对象 -
- (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;
}
答案 2 :(得分:0)
//
// 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