简体   繁体   中英

Annotations not being placed on map

I'm trying to place an annotation (pin) on the map, and the pin is not showing on the simulator (there is no pin placed). I receive no errors in the code. Below is my viewDidLoad.

import UIKit
import MapKit

class MapViewController: UIViewController {

    var itemStore: ItemStore!
    var mapView: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView = MKMapView()

        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 40.71304, longitude: -74.0072)
        annotation.title = "Test"
        mapView.addAnnotation(annotation)
    }

Remove mapView = MKMapView() . This line creates a new MKMapView instance, while what you want to do is use the one that you created on your Storyboard. If you are not using a Storyboard, than you should use another initializer of MKMapView that sets its size as well.

Create a outlet from your storyboard to your view controller. Also I would probably add MKMapViewDelegate to your view controller.

import UIKit
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate {

var itemStore: ItemStore!
@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    let annotation = MKPointAnnotation()
    annotation.coordinate = CLLocationCoordinate2D(latitude: 40.71304, longitude: -74.0072)
    annotation.title = "Test"
    self.mapView.addAnnotation(annotation)
}

Initializing new MKMapview results in new Instance. That means nothing will be there. That's why the annotation may not get placed. Try removing that initialization and try to connect to IBOutlet if you have. Otherwise, initialize MKMapview totally programmatic with defining the frame for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM