如何在MKMapView上添加Map注释?

时间:2011-03-30 20:15:32

标签: objective-c cocoa-touch

嘿,我试图在我的地图上添加注释。我该怎么办?

继承我的代码:

- (void)abreMapa:(NSString *)endereco {

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", 
                       [endereco stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

double latitude = 0.0;
double longitude = 0.0;

if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
    latitude = [[listItems objectAtIndex:2] doubleValue];
    longitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
    //Show error
}

CLLocationCoordinate2D coordinate;
coordinate.latitude = latitude;
coordinate.longitude = longitude;
myMap.region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000);

[self.view addSubview:mapa];


 }

谢谢!

3 个答案:

答案 0 :(得分:16)

由于MKAnnotation是一种协议,因此您必须定义自己的实现协议的类。例如,

@interface SPAnnotation : NSObject <MKAnnotation> {
    CLLocationCoordinate2D coordinate;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;

如果您有想要映射的位置的纬度,经度:

SPAnnotation *annotation = [[Annotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];
[myMap addAnnotation:annotation];

答案 1 :(得分:0)

您还必须编写采用MKAnnotation协议的注释类。 e.g:

@interface MyMapAnnotation : NSObject <MKAnnotation> {
...
}

答案 2 :(得分:0)

试试这个

Pin *selected = [[Pin alloc] init];

for(i=0; i<[[newxml dataarray] count]; i++)
{
    gapi = [newxml.dataarray objectAtIndex:i]; 
    MKCoordinateRegion region ;  // = { {0.0, 0.0 }, { 0.0, 0.0 } }; 
    region.center. latitude = [gapi.lat floatValue];
    region.center. longitude = [gapi.lng floatValue];

    region.span.longitudeDelta = 0.05f;
    region.span.latitudeDelta = 0.05f;

    [self.mapview setRegion:region animated:YES]; 

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

    myAnnotation1.coordinate=region.center;;
    myAnnotation1.title=gapi.name;
    myAnnotation1.itemIndex = i;
    myAnnotation1.subtitle=gapi.address;
    [self.mapview addAnnotation:myAnnotation1];

    if (j == i)
    {  
            selected = myAnnotation1;
    }

    if(k==123)
    {
        [self.mapview selectAnnotation:selected animated:NO]; 
    }

}