我將一個位置傳遞給另一個UIViewController
,該位置的MapView
使用的是prepareForSegue
。我稱之爲receivedLocation
。地圖以傳遞的位置爲中心。如果用戶點擊一個按鈕將它們帶到地圖上而不先發送位置,這是否會失敗?在Swift中,我可以檢測一個CLLocation是否有效嗎?
如何測試以確定receivedLocation
是否實際上包含數據,以便我可以將地圖設置爲以其他方式爲中心,如果它爲空?
會創建一個布爾變量,並最初將其設置爲false,但通過一個位置並測試時,它將其變爲true我的願望?
我看到一個名爲CLLocationCoordinateIsValid
的東西可用,但它的參數是2DCoordinate,在這裏我碰到了測試receivedLocation
是否存在同樣的問題。
我對此很新,並試圖尋找答案,但找不到合適的答案。謝謝!
import UIKit
import MapKit
import CoreLocation
class mapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet var map: MKMapView!
@IBOutlet var notes: UITextView!
var receivedLocation = CLLocation()
var annotation = MKPointAnnotation()
var currentManager:CLLocationManager!
var latitute:CLLocationDegrees = CLLocationDegrees()
var longitude:CLLocationDegrees = CLLocationDegrees()
override func viewDidLoad() {
super.viewDidLoad()
map.layer.cornerRadius = 12.0
notes.layer.cornerRadius = 12.0
currentManager = CLLocationManager()
currentManager.delegate = self
currentManager.desiredAccuracy = kCLLocationAccuracyBest
currentManager.startUpdatingLocation()
if CLLocationCoordinate2DIsValid(receivedLocation.coordinate) {
latitute = receivedLocation.coordinate.latitude
longitude = receivedLocation.coordinate.longitude
annotation.coordinate.latitude = receivedLocation.coordinate.latitude
annotation.coordinate.longitude = receivedLocation.coordinate.longitude
map.addAnnotation(annotation)
} else {
latitute = currentManager.location.coordinate.latitude
longitude = currentManager.location.coordinate.longitude
}
var latDelta: CLLocationDegrees = 0.01
var lonDelta: CLLocationDegrees = 0.01
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
var location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitute, longitude)
var region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
map.setRegion(region, animated: false)
}
到目前爲止,這不適用於我。 CLLocationCoordinate2DIsValid總是返回true並以一個島爲中心,並向該怪異點添加註釋。
顯示。你的。碼。 – matt
@CodyLucas如果你只想檢查有效的位置,你可以使用'CLLocationCoordinateIsValid'函數,就像你在你的問題中提到的那樣。這裏是迅速 '變種位置= CLLocation示例代碼() VAR的isValid = CLLocationCoordinate2DIsValid(location.coordinate)' 瞭解的問題更深入地需要你的源代碼在這裏。 –
@matt你在這裏 –