0

我有点卡在这里…

我正在尝试为我的 mapbox 视图中的每个标记添加不同的图像。为了填充地图,我使用了一个查看数组的 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
}

我添加将其放在循环之外,因此,它不适用于每个标记。

还有另一种方法吗?

4

1 回答 1

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

         }
    }

始终为图像设置一个新的重用标识符很重要,否则它将始终采用相同的图像。

代码没有测试,但希望原理清楚

于 2016-04-18T12:36:15.350 回答