我正在寻找更改用户位置注释的外观。我知道现在可以使用MGLUserLocationAnnotationView
,但是,我不确定如何实现它。任何人都可以提供一个如何做到这一点的简单例子吗?
由于
答案 0 :(得分:10)
你是对的。 MapBox API MGLUserLocationAnnotationView描述非常简短。自MapBox iOS SDK 3.4.0起,用户位置视图自定义可用。 See also the feature comments on the MapBox GitHub
重要的是要注意:MGLUserLocationAnnotationView是MGLAnnotationView的子类。这意味着MGLUserLocationAnnotationView就像普通的注释视图一样。
以下是如何自定义用户位置视图的示例。创建一个新类(例如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或其他任何东西(例如Service类)中,使用至少两个函数-mapViewDidFinishLoadingMap实现MGLMapViewDelegate: 和-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