获取CLPlacemark

时间:2016-02-19 01:48:50

标签: 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的类型)

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:4)

让我完整解释一下。

首先,您需要检索正确的CLPlacemark个对象。

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

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