我有以下代码,但它没有显示位置。
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)
}
感谢您的帮助。
答案 0 :(得分:2)
这里可能有几件事情:
将代码从那里移到 view 事件,例如viewDidLoad
,viewDidAppear
或viewWillAppear
。我将向您展示第一个示例:
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)
}
如果您想访问用户位置,请小心,在这种情况下,您必须通过locationManager请求它并将正确的字符串添加到.plist文件中
最后,成为一名优秀的 SO 公民,并将积分给予任何给出正确答案的人,或者至少评论一下,如果这些答案都不正确(即使是这一点)。< / p>
答案 1 :(得分:1)
试试这个
self.Map.setCamera(camera, animated: true)
答案 2 :(得分:0)
如前所述,您正在使用didReceiveMemoryWarning(),您希望将其放在viewDidLoad()中,以便在加载视图时调用代码。
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)
}