Update Annotations

Asked

Viewed 33 times

1

I need to update the map’s Annotations after inserting values into Coredata. i have the first view with the map, and a second where I add the new values for new Annotations, but only when I first enter the application do the updated annotations appear. I think I need to correct the map every time I enter the first view controller. How can I update the values (Annotations)? this is the code for annotations and map:

override func viewDidLoad() {

        super.viewDidLoad()

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

        latitude = lat.text!
        longitude = long.text!

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

            if (error != nil)
            {
                println("Error: " + error.localizedDescription)
                return
            }

            if placemarks.count > 0
            {
                let pm = placemarks[0] as! CLPlacemark
                self.displayLocationInfo(pm)
            }
            else
            {
                println("Error with the data.")
            }
        })
    }

    func displayLocationInfo(placemark:CLPlacemark){
        println("display")
        self.locManager.stopUpdatingLocation()



        lat.text = String(stringInterpolationSegment: placemark.location.coordinate.latitude);
        long.text = String(stringInterpolationSegment: placemark.location.coordinate.longitude);
        latitude = lat.text!
        longitude = long.text!

        var latD:CLLocationDegrees = 0.1
        var longD:CLLocationDegrees = 0.1

        var la:CLLocationDegrees = (latitude as NSString).doubleValue
        var lo:CLLocationDegrees = (longitude as NSString).doubleValue

        var span:MKCoordinateSpan = MKCoordinateSpanMake(latD, longD)

        var locat:CLLocationCoordinate2D = CLLocationCoordinate2DMake(la, lo)
        var locat2:CLLocationCoordinate2D = CLLocationCoordinate2DMake(la+1, lo+1)
        var reg:MKCoordinateRegion = MKCoordinateRegionMake(locat, span)
        mapRadar.setRegion(reg, animated: true)

        //Anotações

        var anot = [MKPointAnnotation]()



        var request:NSFetchRequest = NSFetchRequest(entityName: "Radar")

        let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        let context:NSManagedObjectContext = appDelegate.managedObjectContext!

        request.returnsObjectsAsFaults = false

        var results:NSArray = context.executeFetchRequest(request, error: nil)!

        //println(results.count)
        //println(results.objectAtIndex(0))

        if results.count > 0
        {
            for result in results
            {
            var anotacao = MKPointAnnotation()
                let r = result as! Radar
              //  println(r.velocidade)

                locat.latitude = (r.latitude as NSString).doubleValue
                locat.longitude = (r.longitude as NSString).doubleValue

        anotacao.coordinate = locat

        anotacao.title = r.descricao

        anotacao.subtitle = "-_-" //String(_cocoaString: r.velocidade)

                anot += [anotacao]
            }
        }

        self.mapRadar.addAnnotations(anot)
    }

1 answer

1


It is only being updated when it opens because you are getting the location by the method startUpdatingLocation() and consequently its method of displayLocationInfo() in the viewDidLoad().

To call every time you open this screen, you can get the location on viewDidAppear():

override func viewDidAppear() {
    super.viewDidAppear()
    locManager.startUpdatingLocation()
}

But from what I understand of your code, you can optimize and get the location only once because there seems to be no need for the location all the time and then insert the annotations at each screen opening, for this a second method would serve only to fetch this data from the database:

func displayAnnotations() {
    mapRadar.removeAnnotations(mapRadar.annotations)

    var anot = [MKPointAnnotation]()

    var request:NSFetchRequest = NSFetchRequest(entityName: "Radar")

    let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context:NSManagedObjectContext = appDelegate.managedObjectContext!

    request.returnsObjectsAsFaults = false

    var results:NSArray = context.executeFetchRequest(request, error: nil)!

    if results.count > 0 {
        for result in results {
            var anotacao = MKPointAnnotation()

            let r = result as! Radar

            anotacao.coordinate = CLLocationCoordinate2DMake((r.latitude as NSString).doubleValue, (r.longitude as NSString).doubleValue)
            anotacao.title = r.descricao
            anotacao.subtitle = "-_-"

            anot += [anotacao]
        }
    }

    mapRadar.addAnnotations(anot)
}

Note that I need to remove the Annotations to add new ones, otherwise you will be on top of each other. And this method you call in viewDidAppear().

Still a third option, if this second screen opens from this map screen, you can create a delegate so that this above method can be executed only when there is need from a new insertion in the database.

  • Thank you very much, solved my problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.