I am trying to learn MapKit and am now trying to add an image (not a polygon, circle, rectangle, etc.) as an overlay to the map view. I can't seem to find any sample code to help explain how to do this.
So far my code in ViewController.swift is:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView!
var locationManager: CLLocationManager!
var mapOverlay: MKOverlay!
override func viewDidLoad() {
super.viewDidLoad()
//Setup our Location Manager
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
//Setup our Map View
mapView.delegate = self
mapView.mapType = MKMapType.Satellite
mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I know I need to use:
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer
and the drawMapRect function but I don't know what to put in them. Also, it would be useful if all the code is in ViewController.swift
I only need one overlay so I don't need a class. I need it to be an image overlay (so it can resize), not an annotation. I also tried to follow the tutorial at http://www.raywenderlich.com/30001/overlay-images-and-overlay-views-with-mapkit-tutorial but there is not a section with all the code and I find it hard to follow along. Can you people please help me how to create image MKOverlays and add them to MKMapKit?
Thanks in advance...
Swift 3
The following works for me in Swift 3.
Then as usual, in your MapView delegate:
And whenever you need to add an image to your map:
Note, I always ensure that the rect has the same aspect ratio as the image. Otherwise, I suspect image distortion will result.
Apple do have some sample code for displaying overlays but it is in Objective-C so you will have to transpose it to Swift.
Essentially there are two things you need to do (and both can be done in your view controller). The first is to create the overlay and add it to the map i.e. somewhere in
viewDidLoad()
:Note that
points
has to be avar
as you are dereferencing it for the tile creation.The second step is then to define the renderer:
Using Swift 2.1/Xcode 7.2, this renders a tile for me in a location in Australia. So you may want to tweak the lat/lons to give you an overlay in your map - map defaults are to your continent.