我创建了一个方法,如下所示将CGRect转换为MapRect
- (MKMapRect)mapRectForRect:(CGRect)rect
{
CLLocationCoordinate2D topleft = [mapView convertPoint:CGPointMake(rect.origin.x, rect.origin.y) toCoordinateFromView:canvasView];
CLLocationCoordinate2D bottomeright = [mapView convertPoint:CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect)) toCoordinateFromView:canvasView];
MKMapPoint topleftpoint = MKMapPointForCoordinate(topleft);
MKMapPoint bottomrightpoint = MKMapPointForCoordinate(bottomeright);
return MKMapRectMake(topleftpoint.x, topleftpoint.y, bottomrightpoint.x - topleftpoint.x, bottomrightpoint.y - topleftpoint.y);
}
我做了一个小测试。
UIImageView *imageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"heart.png"] imageByScalingProportionallyToSize:CGSizeMake(100, 100)]];
imageView.frame = CGRectMake(0, 0, 100, 100);
imageView.center = [mapView convertCoordinate:mapView.centerCoordinate toPointToView:canvasView];
[canvasView addSubview:imageView];
CGRect rect = imageView.frame;
for (int i = 0; i < 5; i ++)
{
NSLog(@"%f, %f, %f, %f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
maprect = [self mapRectForRect:rect];
NSLog(@"%f, %f, %f, %f", maprect.origin.x, maprect.origin.y, maprect.size.width, maprect.size.height);
region = MKCoordinateRegionForMapRect(maprect);
rect = [mapView convertRegion:region toRectToView:canvasView];
}
它在iOS 5:上运行得很好
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
但是,iOS 4.3上的结果有点奇怪。
110.00000、180.0000000、100.000000、100.000000
78118912.00000094811514.400625252428800.00000052428799.999997
110.000000174.265396100.000000101.746048
78118912.00000091803986.4060252428800.00000053344231.999997
110.000000166.962997100.000000104.330460
78118912.000000、87976370.406253、52428800.000000、54699207.999997
110.000000157.400009,100.000000108.272507
78118912.00000082962610.40625352428800.00000056765975.999997
110.000000144.2974701100.000000114.581375
78118912.0000007609310626452428800.00000060073639.999996
类似这样的东西(Swift代码)似乎工作得很好。在这种情况下,mapView
是GMSMapView!
类型,因此mapView.frame
是CGRect
类型。
let mkMapSize = MKMapSize(width: Double(self.mapView.frame.width), height: Double(self.mapView.frame.height))
let mkMapPoint = MKMapPoint(x: Double(self.mapView.frame.origin.x), y: Double(self.mapView.frame.origin.y))
let mkMapRect = MKMapRect(origin: mkMapPoint, size: mkMapSize)