首页 > 解决方案 > 使 Mapbox 注释根据变量具有不同的图像?

问题描述

因此,我在更新地图视图函数中的 for 循环中创建注释,如下所示:

for item in array {
    let latitude = item.latitude
    let longitude = item.longitude
    let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    let annotation = //make an annotation that uses a different image in Assets depending on a variable called "imageID"
    mapView.addAnnotation(annotation)
}

我尝试使用reuseIdentifiers,但甚至没有接近解决这个问题。我还尝试使用 imageFor 函数并制作一个自定义注释类(以检测传入的图像是什么并相应地更改视图)但它不起作用:

class CustomAnnotation: NSObject, MGLAnnotation {

    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?

    var image: UIImage?

    init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
}

func mapView( _ mapView: MGLMapView, imageFor annotation: MGLAnnotation ) -> MGLAnnotationImage? {
        
    let annotationImage: MGLAnnotationImage
    let annotationImageToilet = mapView.dequeueReusableAnnotationImage(withIdentifier: "custom1")
    let annotationImageDefault = mapView.dequeueReusableAnnotationImage(withIdentifier: "defaultImage")
            
    switch annotation.image { //tried to sort according to the image value of the custom class
        case "custom1":
            var featureAnnotation = FeatureAnnotation(coordinate: annotation.coordinate, title: "Title", subtitle: "subtitle")
            featureAnnotation.image = UIImage(named: "custom1")!
            annotationImage = annotationImageToilet ?? featureAnnotation //couldn't get this line working properly
        default:
            var featureAnnotation = FeatureAnnotation(coordinate: annotation.coordinate, title: "Title", subtitle: "subtitle")
            featureAnnotation.image = UIImage(named: "defaultImage")!
            annotationImage = annotationImageDefault ?? featureAnnotation //couldn't get this line working properly
        }
            
        return annotationImage
 }

本质上,我只是希望自定义注释的图像根据 feature.imageID 是什么而改变,非常感谢任何帮助!

标签: swiftannotationsuikituiimagemapbox

解决方案


推荐阅读