我想这样做:
在mapView上,我有3个按钮。当应用首次运行时-坐标最初从1个按钮显示。使用时,按第二个或另一个按钮-坐标更改为另一个
var lang = 40.7143528
var long = -74.0059731
let annotation = MKPointAnnotation()
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let distanceSpan: CLLocationDegrees = 2000
let bsuCSCampus: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lang, long)
mapView.setRegion(MKCoordinateRegionMakeWithDistance(bsuCSCampus, distanceSpan, distanceSpan), animated: true)
annotation.coordinate = bsuCSCampus
annotation.title = "Big Ben"
mapView.addAnnotation(annotation)
mapView.selectAnnotation(annotation, animated: true)
@IBAction func firstBtn(_ sender: UIButton) {
lang = 40.7143528
long = -74.0059731
}
@IBAction func secondBtn(_ sender: UIButton) {
lang = 40.69144874
long = -73.9290688
}
@IBAction func thirdBtn(_ sender: UIButton) {
lang = 40.63728056
long = -73.9455483
}
但是当我按下任何按钮时都不会发生
答案 0 :(得分:0)
当然什么也没发生。您有两个实例变量lat和long,您的IBAction只是在更改这些实例变量。他们与地图显示的内容无关。
如果您一次只希望显示一个注释,并且每次都希望地图以该注释为中心,则应该:
创建函数showAnnotationAt(coord: CLLocationCoordinate2D)
在该函数中:
现在从viewDidLoad()和所有按钮操作中调用该函数。
看看您是否可以算出如何编写代码。如果遇到问题,请发布您的代码,然后有人会帮助您对其进行调试。 不请我为您编写该代码。
答案 1 :(得分:0)
我建议您使用一个函数来添加注释和缩放注释:
func addAnnotation(lang: Double, long: Double, title: String) {
let annotation = MKPointAnnotation()
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lang, long)
mapView.setRegion(MKCoordinateRegionMakeWithDistance(location, distanceSpan, distanceSpan), animated: true)
annotation.coordinate = location
annotation.title = title
mapView.addAnnotation(annotation)
mapView.selectAnnotation(annotation, animated: true)
}
这将使您的代码如下所示:
var lang = 40.7143528
var long = -74.0059731
let distanceSpan: CLLocationDegrees = 2000
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
点击按钮将使用所需的lang
,long
和注释标题来调用此功能:
@IBAction func firstBtn(_ sender: UIButton) {
addAnnotation(lang: 40.7143528, long: -74.0059731, title: "Big Ben")
}
@IBAction func secondBtn(_ sender: UIButton) {
addAnnotation(lang: 40.69144874, long: -73.9290688, title: "963 Greene Ave, Brooklyn")
}
@IBAction func thirdBtn(_ sender: UIButton) {
addAnnotation(lang: 40.63728056, long: -73.9455483, title: "585 E 32nd St, Brooklyn")
}
如果您有一系列位置词典:
var locations = [["latitude": 40.7143528, "longitude": -74.0059731],
["latitude": 40.69144874, "longitude": -73.9290688],
["latitude": 40.63728056, "longitude": -73.9455483]]
然后您可以使用此功能:
func addAnnotations(From arrayOfLocations : [[String : Double]]) {
let annotations: [MKPointAnnotation] = arrayOfLocations.map {locationDictionary in
guard let latitude = locationDictionary["latitude"], let longitude = locationDictionary["longitude"] else {
fatalError("Wrong coordinates")
}
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
return annotation
}
mapView.addAnnotations(annotations)
mapView.showAnnotations(annotations, animated: true)
}