Get right zoom area for CLPlacemark

拥有回忆 提交于 2019-12-12 11:37:55

问题


I'm using MKLocalSearchto search for certain places like cities or streets in cities to shown them on an MKMapView

I show the placemark like this

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)

This works good when the place marks are cities as it shows a larger area at a reasonable zoom level. But when I want to show a specific street (which is the CLPlacemarks Location) in the city it is to far away.

Now I'm looking for a way to calculate the right span according to the "detail" of your CLPlacemark (Note that you don't know the type of the CLPlacemark upfront)

Is there a way to do this?


回答1:


Let me explain it fully.

First of all, you need to retrieve proper CLPlacemark objects.

If you would like to search for CLPlacemarks at some specific CLLocationCoordinate2D, then use this approach:

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;
 }];

Now that you got some proper CLPlacemark, you can use its .region property. Please note that documentation says that .region is CLRegion, but actually it is CLCircularRegion.

CLCircularRegion *theRegion = (id)thePlacemark.region;

However, MKMapView doesn't work with CLCircularRegion, while it works with MKMapRect. You can use the solution below:

How to convert CLCircularRegion to MKMapRect

MKMapRect theMapRect = [self rectForCLRegion:theRegion];

Now that we got our MKMapRect, we can pass it to our MKMapView like so:

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

Or, if you would like to adjust the screen offsets a bit further, you can use:

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

Conclusion:

Code seems to work fine and adjusts the span automatically, using information provided via CLCircularRegion .radius property.

The picture below shows the result if you pass (37.382640, -122.151780)

To compare, this is the picture if you pass (37.382640, -12.151780)



来源:https://stackoverflow.com/questions/35495900/get-right-zoom-area-for-clplacemark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!