作者:mobiledu2502889283 | 来源:互联网 | 2023-05-24 21:32
我有2个注释要显示在mapview上,但无法设置maprect以在屏幕上显示所有这些注释而无需用户缩小.
我试过showAnnotations
但没有运气.任何人都可以在Swift和Xcode 6.1.1中做到这一点?
这是我的代码:
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var mapView = map
// 1
let point1 = CLLocationCoordinate2D(latitude: 38.915565, longitude: -77.093524)
let point2 = CLLocationCoordinate2D(latitude: 38.890693, longitude: -76.933318)
//2
let annotation = MKPointAnnotation()
annotation.setCoordinate(point1)
annotation.title = "point1"
map.addAnnotation(annotation)
let annotation2 = MKPointAnnotation()
annotation2.setCoordinate(point2)
annotation2.title = "point2"
map.addAnnotation(annotation2)
//3
// option1: set maprect to cover all annotations, doesn't work
var points = [annotation, annotation2]
var rect = MKMapRectNull
for p in points {
let k = MKMapPointForCoordinate(p.coordinate)
rect = MKMapRectUnion(rect, MKMapRectMake(k.x, k.y, 0.1, 0.1))
println("result: x = \(rect.origin.x) y = \(rect.origin.y)")
}
map.setVisibleMapRect(rect, animated: true)
// option 2: using showAnnotations, doesn't work
//map.showAnnotations(points, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这就是我目前所得到的:
这是我期望看到的:
谢谢你的帮助.
1> tala9999..:
我终于找到了为什么注释的引脚没有显示在屏幕的可见区域中.我认为MapKit框架的行为与以前的版本略有不同.由于我使用autolayout允许地图扩展到所有设备(iPhone,iPad)的整个屏幕,因此应在mapViewDidFinishLoadingMap中调用setVisibleMapRect或mapView.showAnnotations,而不是在视图控制器的viewDidLoad中调用
例如:
func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
// this is where visible maprect should be set
mapView.showAnnotations(mapView.annotations, animated: true)
}