使用两个函数将注释添加到mapView中

时间:2017-04-09 18:17:15

标签: swift mapbox

我已经创建了这两个函数,当我调用函数pippo()时,我收到一个错误"致命错误:在解开一个Optional值"时意外地发现了nil,为了修复这个错误,我修改了这个mapView.addAnnotation(hello)进入mapView?.addAnnotation(hello),但我没有在地图中显示注释,如果我在caricamappa中调用pippo注释成功添加,但我想分离函数加载图并添加注释,有可能吗?

func caricamappa(){
    let styleURL = NSURL(string: "mapbox://**")
    let mapView = MGLMapView(frame: view.bounds,
                              styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 46.370417,
                                              longitude: 8.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)
    mapView.delegate = self

}

func pippo(){
    let hello = MGLPointAnnotation()
    hello.coordinate = CLLocationCoordinate2D(latitude: 46.376362, longitude: 8.396907)
    hello.title = "Hello world!"
    hello.subtitle = "Welcome to my marker"

    // Add marker `hello` to the map.
    mapView.addAnnotation(hello)

}



override func viewDidLoad() {
    super.viewDidLoad()
    caricamappa()
    pippo()
}

1 个答案:

答案 0 :(得分:0)

您在caricamappa中定义了mapView,因此它在pippo中不存在。相反,请将mapView设置为方法之外的IBOutlet。

相关问题