【问题标题】:iOS MapKit Annotation, not showing correct locationiOS MapKit Annotation,未显示正确的位置
【发布时间】:2026-01-20 02:30:01
【问题描述】:

我为我的 mapkit 注释使用自定义图像。但似乎我在使用自定义图像时遇到的主要问题是,当缩小时,注释不在地图上的正确点,只有在我一直放大之前,它才会显示注释点在正确的位置。似乎当我使用常规图钉 MKPinAnnotationView 时,它可以正常工作,因为图钉在正确的位置放大或缩小,提前感谢任何可以提供帮助的人。

我使用的代码如下:

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

NSLog(@"welcome into the map view annotation");

if ([annotation isKindOfClass:[MKUserLocation class]])

return nil;

MKAnnotationView *pprMapNote = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"pprMapNote"];


pprMapNote.image = [UIImage imageNamed:[NSString stringWithFormat:@"GPS_note.png"]];

pprMapNote.canShowCallout = YES;
pprMapNote.centerOffset = CGPointMake(-21,-60);
pprMapNote.calloutOffset = CGPointMake(0, 0);
//[pprMapNote addSubview:pprMapNoteImg];

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(showDetail)
      forControlEvents:UIControlEventTouchUpInside];
pprMapNote.rightCalloutAccessoryView = rightButton;

//remember to write in conditional for the different icons that should be loaded based on location

UIImageView *pprNoteLocIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loc_icon_casino.png"]];
pprMapNote.leftCalloutAccessoryView = pprNoteLocIcon;
[pprNoteLocIcon release];

return pprMapNote;

}

【问题讨论】:

    标签: ios mapkit mkannotationview


    【解决方案1】:

    您正在设置注释视图的centerOffset

    请注意,此偏移随缩放级别缩放。缩小得越远,图像就会离坐标越远。

    在默认的MKPinAnnotationView 中,centerOffset 保留为默认值 0,0,并且引脚图像的设计使得引脚的底点位于坐标上。因此,当您进一步缩小时,图钉图像似乎相对于其下方的地图增长,但图钉的底部仍指向坐标。

    您需要根据您的图像调整centerOffset,或者修改您的图像,这样您就不需要设置centerOffset。或者只是尝试注释掉centerOffset的设置--也许你不需要它。


    其他一些不相关的项目:

    • pprMapNote alloc+init 存在内存泄漏(添加自动释放)
    • 您应该使用dequeueReusableAnnotationViewWithIdentifier 以允许注释视图重用。
    • 与其使用addTarget调用你自己的方法来调用callout按钮按下,不如使用地图视图自己的委托方法calloutAccessoryControlTapped

    以上三点的例子见this answer

    【讨论】:

      【解决方案2】:

      图钉在单独的视图中绘制,因此不会根据您的视图状态进行缩放。

      您必须手动设置自定义 Pin 图的大小。这可以使用 centerOffset 轻松完成。在大多数情况下,将框架的高度设置为图像大小的一半就足够了。图像完全填充在框架中,因此您可以轻松使用此框架大小(高度)。

        aView.image = [UIImage imageNamed ... ];
        aView.centerOffset = CGPointMake(0,-aView.frame.size.height*0.5);
      

      【讨论】: