将图像添加到MKPointAnnotation

时间:2011-03-30 21:13:03

标签: objective-c cocoa-touch

有可能吗?

我在这里执行了一个给我一个针脚的动作。但我需要一个图像。 MKAnnotation对我来说似乎很复杂。

        - (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);



            MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
            [annotation setCoordinate:coordinate];
            [annotation setTitle:@"Some Title"];
            [myMap addAnnotation:annotation];




            // Coloca o icone
            [self.view addSubview:mapa];


        }

谢谢!

1 个答案:

答案 0 :(得分:23)

您需要设置MKMapViewDelegate并实施

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation

这是从Apple开发者网站上提供的MapCallouts示例代码中窃取的示例代码。我已将其修改为专注于重要细节。您可以在下面看到关键是在注释视图上设置图像,并从此方法返回该注释视图。

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
        static NSString *SFAnnotationIdentifier = @"SFAnnotationIdentifier";
        MKPinAnnotationView *pinView =
            (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:SFAnnotationIdentifier];
        if (!pinView)
        {
            MKAnnotationView *annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                           reuseIdentifier:SFAnnotationIdentifier] autorelease];
            UIImage *flagImage = [UIImage imageNamed:@"flag.png"];
            // You may need to resize the image here.
            annotationView.image = flagImage;
            return annotationView;
        }
        else
        {
            pinView.annotation = annotation;
        }
        return pinView;
}

我们使用dequeueReusableAnnotationViewWithIdentifier来获取已创建的视图,以重用我们的注释视图。如果没有返回,我们创建一个新的。这可以防止我们创建数百个MKAnnotationViews,如果只有少数MKAnnotationView同时出现。

相关问题