2012-08-16 55 views
0

我对XCode和objective-c非常陌生。这个问题以前可能已经得到了答案,但我无法使其工作。我的目标是在Google地图上显示多个注释。我有一堆Lats和Longs,但是到目前为止,我只能显示一个注释。我如何一次显示所有注释。我有以下为MKMapView代码 -使用XCode Mapkit的多个地址

- (void)viewDidLoad { 

    // Set some coordinates for our position 
    CLLocationCoordinate2D location; 

    location.latitude = (double) 44.271745; 
    location.longitude = (double) -88.453265; 
    // Add the annotation to our map view 
    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Appleton" andCoordinate:location]; 
    [self.mapview addAnnotation:newAnnotation]; 

    [newAnnotation release]; 

    self.mapview.region = MKCoordinateRegionMakeWithDistance(location,100000,100000); 
} 

我明白,我可以遍历和实例newAnnotation然后用addAnnotation添加注释。但我不知道如何去做。这可能是非常基本的,但我对此很新。任何帮助将不胜感激。

// 
// MapViewAnnotation.h 
// 

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

@interface MapViewAnnotation : NSObject <MKAnnotation> { 

    NSString *title; 
    CLLocationCoordinate2D coordinate; 

} 

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

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d; 

@end 

而且

// 
// MapViewAnnotation.m 
// 

#import "MapViewAnnotation.h" 


@implementation MapViewAnnotation 
@synthesize title, coordinate; 

- (id)initWithTitle:(NSString *)ttl andCoordinate:(CLLocationCoordinate2D)c2d { 
    [super init]; 
    title = ttl; 
    coordinate = c2d; 
    return self; 
} 

- (void)dealloc { 
    [title release]; 
    [super dealloc]; 
} 
@end 

回答

1

看起来像你只有一个位置。你应该有经度和纬度列表,然后遍历该列表并实例化MapViewAnnotation。

- (void)viewDidLoad { 
    NSArray *arrayOfLatLong = [NSArray arrayWithObjects: [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"10.22", @"20.212", nil] forKeys:[NSArray arrayWithObjects:@"Lat",@"Long",nil]], 
           [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"10.22", @"24.5", nil] forKeys:[NSArray arrayWithObjects:@"Lat",@"Long",nil]], nil]; 


    for(NSDictionary *location in arrayOfLatLong) { 
     CGFloat latitude = [[location valueForKey:@"Lat"] floatValue]; 
     CGFloat longitude = [[location valueForKey:@"Long"] floatValue]; 

     CLLocationCoordinate2D location; 
     location.latitude = latitude; 
     location.longitude = latitude; 
     MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"Appleton" andCoordinate:location]; 
     [self.mapview addAnnotation:newAnnotation]; 

     [newAnnotation release]; 
     self.mapview.region = MKCoordinateRegionMakeWithDistance(location,100000,100000); 
    } 
} 
+0

谢谢。我根据你的回答改变了代码(用Lat和long代替了Lat-10.22和long-24.5),但是它在'self.mapview.region = ...'行中给我一个错误'location undefined' 。 – Annjawn 2012-08-16 04:05:03

+0

查看更新的代码。最后一个位置被用作mapview的区域 – dianz 2012-08-16 04:09:31

+0

好的,我再次改变它,并在'for'循环中包含'self.mapview.region = ...',它现在可以工作。还有一个问题 - 我如何向阵列添加更多的值(经纬度和长度)。 – Annjawn 2012-08-16 04:10:05