Swift annotation location update

937 views Asked by At
import UIKit
import MapKit
import CoreLocation


class ServisimNeredeViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    var coordinates: [[Double]]!
    var names:[String]!
    var addresses:[String]!
    var phones:[String]!

    var locationManager :CLLocationManager = CLLocationManager()
    let singleton = Global.sharedGlobal

    let point = ServisimAnnotation(coordinate: CLLocationCoordinate2D(latitude: 41.052466 , longitude: 29.132123))

    override func viewDidLoad() {
        super.viewDidLoad()

        coordinates = [[41.052466,29.108976]]// Latitude,Longitude
        names = ["Servisiniz Burada"]
        addresses = ["Furkan Kutlu"]
        phones = ["5321458375"]
        self.map.delegate = self

        let coordinate = coordinates[0]

        point.image = UIImage(named: "direksiyon")
        point.name = names[0]
        point.address = addresses[0]
        point.phone = phones[0]
        self.map.addAnnotation(point)

        ...
    }

    ...
}

I add the coordinate's annotation when the first screen is loaded I update the newly set coordination when the button is pressed. I want instant update of location when button is pressed. How can I do it?

@IBAction func tttesttt(_ sender: Any) {
    self.point.coordinate = CLLocationCoordinate2D(latitude: 42.192846, longitude: 29.263417)       
}

Does not update the new location when you do the above operation. But the coordination is eliminated and the new one is updated instead I did it like this, but it did not happen again

DispatchQueue.main.async { 
    self.point.coordinate = CLLocationCoordinate2D(latitude: surucuKordinant.latitude!, longitude: surucuKordinant.longitude!)
}
1

There are 1 answers

0
Rob On

The likely issue is that your configuration property has not been configured for key-value observing (KVO), which is how the map and/or annotation view become aware of changes of coordinates.

I would ensure that coordinate is KVO-capable by including the dynamic keyword. For more information, see the Key-Value Observing in Using Swift with Cocoa and Objective-C: Adopting Cocoa Design Patterns.

Clearly, we don't have to do all of that observer code in that KVO discussion (as MapKit is doing all of that), but we do at least need to make our annotation KVO-capable. For example, your annotation class might look like:

class ServisimAnnotation: NSObject, MKAnnotation {
    dynamic var coordinate: CLLocationCoordinate2D
    ...
}

The failure to declare coordinate as dynamic will prevent key-value notifications from being posted, and thus changes to the annotation will not be reflected on the map.