ios - 获取 CLPlacemark 的正确缩放区域

标签 ios swift cocoa-touch mapkit

我正在使用 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)

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

现在我正在寻找一种方法来根据您的 CLPlacemark 的“详细信息”计算正确的跨度(请注意,您不知道 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)的结果

enter image description here

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

enter image description here

关于ios - 获取 CLPlacemark 的正确缩放区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35495900/

相关文章:

ios - Game Center Sandbox 中缺少邀请

ios - 大于 60 秒时,Alamofire 超时不起作用

swift - Swift 通用约束中的元组类型

ios - 使用 firebase 3.0 + swift 检查用户是否存在

快速委派

ios - 当 UIAlertView 在屏幕上时,无法在 UIViewController 堆栈中隐藏键盘

objective-c - Mac 到 iPhone 应用程序通过 WiFi 进行通信

ios - iOS 中的 DropboxSDK 和 Dropbox 框架

ios - iOS 上的 Xamarin Forms 如何设置页面的屏幕方向?

ios - 如何使用移动标签正确创建动画并在其进行时禁用任何 UI 交互