faridorid
faridorid

Reputation: 33

Swift Map kit annotation

I have the following code, but it doesn´t show the location.

import Foundation
import UIKit    
import MapKit    
import CoreLocation

class ViewTwo : UIViewController {

 @IBOutlet var Map: MKMapView!

 override func didReceiveMemoryWarning() {
    super.viewDidLoad()
    var location = CLLocationCoordinate2DMake(51.385493, 6.741528)
    var span = MKCoordinateSpanMake(0.2, 0.2)
    var region = MKCoordinateRegion(center: location , span: span)
    Map.setRegion(region, animated: true)

    var annotation =  MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = "hi"
    annotation.coordinate = location
    Map.addAnnotation(annotation)
 }

Thanks for the help in advance.

Upvotes: 0

Views: 185

Answers (3)

djacobsdev
djacobsdev

Reputation: 71

As stated you are working inside of didReceiveMemoryWarning(), you want to place it in viewDidLoad() so that the code is called when the view is loaded.

import Foundation
import UIKit    
import MapKit    
import CoreLocation

class ViewTwo : UIViewController {

 @IBOutlet var Map: MKMapView!

 override func viewDidLoad() {
  super.viewDidLoad()
  var location = CLLocationCoordinate2DMake(51.385493, 6.741528)
  var span = MKCoordinateSpanMake(0.2, 0.2)
  var region = MKCoordinateRegion(center: location , span: span)
  Map.setRegion(region, animated: true)

  var annotation =  MKPointAnnotation()
  annotation.coordinate = location
  annotation.title = "hi"
  annotation.coordinate = location
  Map.addAnnotation(annotation)
 }

Upvotes: 0

Mauricio Chirino
Mauricio Chirino

Reputation: 1232

There might be several things here:

  1. Move your code out from there to a view event such as viewDidLoad, viewDidAppear or viewWillAppear. I'll show you an example with the first one:

    override func viewDidLoad() {
        super.viewDidLoad()
        var location = CLLocationCoordinate2DMake(51.385493, 6.741528)
        var span = MKCoordinateSpanMake(0.2, 0.2)
        var region = MKCoordinateRegion(center: location , span: span)
        Map.setRegion(region, animated: true)
        var annotation =  MKPointAnnotation()
        annotation.coordinate = location
        annotation.title = "hi"
        annotation.coordinate = location
        Map.addAnnotation(annotation)
    }
    
  2. Careful if you want to access user location, in that case you MUST request for it via a locationManager and add the proper string into the .plist file

  3. Finally, be a good SO citizen and grant the points to whoever had given the right answer or at the very least comment if none of them are correct (even this one).

Upvotes: 2

demopix
demopix

Reputation: 169

try this

self.Map.setCamera(camera, animated: true)

Upvotes: 1

Related Questions