ios - MapBox iOS 不同的标记图像?

标签 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
}

有什么想法吗?或者我可以子类化 MGLAnnotation 并将其用于所有委托(delegate)方法吗?

最佳答案

您可以子类化并添加一个 userInfo 属性 ( as in this answer ),或者您可以使用现有的标题/副标题属性:

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)!
}

您会希望使图像加载更稳健并自定义重用标识符字符串的特异性,但这通常应该可行。

关于ios - MapBox iOS 不同的标记图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36115342/

相关文章:

ios - "Export Compliance Review"下的应用程序 - 我应该重新提交吗?

ios - 为什么我在 IOS 上得到 Mapboxgl api 的空白页?

mapbox - 向 Mapbox map 添加可折叠侧边栏

ios - 我应该使用数组还是数据库——在哪里初始化它?

ios - 无法将 JSON 响应添加到 Realm

ios - 当我的游戏在 sprite kit 中暂停时如何返回主场景

ios - 通过移动多个 View 来更改旋转布局

javascript - Mapbox 自定义标记

android - Mapbox 我的位置漂移 android

ios - 如何使用 .p8 JWT key 测试推送? (APNs 授权 key )