在地图注释中显示图像

时间:2011-02-10 03:41:49

标签: iphone ios4 mkmapview

使用下面的代码,我可以显示标题和副标题,我想在其中显示图像。那可能吗?如果是的话,请帮帮我。

MKPointAnnotation *aAnnotationPoint = [[MKPointAnnotation alloc] init];

aAnnotationPoint.title = @"Virginia";

aAnnotationPoint.subtitle = @"Test of sub title";

// Add the annotationPoint to the map
[myMapView addAnnotation:aAnnotationPoint];

1 个答案:

答案 0 :(得分:17)

我假设您在标注的标注中显示标题和副标题(如果您使用的是针脚,则点击针脚时出现的灰色框)。如果是这样,callout有两个视图供你自定义(leftCalloutAccessoryView和rightCalloutAccessoryView(两者都在注释视图上设置))

因此,如果您希望图像显示在引脚上方的灰色框中,则可以通过实现如下的委托方法来自定义注释视图来执行此操作:

-(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
  // If you are showing the users location on the map you don't want to change it
  MKAnnotationView *view = nil;
  if (annotation != mapView.userLocation) {
    // This is not the users location indicator (the blue dot)
    view = [mapView dequeueReusableAnnotationViewWithIdentifier:@"myAnnotationIdentifier"];
    if (!view) {
      // Could not reuse a view ...

      // Creating a new annotation view, in this case it still looks like a pin
      view = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotationIdentifier"] autorelease];
      view.canShowCallOut = YES; // So that the callout can appear

      UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someName"]];
      myImageView.frame = CGRectMake(0,0,31,31); // Change the size of the image to fit the callout

      // Change this to rightCallout... to move the image to the right side
      view.leftCalloutAccessoryView = myImageView;
      [myImageView release], myImageView = nil;
    }
  }
  return view;
}

然而,如果您想要的只是直接在地图上显示大量图片(而不是在标注中),那么您可以使用相同的委托方法设置“image”属性注释视图,如下所示:

-(MKAnnotationView*)mapView:(MKMapView)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
      // If you are showing the users location on the map you don't want to change it
      MKAnnotationView *view = nil;
      if (annotation != mapView.userLocation) {
        // This is not the users location indicator (the blue dot)
        view = [mapView dequeueReusableAnnotationViewWithIdentifier:@"myAnnotationIdentifier"];
        if (!view) {
          // Could not reuse a view ...

          // Creating a new annotation view
          view = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotationIdentifier"] autorelease];

          // This will rescale the annotation view to fit the image
          view.image = [UIImage imageNamed:@"someName"];
        }
      }
     return view;
}

我希望能回答你的问题