Kar534
Kar534

Reputation: 127

Changing the image and color of a mapView annotation

How would I change this code so that I could implement a color and a unique image for the respected group? Right now when I call the functions, they all produce the same generic red annotation. I would like for the groups to have different images and colors as opposed to multiple groups sharing the same annotations. How would I change this?

Here is my code.

import UIKit
import MapKit

struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double

init(name: String, latitude: Double, longitude: Double) {
    self.name = name
    self.latitude = latitude
    self.longitude = longitude
}
}

class MapViewController: UIViewController {

@IBOutlet var mapView: MKMapView!

var placesFirst = [PlacesOnMap(name: "place 1", latitude: 28.551700, longitude: -81.374800),
    PlacesOnMap(name: "place 2", latitude: 28.553018, longitude: -81.374206),
    PlacesOnMap(name: "place 3", latitude: 28.553019, longitude: -81.367839)]
var placesSecond = [PlacesOnMap(name: "place 1", latitude: 28.556969, longitude: -81.364319),
var placesThird = [PlacesOnMap(name: "place 1", latitude: 28.54693, longitude: -81.393071)]
    PlacesOnMap(name: "place 2", latitude: 28.538523, longitude: -81.385399)]

override func viewDidLoad() {
    super.viewDidLoad()
    }

let markerView = MKMarkerAnnotationView()

func setupFirstPlacesAnnotations() {
    let places = placesFirst.map { placeOnMap -> MKPointAnnotation in
        let place = MKPointAnnotation()
        place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
        place.title = placeOnMap.name
        return place
    }
    mapView.addAnnotations(places)
}

func setupSecondPlacesAnnotations() {
    let places = placesSecond.map { placeOnMap -> MKPointAnnotation in
        let place = MKPointAnnotation()
        place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
        place.title = placeOnMap.name
        return place
    }
    mapView.addAnnotations(places)
}

func setupThirdPlacesAnnotations() {
    let places = placesThird.map { placeOnMap -> MKPointAnnotation in
        let place = MKPointAnnotation()
        place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
        place.title = placeOnMap.name
        return place
    }
    mapView.addAnnotations(places)
}

extension MapViewController: CLLocationManagerDelegate, MKMapViewDelegate {

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

}
}

Upvotes: 0

Views: 1146

Answers (1)

Val Moratalla
Val Moratalla

Reputation: 211

You can follow this tutorial and download the source code, you can see that it will tackle how to change the marker colors and images.

https://www.raywenderlich.com/7738344-mapkit-tutorial-getting-started

Upvotes: 1

Related Questions