将图像添加到MKPointAnnotation

Luc*_*iga 6 cocoa-touch objective-c

可能吗?

我在这里执行了一个给我一个针脚的动作.但我需要一个图像.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];


        }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ste*_*tto 23

您需要设置MKMapViewDelegate并实现

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
Run Code Online (Sandbox Code Playgroud)

这是从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;
}
Run Code Online (Sandbox Code Playgroud)

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