ios - Swift MapKit 自定义当前位置标记

标签 ios swift location mapkit

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

最佳答案

我相信您知道用户习惯于将那个蓝点视为当前用户的位置。除非有充分的理由,否则不应更改它。

修改方法如下:

为 mapView 设置委托(delegate),然后重写以下函数...像这样:

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
}

并改为显示图像: 只需将 if 语句中的代码替换为以下代码:

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

我认为此代码示例应该为您提供足够的信息来帮助您确定要做什么。 (注意 mapView 是在 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
    }
}

关于ios - Swift MapKit 自定义当前位置标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046633/

相关文章:

c# - 在 C# 中查找大图像中的子图像

ios - 在 Carthage 依赖项上禁用位码

ios - 以编程方式更改 iOS 中的启动画面?

iphone - 计算足够的文本以适应现有的 UILabel

ios - 将瓷砖变体添加到 SKTileGroup

php - 邮政编码/位置搜索 - PHP

ios - 旧 View 的线程仍在运行

swift - 在 View Controller 中获取 applicationDidFinishLaunching 调用。解析尚未初始化

ios - UIKeyboardDidShow 触发太频繁?

java - 安全异常 : Permission 'android.permission.LOCATION_HARDWARE' not granted