user7370780
user7370780

Reputation:

how to change a pin color in swift 3 using MapKit

Below is my code that lists 1 annotation pin. Right now its red. How can I make it blue? Do I need to put in a extension file? The code also includes the current users location. Also I could I make the annotation a button?

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet var map: MKMapView!

let manager = CLLocationManager()


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    let span: MKCoordinateSpan = MKCoordinateSpanMake(1.0, 1.0)
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)

    map.setRegion(region, animated: true)

    print(location.altitude)
    print(location.speed)

    self.map.showsUserLocation = true

}




override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(37.5656, -122.443)
    let annoation = MKPointAnnotation()

           annoation.coordinate = location
    annoation.title = "MYSHOP"
    annoation.subtitle = "Come Visit"
    map.addAnnotation(annoation)

}


}

Upvotes: 0

Views: 5071

Answers (2)

JohnSF
JohnSF

Reputation: 4300

I see this question has been around a while, but I remember that I had trouble creating custom pin colors so maybe someone can use this in the future. MKPinAnnotationColor has been deprecated so you need to create your own colors if you want pins that are not red, green or purple. You do that by creating an extension to MKPinAnnotationView and defining a new color. For example, if you want a blue pin:

 extension MKPinAnnotationView {
     class func bluePinColor() -> UIColor {
         return UIColor.blue
     }
 }

then assign the color to your annotation:

 MKPinAnnotationView.bluePinColor()

Upvotes: 3

Duncan C
Duncan C

Reputation: 131418

You need to set up some object to serve as the map's delegate, and then implement viewForAnnotation. You can use MKPinAnnotationView to return standard pin annotations, or create a custom view and return that if you need something special.

There should be plenty of tutorials around showing how to do this since it's dirt-simple map customization.

A quick Google search revealed this SO post:

How to change MKAnnotation Color using Swift?

Note that the answer to that question uses pinColor, which was deprecated in iOS 10. You'll need to use MKPinAnnotationColor instead.

Upvotes: 1

Related Questions