在for循环中的mapbox中添加自定义标记

时间:2016-04-04 19:39:31

标签: swift for-loop mapbox mapbox-gl

我有点卡在这里......

我正在尝试为地图框视图中的每个标记添加不同的图像。为了填充地图,我使用了一个查看数组的for循环:

    for arrayInterest in dicoInterest {

        let point = MGLPointAnnotation()
        var latitudePoint : Double
        var longitudePoint : Double
        var typePoint : String
        latitudePoint = (arrayInterest["latitude"] as! Double)
        longitudePoint = (arrayInterest["longitude"] as! Double)
        typePoint = (arrayInterest["type"] as! String)
        point.coordinate = CLLocationCoordinate2D(latitude: latitudePoint, longitude: longitudePoint)

        mapView.addAnnotation(point)

        print("latitude : \(latitudePoint)")
        print("longitude : \(longitudePoint)")
        print("point : \(point)")
        print("type : \(typePoint)")


    }

到目前为止一切顺利。问题是,添加我发现在线查找的特定图像的唯一方法是:

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

    var annotationImage = mapView.dequeueReusableAnnotationImageWithIdentifier(typePoint)
    var image = UIImage(named: typePoint)
    image = image?.imageWithAlignmentRectInsets(UIEdgeInsetsMake(0, 0, image!.size.height/2, image!.size.width/2))
    annotationImage = MGLAnnotationImage(image: image!, reuseIdentifier:"\(point)")
    return annotationImage
}

我添加将它放在循环之外,因此,它对每个标记都不起作用。

还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

你仍然可以添加不同的图像。每次添加标记时都会调用此函数,因此可以添加不同的图像。

import UIKit
import Mapbox 

class yourClassController: UIViewController{

//define an image var in your class
var markerImage = UIImage(name: "defaultMarker.png") 


        override func viewDidLoad() {      
        super.viewDidLoad()       

            //Set new image in yout loop
            for arrayInterest in dicoInterest {

                    //new marker Image
                    markerImage = UIImage(name:newImageName)
            }
        }

    }


// MARK: - MKMapViewDelegate// Use Extension
extension yourClassController: MGLMapViewDelegate {

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

        let annotationImage = MGLAnnotationImage(image: markerImage, reuseIdentifier: "NewIdentiferName")

        return annotationImage

         }
    }

为图像设置一个新的reuseIdentifier非常重要,否则它将始终采用相同的图像。

代码未经过测试,但希望原则很明确