Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift MapKit custom current location marker

This is what my project currently looks like. My questions is, how do I change the blue ball (current location) to a custom image or icon?

like image 511
Victor Avatar asked Aug 19 '16 19:08

Victor


1 Answers

I am sure you know that a user is used to seeing that blue-dot as the current user's location. You shouldn't change it unless you have a good reason.

Here is how to change it:

Set the delegate for the mapView, and then override the following function... something like this:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        let pin = mapView.view(for: annotation) as? MKPinAnnotationView ?? MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil)
        pin.pinTintColor = UIColor.purple
        return pin

    } else {
        // handle other annotations

    }
    return nil
}

and to have an image displayed instead: Just replace the code inside if statement with the following code:

let pin = mapView.view(for: annotation) as? MKPinAnnotationView ?? MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil)
pin.image = UIImage(named: "user_location_pin")
return pin

I think this code sample should give you enough information to help you figure out what to do. (Note that mapView is created in a storyboard...)

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var mapView: MKMapView!

    let loc = CLLocationManager()
    var angle = 0
    var timer: NSTimer!
    var userPinView: MKAnnotationView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        loc.requestWhenInUseAuthorization()

        timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(rotateMe), userInfo: nil, repeats: true)
    }

    func rotateMe() {
        angle = angle + 10
        userPinView?.transform = CGAffineTransformMakeRotation( CGFloat( (Double(angle) / 360.0) * M_PI ) )

    }

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation {
            let pin = mapView.viewForAnnotation(annotation) ?? MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
            pin.image = UIImage(named: "userPinImage")
            userPinView = pin
            return pin

        } else {
            // handle other annotations

        }
        return nil
    }
}
like image 102
chuthan20 Avatar answered Dec 21 '22 08:12

chuthan20