MapBox iOS不同的标记图像?

der*_*ida 4 ios mapbox

有没有办法添加ID或其他东西,我能够设置自定义标记图像?

我有多个带数字的标记,我需要每个新标记都有另一个图像.

例如:

marker1 - marker_1_image

marker2 - marker_2_image

Atm我只能为所有标记设置1个图像(全局):

func mapView(mapView: MGLMapView, imageForAnnotation annotation: MGLAnnotation) -> MGLAnnotationImage? {

    var annotationImage = mapView.dequeueReusableAnnotationImageWithIdentifier("place")

    if annotationImage == nil {
        var image = UIImage(named: "marker_1")!
        image = image.imageWithAlignmentRectInsets(UIEdgeInsetsMake(0, 0, image.size.height/2, 0))
        annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: "place")
    }

    return annotationImage
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?或者我可以继承MGLAnnotation并将其用于所有委托方法吗?

fri*_*nny 7

您可以继承并添加userInfo属性(如本答案中所述),或者您可以使用现有的标题/副标题属性:

func mapView(mapView: MGLMapView, imageForAnnotation annotation: MGLAnnotation) -> MGLAnnotationImage? {
    // get the custom reuse identifier for this annotation
    let reuseIdentifier = reuseIdentifierForAnnotation(annotation)
    // try to reuse an existing annotation image, if it exists
    var annotationImage = mapView.dequeueReusableAnnotationImageWithIdentifier(reuseIdentifier)

    // if the annotation image hasn‘t been used yet, initialize it here with the reuse identifier
    if annotationImage == nil {
        // lookup the image for this annotation
        let image = imageForAnnotation(annotation)
        annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
    }

    return annotationImage
}

// create a reuse identifier string by concatenating the annotation coordinate, title, subtitle
func reuseIdentifierForAnnotation(annotation: MGLAnnotation) -> String {
    var reuseIdentifier = "\(annotation.coordinate.latitude),\(annotation.coordinate.longitude)"
    if let title = annotation.title where title != nil {
        reuseIdentifier += title!
    }
    if let subtitle = annotation.subtitle where subtitle != nil {
        reuseIdentifier += subtitle!
    }
    return reuseIdentifier
}

// lookup the image to load by switching on the annotation's title string
func imageForAnnotation(annotation: MGLAnnotation) -> UIImage {
    var imageName = ""
    if let title = annotation.title where title != nil {
        switch title! {
        case "blah":
            imageName = "blahImage"
        default:
            imageName = "defaultImage"
        }
    }
    // ... etc.
    return UIImage(named: imageName)!
}
Run Code Online (Sandbox Code Playgroud)

您将希望使图像加载更加健壮并自定义重用标识符字符串的特殊性,但这通常应该起作用.