无法将MapKit用户坐标转换为屏幕坐标

时间:2011-12-11 12:20:48

标签: iphone ios ios5 ios-simulator mapkit

好的,这实际上是一个帖子中的三个不同的问题:

1)我正在使用:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [mapView setFrame :CGRectMake(-100,-100,520,520)];
    [mapView setAutoresizesSubviews:true];
    mapView.showsUserLocation = YES;

    locManager = [[CLLocationManager alloc] init];
    locManager.delegate = self;
    [locManager startUpdatingLocation];
    [locManager startUpdatingHeading];

    [bt_toolbar setEnabled:YES];
}


- (IBAction) CreatePicture
{
     CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude);

     CGPoint annPoint = [self.mapView convertCoordinate:coord toPointToView:self.mapView];    
     mapPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
     mapPic.frame = CGRectMake(annPoint.x, annPoint.y, 32, 32);
     [self.view addSubview:macPic];
}

使用GCRectMake在用户的坐标上放置图像,但遗憾的是图像没有放在正确的位置:

Coordinate conversion gone wrong

如果我移动地图,图片将始终放置与用户位置完全相同的偏移量。我错过了什么?它不应该直接放在用户上方吗?我猜测偏移量(-100,-100)我首先给出了mapView是导致这种情况的原因(我在下方有一个工具栏,因此偏移)。

2)我的iOS 5模拟器表现得很疯狂,因为某种原因将我的位置放在凤凰城的格伦代尔(不应该是在Cupertino吗?),因为我正在向东移动;我的iPhone 4一切正常(除了不正确的图片放置)。有什么想法吗?

3)我一直在考虑使用Annotations,但我听说它们是静态的(我真的需要它们是动态的)。这是真的吗?

谢谢!

3 个答案:

答案 0 :(得分:6)

添加子视图时,其帧原点相对于其超级视图的原点。在这种情况下,您从地图视图派生了一个原点,然后将该图像添加到视图控制器的视图中。您需要将图像的原点转换为self.view的坐标系,如下所示:

CGPoint imageOrigin = [self.view convertPoint:annPoint fromView:self.mapView];
mapPic.frame.origin = imageOrigin;
[self.view addSubview:macPic];

注意:这是未经测试的代码,但主要是你需要在mapView的坐标空间(你从[self.mapView convertCoordinate:coord toPointToView:self.mapView]获得)到self.view的坐标之间进行转换空间。这个例子有点人为,因为更简单的方法是首先使用self.view的坐标空间:

CGPoint annPoint = [self.mapView convertCoordinate:coord toPointToView:self.view];    

答案 1 :(得分:2)

我认为您最好使用自己的图像使用自定义MKPinAnnotationView。 根据这个答案。 Add image behind MKPinAnnotationView

答案 2 :(得分:2)

MKMapView提供了以下用于在视图空间和地理坐标之间进行转换的方法:

– convertCoordinate:toPointToView:
– convertPoint:toCoordinateFromView:
– convertRegion:toRectToView:
– convertRect:toRegionFromView:

这些适用于将触摸转换为地图坐标等任务。对于您描述的任务,我认为地图叠加比尝试使用子视图在地图上绘制更合适。叠加层是一种注释,允许您绘制任何您喜欢的内容,但让地图负责确定叠加层何时可见并且根本需要绘制。

  

3)我一直在考虑使用Annotations,但我听说过   它们是静态的(我真的需要它们动态)。这是真的吗?

这里的“静态”与“动态”是什么意思?您是否想要更改叠加视图中的内容?或者您想要更改叠加层本身的位置?我认为应该可以根据需要随时更新叠加视图。我不确定你是否可以通过调整它的boundingMapRect属性来移动叠加层,但我希望它可以工作。如果没有,您可以随时删除叠加层并重新添加。

尝试创建自己的地图叠加系统而不是使用MapKit提供的工具应该是您的选项列表中的最后一件事。当你可以使用框架而不是使用框架时,生活总是更容易,并且你的代码将来不太可能破坏。