0

I'm a little bit stuck here…

I'm trying to add a different image for each marker in my mapbox view. To populate the map I used a for loop that look into an array :

    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)")


    }

So far so good. The problem is, the only way to add a specific image I found looking online was this :

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
}

I add to put that outside the loop, and therefore, it doesnt work for each marker.

Is there another way to do that ?

iH8
  • 27,722
  • 4
  • 67
  • 76

1 Answers1

0

you still can add different images. this function will be called each time you add an marker, so can add a different image.

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

         }
    }

It's important to set always a new reuseIdentifier for the image, otherwise it will take always the same image.

Code is not tested, but hope the principle is clear

Peter Pohlmann
  • 1,478
  • 15
  • 30