获取 CLPlacemark 的正确缩放区域

Get right zoom area for CLPlacemark

我正在使用 MKLocalSearch 搜索某些地方,例如城市或城市中的街道,以便在 MKMapView

上显示它们

我这样显示地标

let loc = placemark.location! //CLLocation of CLPlacemark
var mapRegion = MKCoordinateRegion()
mapRegion.center.longitude = loc.coordinate.longitude
mapRegion.center.latitude = loc.coordinate.latitude
mapRegion.span.latitudeDelta = 0.03 // I choose 0.03 by trying
mapRegion.span.longitudeDelta = 0.03
mapView.setRegion(mapRegion, animated: true)

当地点标记是城市时,这很有效,因为它在合理的缩放级别下显示了更大的区域。但是当我想显示城市中的特定街道(即 CLPlacemarks 位置)时,它太远了。

现在我正在寻找一种方法来根据您的 CLPlacemark 的 "detail" 计算正确的跨度(请注意,您不知道 CLPlacemark 的类型预先)

有办法吗?

让我详细解释一下。

首先,您需要检索适当的 CLPlacemark 对象。

如果您想在某些特定的 CLLocationCoordinate2D 处搜索 CLPlacemark,请使用此方法:

CLLocationCoordinate2D theCoordinate = CLLocationCoordinate2DMake(37.382640, -122.151780);
CLGeocoder *theGeocoder = [CLGeocoder new];
[theGeocoder reverseGeocodeLocation:[[CLLocation alloc] initWithLatitude:theCoordinate.latitude longitude:theCoordinate.longitude]
                  completionHandler:^(NSArray *placemarks, NSError *error)
 {
      CLPlacemark *thePlacemark = placemarks.firstObject;
 }];

现在您已经有了一些合适的 CLPlacemark,您可以使用它的 .region 属性。请注意文档说 .regionCLRegion,但实际上它是 CLCircularRegion.

CLCircularRegion *theRegion = (id)thePlacemark.region;

但是,MKMapView 不适用于 CLCircularRegion,而它适用于 MKMapRect。您可以使用以下解决方案:

How to convert CLCircularRegion to MKMapRect

MKMapRect theMapRect = [self rectForCLRegion:theRegion];

现在我们得到了 MKMapRect,我们可以像这样将它传递给我们的 MKMapView

[theMapView setVisibleMapRect:[theMapView mapRectThatFits:theMapRect]
                     animated:YES];

或者,如果您想进一步调整屏幕偏移量,您可以使用:

[theMapView setVisibleMapRect:[theMapView mapRectThatFits:theMapRect]
                  edgePadding:UIEdgeInsetsMake(50, 50, 50, 50)
                     animated:YES];

结论:

代码似乎工作正常并自动调整跨度,使用通过 CLCircularRegion .radius 属性.

提供的信息

下图是通过(37.382640, -122.151780)的结果

对比一下,如果你通过了就是这个图(37.382640, -12.151780)