2012-08-16 54 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