13
Sep

MKMapView too slow? Use preview – MKMapSnapshotter

Did you ever needed to just show a piece of map and added it disabling all touch events and end up with crazy slow unneccesary MKMapView? I’ve recently discovered

MKMapSnapshotter

which solves all the issues. We can use it since iOS7 so MKMapView can be easily replaced and snapshotter result (which is an image) can be cached – clean and quick!

import MapKit
import CoreLocation

let coords = CLLocationCoordinate2D(latitude: 52.235799, longitude: 20.995958)
let distanceInMeters: Double = 500
let size = CGSize(width: 200, height: 200)

let options = MKMapSnapshotOptions()
options.region = MKCoordinateRegionMakeWithDistance(coords, distanceInMeters, distanceInMeters)
options.size = size

let snapShotter = MKMapSnapshotter(options: options)
let bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
// this might be run in foregourd but we want to have responsive UI
// which helped a lot being a UITableViewCell which lagged a lot
snapShotter.startWithQueue(bgQueue) { [weak self] (snapShot, error) in
    guard error == nil else {
        return
    }

    if let snapShotImage = snapShot?.image, let coordinatePoint = snapShot?.pointForCoordinate(coords), let pinImage = UIImage(named: "pinImage") {
        UIGraphicsBeginImageContextWithOptions(snapShotImage.size, true, snapShotImage.scale)
        snapShotImage.drawAtPoint(CGPointZero)
        // need to fix the point position to match the anchor point of pin which is in middle bottom of the frame
        let fixedPinPoint = CGPointMake(coordinatePoint.x - pinImage.size.width / 2, coordinatePoint.y - pinImage.size.height)
        pinImage.drawAtPoint(fixedPinPoint)
        let mapImage = UIGraphicsGetImageFromCurrentImageContext()
        dispatch_async(dispatch_get_main_queue(), {
            self?.mapPreviewImageView.image = mapImage
            // stop and hide spinner which was in image center place
            self?.activityIndicator.stopAnimating()
        })
        UIGraphicsEndImageContext()
    }
}

I’ve put some comments to explain some non standard stuff but overall it should be simple enough. If you have any questions just ask!

Comments ( 0 )

    Leave A Comment

    Your email address will not be published. Required fields are marked *