我已经从一个 xml 文件中读取了纬度和经度,我想用它们添加一些注释。但除了用户位置外,没有一个被添加。mapview.annotations 的计数始终为空。这是我的代码:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (newLocation != nil) {
self.myLocation = newLocation;
}
mapView.region = MKCoordinateRegionMake(self.myLocation.coordinate, MKCoordinateSpanMake(0.005f, 0.005f));
mapView.zoomEnabled = YES;
//mapView.showsUserLocation = YES;
mapView.centerCoordinate = self.myLocation.coordinate;
MKPointAnnotation *userLocation = [[MKPointAnnotation alloc] init];
userLocation.coordinate = myLocation.coordinate;
userLocation.title = @"my position";
userLocation.subtitle = @"my position now";
[mapView removeAnnotations:mapView.annotations];
[mapView addAnnotation:userLocation];
[userLocation release];
if ([self.positionArray count] < 5) {
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"position" ofType:@"xml"];
NSData *positionData = [[NSData alloc] initWithContentsOfFile:dataPath];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:positionData];
parser.delegate = self;
[parser parse];
}
if (self.myLocation != nil) {
[self.manager stopUpdatingLocation];
}
}
这是 MapInfo 类:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface MapInfo : NSObject<MKAnnotation>
{
NSString *subtitle;
NSString *title;
CLLocationCoordinate2D coordinate;
}
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- (id)initWithCoordinate:(CLLocationCoordinate2D)location;
- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate;
@end
然后这里是委托方法
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *AnnotationIdentifier = @"AnnotationIdentifer";
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if ([annotation isKindOfClass:[MapInfo class]]) {
if (pinView == nil) {
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
}
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}else if([annotation isKindOfClass:[MKPointAnnotation class]])
{
if (pinView == nil) {
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
}
pinView.pinColor = MKPinAnnotationColorPurple;
pinView.canShowCallout = YES;
pinView.animatesDrop = NO;
}
return pinView;
}
我真的不知道为什么只能添加用户位置,请高人帮帮我!!困扰了我好几天!