Code Farmer Code Farmer - 1 year ago 61
Objective-C Question

What is the best way to generate a snapshot given latitude and longitude, skipping MKMapView is really encouraged

I am implementing location sharing in my APP, this forces me to generate multiple snapshots according to their latitude and longitude accordingly. So simply using directly:

- (UIImage*) renderToImage:(MKMapView*) view
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
return image;

will lead me a un-finished snapshot.

I tried to use following code:

- (void)mapViewDidFinishRenderingMap:(MKMapView *)mapView fullyRendered:(BOOL)fullyRendered
// Image creation code here

However, it's hard for me to get back to the right cell setting a snapshot even I know it is fully loaded.

So is there some API to generate the snapshot directly from the latitude and longitude without these complex procedure? Thank you guys in advance!

Answer Source

You can use MKMapSnapshotter for this purpose. It allows you to create an image of a map at a specific location, centered on a region.

- (void)renderSnapshotForLocation:(CLLocationCoordinate2D)location {
    MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
    options.size = CGSizeMake(200, 200); // whatever size you need
    options.scale = [[UIScreen mainScreen] scale];
    // size of region in degrees of latitude and longitude
    MKCoordinateSpan span = MKCoordinateSpanMake(0.25, 0.25);
    options.region = MKCoordinateRegionMake(location, span);

    MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
    [snapshotter startWithCompletionHandler:^(MKMapSnapshot * _Nullable snapshot, NSError * _Nullable error) {
            UIImage *mapImage = snapshot.image;
            // do what you need with the image

        NSLog(@"Error rendering snapshot for map at: (%f, %f)",,;
        NSLog(@"%@", error);

There is a pretty good article on NSHipster about MKMapSnapshotter.