Swift 3 – Mapbox – 自定义用户位置注释

我正在寻找改变用户位置注释的外观。 我明白这是现在可能使用MGLUserLocationAnnotationView ,但是,我不确定如何实现这一点。 任何人都可以提供一个简单的例子,这是如何做到的?

谢谢

你是对的。 MapBox API的MGLUserLocationAnnotationView描述非常简短。 用户位置视图自定义从MapBox iOS SDK 3.4.0开始可用。 另请参阅MapBox GitHub上的function注释

需要注意的是:MGLUserLocationAnnotationView是MGLAnnotationView的一个子类。 这意味着MGLUserLocationAnnotationView就像普通的注释视图一样。

以下是如何自定义用户位置视图的示例。 创build一个新类(例如CustomUserLocationAnnotationView)并重写layoutSubviews()以添加自定义代码。 在这个例子中,我使用UIImage UserLocationIcon.png来显示用户在地图上的位置。

 import Foundation import UIKit import Mapbox final class CustomUserLocationAnnotationView: MGLUserLocationAnnotationView { override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // Force the annotation view to maintain a constant size when the map is tilted. scalesWithViewingDistance = false layer.contentsScale = UIScreen.main.scale layer.contentsGravity = kCAGravityCenter // Use your image here layer.contents = UIImage(named: "UserLocationIcon")?.cgImage } } 

在您的UIViewController或其他任何(如服务类)实现MGLMapViewDelegate至less有两个函数-mapViewDidFinishLoadingMap:和-mapView:viewForAnnotation :. 在线查看我的评论:

 extension ViewController: MGLMapViewDelegate { // Wait until the map is loaded before proceed with other actions on map func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) { // Show the user location here mapView.showsUserLocation = true } func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? { // Customise the user location annotation view if annotation is MGLUserLocation { var userLocationAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "CustomUserLocationAnnotationViewIdentifier") as? CustomUserLocationAnnotationView if userLocationAnnotationView == nil { userLocationAnnotationView = CustomUserLocationAnnotationView(reuseIdentifier: "CustomUserLocationAnnotationViewIdentifier") } // Optional: You can save the annotation object for later use in your app self.userLocationAnnotation = annotation return userLocationAnnotationView } // Customise your annotation view here... return customAnnotationView } } 

MapView -mapView:viewForAnnotation:delegate函数被调用,包括用户注解视图在内的每个注解视图实例。

可选:为了得到你的CustomUserLocationAnnotationView实例,你可以在你的代码中的任何地方使用这个函数:

  // The userLocationAnnotation was previously saved in your ViewController in the -mapView:viewForAnnotation: delegate function let view = mapView.view(for: self.userLocationAnnotation) as? CustomUserLocationAnnotationView