Code Farmer Code Farmer - 4 months ago 38
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();
UIGraphicsEndImageContext();
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

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) {
        if(snapshot){
            UIImage *mapImage = snapshot.image;
            // do what you need with the image
            return;
        }

        NSLog(@"Error rendering snapshot for map at: (%f, %f)", options.region.center.latitude, options.region.center.longitude);
        NSLog(@"%@", error);
    }];
}

There is a pretty good article on NSHipster about MKMapSnapshotter.