获取CLPlacemark的正确缩放区域

4
我正在使用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
你有检查过这个问题吗?https://dev59.com/HmDVa4cB1Zd3GeqPaB1m - ljk321
对我来说,你想做什么并不清楚。你想知道为什么城市特定街道的标记太远吗?还是想根据标记的“详细信息”计算跨度? - Ramis
@Ramis 我想计算地标的详细信息。 - arnoapp
你为我提供的代码在地图的中心显示为span。我无法复制或理解问题出在哪里。 - Ramis
我想要正确的跨度来显示地标的详细信息。如果地标是城市中的某条街道,那么我希望能够缩放更近,就像它只是城市一样。 - arnoapp
1个回答

6
让我详细解释一下。
首先,您需要检索正确的 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。您可以使用以下解决方案:

如何将CLCircularRegion转换为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


这是完美的答案 - 你完全配得上奖励!感谢你花时间 - 无论我查找或搜索什么,都无法弄清楚。 - arnoapp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接