我使用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
的类型)
有办法做到这一点吗?
答案 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
属性。请注意,文档说.region
为CLRegion
,但实际上是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)