我正在做一个像这样的项目。
有一个带有邮政编码的文本框/按钮,并将邮政编码传递给地图视图控制器的segue,该控制器显示地图上的邮政编码区域。整个设置位于导航控制器后面,以便我可以返回并尝试上一个视图中的其他邮政编码。
问题是地图视图第一次正确地绘制了邮政编码,但是当我返回并在前一个视图控制器中输入另一个邮政编码时,地图视图不会将该区域设置为新的邮政编码正确地,它显示了一个新的地图视图,其中包含模拟器中的默认区域。请参阅以下代码
class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView!
var searchZipCode:String! = "95110" //used by other segues to set zipcode to show on this page
let locationManager = CLLocationManager()
let geocoder = CLGeocoder()
var dispatchGroup = dispatch_group_create()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup)
self.plotZipCodeInMap(self.searchZipCode)
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()){
print("Zip code plotted.")
}
func plotZipCodeInMap(zipCode:String) {
geocoder.geocodeAddressString(zipCode, completionHandler: {(placemarks, error) -> Void in
print("Zip code = \(zipCode)")
if let placemark = placemarks?.first {
print("Successfully decoded the zip code..")
let coordinate = placemark.location?.coordinate
let center = CLLocationCoordinate2D(latitude: coordinate!.latitude, longitude: coordinate!.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.04, longitudeDelta: 0.04))
self.mapView.setRegion(region, animated: true)
dispatch_group_leave(self.dispatchGroup)
}
})
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Location updated..")
let locations = locations.last
let center = CLLocationCoordinate2D(latitude: locations!.coordinate.latitude, longitude: locations!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.075, longitudeDelta: 0.075))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
}
问题是当我回到导航控制器中的第一个视图并点击另一个邮政编码时,地图视图似乎正在正确地进入plotZipCodeInMap方法,但是它不会打印该行
“已成功解码邮政编码..”
这意味着第二次获得地标会有一些麻烦。不知道这里有什么问题。变量都是本地变量,我希望它们在单击后退按钮(地图视图消失)时的行为没有区别,并且根据我的输入再次显示另一个邮政编码。
答案 0 :(得分:0)
发现问题,它与视图消失/重新出现无关,而是与我所做的地理编码调用次数有关。当我打印错误时,它全部清除 - kCLErrorDomain error 2 after geocoding repeatedly with CLGeocoder