MapKit annotation button not showing up - ios

I'm trying to build an app for iOS 8 using Swift which uses a Parse.com database to display pins on a MapView. I've succeeded in loading all the pins on the map us PFGeoPoints, but I'm trying to add a disclosure button to each pin which will perform a segue to show extra info.
I've double checked my code but I'm missing something, does anyone notice problems?
import UIKit
import Foundation
import Parse
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var userLocationParse = PFGeoPoint(latitude: 47.49, longitude: 19.06)
#IBOutlet weak var nmapview: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: 47.49, longitude: 19.06)
let span = MKCoordinateSpanMake(0.03, 0.03)
let region = MKCoordinateRegion(center: location, span: span)
nmapview.setRegion(region, animated: true)
nmapview.showsPointsOfInterest = false
nmapview.showsUserLocation = true
displayMarkers()
}
func displayMarkers() -> Void {
//GET PIN DATA HERE
var query = PFQuery(className: "Places")
query.whereKey("PlaceLocation", nearGeoPoint: userLocationParse)
query.limit = 30
let foundPlaces = query.findObjects()
//GETTING PFGEOLOCATIONS AND PUTTING THEM ON MAP AS ANNOTATIONS
//Loading pin details
var annotationQuery = PFQuery(className: "Places")
annotationQuery.whereKey("PlaceLocation", nearGeoPoint: userLocationParse)
annotationQuery.findObjectsInBackgroundWithBlock {
(posts, error) -> Void in
if error == nil {
// The find succeeded.
//println("Successful query for annotations")
let myPosts = posts as! [PFObject]
for post in myPosts {
let pinAnnotation = PinAnnotation()
let point = post["PlaceLocation"] as! PFGeoPoint
let pointName = post["PlaceName"] as! String
let pointDetails = post["PlaceDetails"] as! String
let thePinsLocation = CLLocationCoordinate2DMake(point.latitude, point.longitude)
pinAnnotation.setCoordinate(thePinsLocation)
pinAnnotation.title = pointName
pinAnnotation.subtitle = pointDetails
self.nmapview.addAnnotation(pinAnnotation)
}
} else {
// Log details of the failure
// println("Error: \(error)")
}
}
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is PinAnnotation {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseID = "myPin"
var pinAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseID) as? MKPinAnnotationView
if pinAnnotationView == nil {
pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
pinAnnotationView!.pinColor = .Purple
pinAnnotationView!.canShowCallout = true
pinAnnotationView!.animatesDrop = true
pinAnnotationView!.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as! UIButton
} else {
pinAnnotationView!.annotation = annotation
}
return pinAnnotationView
}
return nil
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if control == view.rightCalloutAccessoryView{
performSegueWithIdentifier("infoViewController", sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Also I created a class for "PinAnnotation" for use with the pins. Not sure if redundant but some tutorials on the subject brought it up as necessary.
import UIKit
import MapKit
import UIKit
class PinAnnotation: NSObject, MKAnnotation {
private var coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 90.0, longitude: 0.0)
var coordinate: CLLocationCoordinate2D {
get {
return coord
}
}
var title: String = "North Pole"
var subtitle: String = "Santa's house"
func setCoordinate(newCoordinate: CLLocationCoordinate2D) {
self.coord = newCoordinate
}
}

On the basis of what you describe, it sounds like the delegate of the map view has not been set. You can set it in IB by going to the outlets inspector. You can set it programmatically with:
nmapview.delegate = self

Related

Open maps app with custom callout view and multiple annotations

I have made an project and followed a tutorial on the internet. It shows annotations and has a custom callout view.I have added a label with a button feature which is shown in my screenshot. I now would like some help to get the feature to start maps app from my project. I have made comments in the project which shows what i have done and what i need help with
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, UISearchBarDelegate {
#IBOutlet var mapView: MKMapView!
#IBOutlet var searchBarMap: UISearchBar!
var coordinates: [[Double]]!
var names:[String]!
var addresses:[String]!
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation
{
return nil
}
if annotation is MKPointAnnotation
{
return nil
}
var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin")
if annotationView == nil{
annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "Pin")
annotationView?.canShowCallout = false
}else{
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named: "parking-sign")
return annotationView
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
searchBarMap.delegate = self
coordinates = [[57.638486,18.299698],[57.636859,18.300468],[57.634807, 18.293389]]// Latitude,Longitude
names = ["Österport","Åhléns","Söderport/busstation"]
addresses = ["regler: p-skiva 2 timmar 9-18, oftast få platser lediga","stor med två våningar, övre plan oftast väl fylld och komplicerade parkeringsrutor","Nära om du vill till adelsgatan"]
self.mapView.delegate = self
for i in 0...2
{
let coordinate = coordinates[i]
let point = StarbucksAnnotation(coordinate: CLLocationCoordinate2D(latitude: coordinate[0] , longitude: coordinate[1] ))
point.name = names[i]
point.address = addresses[i]
self.mapView.addAnnotation(point)
}
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 57.630615, longitude: 18.303023), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
self.mapView.setRegion(region, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView)
{
// 1
if view.annotation is MKUserLocation
{
return
}
if view.annotation is MKPointAnnotation
{
return
}
let starbucksAnnotation = view.annotation as! StarbucksAnnotation
let views = Bundle.main.loadNibNamed("CustomCalloutView", owner: nil, options: nil)
let calloutView = views?[0] as! CustomCalloutView
calloutView.starbucksName.text = starbucksAnnotation.name
calloutView.starbucksAddress.text = starbucksAnnotation.address
// declaring label as a button
let button = UIButton(frame: calloutView.directions.frame)
button.addTarget(self, action: #selector(ViewController.openInMaps(sender:)), for: .touchUpInside)
calloutView.addSubview(button)
calloutView.center = CGPoint(x: view.bounds.size.width / 2, y: -calloutView.bounds.size.height*0.52)
view.addSubview(calloutView)
mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
if view.isKind(of: AnnotationView.self)
{
for subview in view.subviews
{
subview.removeFromSuperview()
}
}
}
//I want to know what i should fill this function with to open maps and give me directions
func openInMaps(sender: UIButton)
{
//This is what i tested so far
let coordinates1 = coordinates
let point = StarbucksAnnotation(coordinate: CLLocationCoordinate2D(latitude: coordinates1[0] , longitude: coordinates1[1] ))
let regionDistance:CLLocationDistance = 10000
let regionSpan = MKCoordinateRegionMakeWithDistance(point, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: point, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = "destination"
mapItem.openInMaps(launchOptions: options)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBarMap.resignFirstResponder()
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(searchBar.text!) { (placemarks:[CLPlacemark]?, error:Error?) in
if error == nil {
let placemark = placemarks?.first
let anno = MKPointAnnotation()
anno.coordinate = (placemark?.location?.coordinate)!
anno.title = self.searchBarMap.text!
self.mapView.addAnnotation(anno)
self.mapView.selectAnnotation(anno, animated: true)
}else{
print(error?.localizedDescription ?? "error")
}
}
}
}

MapKit and Userdefaults issues ('NSUnknownKeyException', 'setValue for undefined key' when trying to open a view from my Annotation Callout )

I am working on an App where you have access to a Map and you can add some annotations and when you click them a callout appears with a button and if you press it, it will send you to another view. The problem is, when I want to open the View, the App crashes and I see the error I mentioned in the title. I don't know if this is a problem with my Userdefaults or maybe a problem with a function when I prepare a segue to call the view. I appreciate your help and comments. Here is my code...
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var hospitales = [MKPointAnnotation]()
var imagenes = [UIImage]()
//For UserDafaults data
var nombreHospital = [String]()
var distanciaEntreUbicaciones = [Double]()
struct Location {
let title: String
let latitude: Double
let longitude: Double
}
let locations = [
Location(title: "Hospital Zambrano", latitude: 25.647399800, longitude: -100.334304500),
Location(title: "Christus Mugerza Sur", latitude: 25.589339000, longitude: -100.257724800),
Location(title: "Saint Paul Hospital", latitude: 49.280524700, longitude: -123.128232600)
]
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
mapView.showsUserLocation = true
for location in locations {
//var i = 0
let point = MKPointAnnotation()
point.title = location.title
point.coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude)
nombreHospital.append(location.title)
//i += 1
//mapView.addAnnotation(point)
if let currentLocation = locationManager.location?.coordinate {
let locationMapPoint = MKMapPointForCoordinate(currentLocation)
let pinMapPoint = MKMapPointForCoordinate(point.coordinate)
let distance = MKMetersBetweenMapPoints(locationMapPoint, pinMapPoint)
UserDefaults.standard.set(distanciaEntreUbicaciones, forKey: "distancia")
UserDefaults.standard.synchronize()
if distance >= 0 && distance <= 45000000 {
let distancia: Double = round (distance / 1000)
distanciaEntreUbicaciones.append(distancia)
point.subtitle = "Dist. \(distancia) kilometros"
mapView.addAnnotation(point)
//Does not perform condition... Or that´s what happens to me
}
}
}
UserDefaults.standard.set(nombreHospital, forKey: "nombre")
UserDefaults.standard.set(distanciaEntreUbicaciones, forKey: "distancia")
UserDefaults.standard.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is MKPointAnnotation) {
print("No es de tipo MKPointAnnotation")
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "identifier")
if annotationView == nil{
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "identifier")
annotationView!.canShowCallout = true
annotationView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
annotationView!.annotation = annotation
}
annotationView!.image = UIImage(named: "curz")
return annotationView
}
var anotacionSeleccionada : MKPointAnnotation!
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
anotacionSeleccionada = view.annotation as? MKPointAnnotation
performSegue(withIdentifier: "vista", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//I want to open the segue in my DetailView class is it ok
//if I leave the as? ViewController? or should I change it?
if let destination = segue.destination as? ViewController {
//There´s also an error here, I want to open the view for an
//specific annotation, maybe an array will be good
destination.hospitales[] = anotacionSeleccionada
}
}
}
The error:

iOS: MapView Annotations not showing for pins

For some odd reason the viewForAnnotation is only working for the pin that is set in viewDidLoad (this is a test pin). The pins that are loaded elsewhere aren't getting annotated when pressed. I've already set the delegate. I think it has something to do with the identifier in the mapView call? But I'm unsure of how to fix it. Any help is appreciated! Thanks!
Here's my code:
import Foundation
import UIKit
import MapKit
import CoreLocation
import Alamofire
class MapViewController: UIViewController, MKMapViewDelegate {
var locationManager:CLLocationManager = CLLocationManager()
#IBOutlet weak var potholeMapView: MKMapView!
var listData: Array<String> = []
var idData: Array<Int> = []
var descriptionData: Array<String> = []
var latitudeData:Array<Double> = []
var longitudeData:Array<Double> = []
override func viewDidLoad() {
super.viewDidLoad()
potholeMapView.delegate = self
locationManager.requestWhenInUseAuthorization()
potholeMapView!.region = sanDiegoCountyLocation()
potholeMapView!.mapType = MKMapType.Standard
potholeMapView!.showsUserLocation = true
potholeMapView!.showsTraffic = true
print(potholeMapView!.userLocationVisible)
// WORKING HERE ACCESSORY VIEW SHOWS
let encinitas = CLLocationCoordinate2DMake(32.955, -117.2459)
let marker = AnnotatedLocation(
coordinate: encinitas,
title: "There",
subtitle: "You are not here")
potholeMapView!.addAnnotation(marker)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//HERE ACCESSORY VIEWS DONT SHOW
loadPotholeData()
}
func sanDiegoCountyLocation()-> MKCoordinateRegion {
let center = CLLocationCoordinate2DMake(32.76572795, -117.07319880 )
let widthMeters:CLLocationDistance = 100
let heightMeters:CLLocationDistance = 1000*120
return MKCoordinateRegionMakeWithDistance(center, widthMeters, heightMeters)
}
func loadPotholeData(){
let url = "http://bismarck.sdsu.edu/city/fromDate"
let parametersGet = ["type" : "street", "user" : "008812"]
Alamofire.request(.GET, url, parameters: parametersGet)
.responseJSON { response in
if let dataGet = response.result.value {
let dataDict:NSArray = dataGet as! NSArray
for item in dataDict{
let descrip = item["created"]
self.listData.append(descrip!! as! String)
let ids = item["id"]
self.idData.append(ids! as! Int)
let description = item["description"]
self.descriptionData.append(description!! as! String)
let latitude = item["latitude"]
self.latitudeData.append(latitude as! Double)
let longitude = item["longitude"]
self.longitudeData.append(longitude as! Double)
}
}
else {
print("There was some error getting data")
}
}
createAllPins()
}
func createAllPins(){
for (x, y) in zip(self.latitudeData, self.longitudeData) {
let location = CLLocationCoordinate2DMake(x, y)
let marker = AnnotatedLocation(
coordinate: location,
title: "",
subtitle: "")
potholeMapView!.addAnnotation(marker)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? AnnotatedLocation {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
//view = MKPinAnnotationView(annotation: <#T##MKAnnotation?#>, reuseIdentifier: <#T##String?#>)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
}
return view
}
return nil
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
self.performSegueWithIdentifier("pushAnnotation", sender: view)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "pushAnnotation":
let nextVC = segue.destinationViewController as! MapAnnotationDetailViewController
//nextVC.
default: break
}
}
}
}
It appears that it is because your title and subtitle for the others are blank. I tested out having nothing in quotations and adding something, and that seems to fix that issue.
For me, it was that after specifying my custom mapView.mapType, I had to also tell the mapView to "showAnnotations".
Until I told it to show them, the annotations would not display.
mapView.mapType = mapTypes[Preference.mapType]
mapView.showAnnotations(mapView.annotations, animated: true) //this fixed it

Update custom annotation pin image to standard annotation pin in swift

I want to update map view every 60 seconds & make an annotation with custom pin/image but want to show standard pin [red color - See Figure 6-1] icon to the previously drawn annotation. I tried like below code but that does not working properly. With another custom image it works but i can't show that default/standard red pin to previous annotation. Please see "currentLocationHasBeenUpdated" function where i tried to show standard red icon to the previous annotation. Please let me know how can i achieve this. Thanks.
My ViewController :
import UIKit
import MapKit
class FirstTabController: UIViewController, MKMapViewDelegate, DelegateForUpdateCurrentLocation {
#IBOutlet weak var mapView: MKMapView!
var gpsLocations : [[String: AnyObject]]!
var dataManager : DataManager!
var currentAnnotation : MKAnnotation!
//Return CLLocation Coordinate
func getLocationObject(latitude:Double, longitude:Double) -> CLLocationCoordinate2D {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude
)
}
//Create annotation object & return
func createAnnotation(latitude:Double, longitude:Double, locationName:String, territory:String) -> MKPointAnnotation {
let annotation = MKPointAnnotation()
annotation.coordinate = self.getLocationObject(latitude, longitude: longitude)
annotation.title = locationName
annotation.subtitle = territory
return annotation
}
//Create annotaion for current ship position
func createAnnotationForCurrentPosition(location:[String: AnyObject]) -> MKPointAnnotation {
let latitude = (location["latitude"] as? Double)!
let longitude = (location["longitude"] as? Double)!
let name = (location["locationName"] as? String)!
let territory = (location["territory"] as? String)!
return self.createAnnotation(latitude, longitude: longitude, locationName: name, territory: territory)
}
//Set region on map view
func setRegion(location:[String: AnyObject]){
let latitude = (location["latitude"] as? Double)!
let longitude = (location["longitude"] as? Double)!
let location = self.getLocationObject(latitude, longitude: longitude)
//Set zoom span
let span = MKCoordinateSpanMake(0.05, 0.05)
//Create region on map view & show
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
}
//This function will fire from data manager when current location from API has been updated
func currentLocationHasBeenUpdated(location:[String: AnyObject]){
dispatch_async(dispatch_get_main_queue()){
if self.currentAnnotation != nil {
var currentAnnotationView = self.mapView.viewForAnnotation(self.currentAnnotation)
if currentAnnotationView != nil {
currentAnnotationView.image = nil //this line makes app crash [gave nil to show standard red icon]
// currentAnnotationView.image = UIImage(named:"first") - this line works perfectly with different icon. but i don't want any custom icon except the standard red one
}
}
self.mapView.addAnnotation(self.createAnnotationForCurrentPosition(location))
self.setRegion(location)
}
}
//Update map view by scheduling time if current location is changed yet
func updateMapView() {
self.dataManager.getCurrentLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
//Get gps locations from data manager
self.dataManager = DataManager()
self.dataManager.delegate2 = self
self.dataManager.getCurrentLocation()
//self.mapView.userTrackingMode = MKUserTrackingMode.FollowWithHeading
//Get GPS location by scheduling time
NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("updateMapView"), userInfo: nil, repeats: true)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!{
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return nil
}
//Make custom annotaion pin if the annotation is of ship's current position
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
println("Hello")
self.currentAnnotation = annotation
//Custom annotation view with custom pin icon
let reuseId = "custom"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
}
else {
annotationView.annotation = annotation
}
//Set annotation specific properties after the view is dequeued or created...
annotationView.image = UIImage(named:"pinicon")
return annotationView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and for coordinates from api
import Foundation
extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)?.doubleValue
}
}
class DataSet{
var settings : Settings!
var getService : GetService!
var currentLocation : [String: AnyObject]!
//Object initialization for API call
init(){
self.settings = Settings()
self.getService = GetService()
}
func getCurrentLocation(callback:([String: AnyObject]) -> ()){
self.getService.apiCallToGet(self.settings.getCoordinates(), callback: {
(response) in
var location = [String: AnyObject]()
for item in response {
if let dictionary = item as? NSDictionary {
if let lat = dictionary["Lat"] as? String {
if lat.toDouble() != nil {
location["latitude"] = lat.toDouble()!
}
}
if let long = dictionary["Long"] as? String {
if long.toDouble() != nil {
location["longitude"] = long.toDouble()!
}
}
if let name = dictionary["Name"] as? String {
location["locationName"] = name
}
if let territory = dictionary["Territory"] as? String {
location["territory"] = territory
}
println(location["latitude"]!)
println(location["longitude"]!)
if self.currentLocation != nil {
if ((self.currentLocation["latitude"] as? Double) != (location["latitude"] as? Double)) && ((self.currentLocation["longitude"] as? Double) != (location["longitude"] as? Double)){
self.currentLocation = location
callback(location)
}
} else {
self.currentLocation = location
callback(location)
}
}
}
})
}
}
I have solved my problem by creating custom annotation class like below -
import UIKit
import MapKit
var ARROW_ANNOTATION : NSString = "ARROW_ANNOTATION"
var PIN_ANNOTATION : NSString = "PIN_ANNOTATION"
class Annotation: NSObject, MKAnnotation {
var currentLocation: CLLocationCoordinate2D
var _title : String
var subTitle : String
var direction : CLLocationDirection!
var typeOfAnnotation : String!
init(coordinate: CLLocationCoordinate2D, title : String, subTitle : String) {
self.currentLocation = coordinate
self._title = title
self.subTitle = subTitle
}
func getLocation() -> CLLocation {
return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
var coordinate: CLLocationCoordinate2D {
return self.currentLocation
}
var title : String {
return self._title
}
var subtitle : String {
return self.subTitle
}
}
and In my ViewController file -
override func viewDidLoad() {
super.viewDidLoad()
var annotation1 : Annotation = Annotation(coordinate: location, title: name, subTitle: territory)
annotation.typeOfAnnotation = PIN_ANNOTATION as String
self.mapView.addAnnotation(annotation1)
var annotation2 : Annotation = Annotation(coordinate: location, title: name, subTitle: territory)
annotation.typeOfAnnotation = ARROW_ANNOTATION as String
self.mapView.addAnnotation(annotation2)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
let reuseId = "custom"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
var customAnnotationView : MKAnnotationView!
if let _annotation = annotation as? Annotation {
if _annotation.typeOfAnnotation == PIN_ANNOTATION {
customAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
customAnnotationView.canShowCallout = true
//customAnnotationView.draggable = true
} else {
customAnnotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
// 17 - Determine the direction
let arrowImage = UIImage(named:"arrow")!
let direction = _annotation.direction
customAnnotationView.image = self.rotatedImage(arrowImage, byDegreesFromNorth: direction)
customAnnotationView.canShowCallout = true
}
} else {
return nil
}
return customAnnotationView
}

How to change MKAnnotation Color using Swift?

I have MKAnnotations set up on a map, but I would like to change the color of the annotations for different scenario's. Is there a way to change the color of the annotation?
Here is my code below, how would I implement the color change?
override func viewDidAppear(animated: Bool) {
var annotationQuery = PFQuery(className: "Post")
currentLoc = PFGeoPoint(location: MapViewLocationManager.location)
//annotationQuery.whereKey("Location", nearGeoPoint: currentLoc, withinMiles: 10)
annotationQuery.whereKeyExists("Location")
annotationQuery.findObjectsInBackgroundWithBlock {
(points, error) -> Void in
if error == nil {
// The find succeeded.
println("Successful query for annotations")
// Do something with the found objects
let myPosts = points as! [PFObject]
for post in myPosts {
let point = post["Location"] as! PFGeoPoint
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(point.latitude, point.longitude)
annotation.title = post["title"] as! String!
annotation.subtitle = post["username"] as! String!
self.mapView.addAnnotation(annotation)
}
} else {
// Log details of the failure
println("Error: \(error)")
}
}
You can use custom images for annotation view or use predefined MKPinAnnotationView with pinColor. But pinColors limited to Red, Green and Purple.
Some example:
import UIKit
import MapKit
class Annotation: NSObject, MKAnnotation
{
var coordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)
var custom_image: Bool = true
var color: MKPinAnnotationColor = MKPinAnnotationColor.Purple
}
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self;
let annotation = Annotation.new()
mapView.addAnnotation(annotation)
let annotation2 = Annotation.new()
annotation2.coordinate = CLLocationCoordinate2D(latitude: 0.0, longitude: 1.0)
annotation2.custom_image = false
mapView.addAnnotation(annotation2)
let annotation3 = Annotation.new()
annotation3.coordinate = CLLocationCoordinate2D(latitude: 1.0, longitude: 0.0)
annotation3.custom_image = false
annotation3.color = MKPinAnnotationColor.Green
mapView.addAnnotation(annotation3)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if (annotation is MKUserLocation) {
return nil
}
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
if let anAnnotation = annotation as? Annotation {
if anAnnotation.custom_image {
let reuseId = "custom_image"
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.image = UIImage(named:"custom_image")
}
else {
let reuseId = "pin"
let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView.pinColor = anAnnotation.color
anView = pinView
}
}
anView.canShowCallout = false
}
else {
anView.annotation = annotation
}
return anView
}
}
Update:
Set delegate for mapView in viewDidLoad
You have to set it in the viewForAnnotation method.
In this tutorial is quite well explained how doing it.

Resources