Swift MapKit自定义当前位置标记

Vic*_*tor 7 location mapkit ios swift

这就是我project目前的样子.我的问题是,如何将蓝色球(当前位置)更改为自定义图像图标

chu*_*n20 15

我相信你知道用户习惯将蓝点视为当前用户的位置.除非你有充分的理由,否则你不应该改变它.

以下是如何更改它:

设置mapView的委托,然后覆盖以下函数......如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

而是显示一个图像:只需用以下代码替换if语句中的代码:

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

我认为这段代码示例应该为您提供足够的信息来帮助您弄清楚该怎么做.(注意mapView是在故事板中创建的......)

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
    }
}
Run Code Online (Sandbox Code Playgroud)