我遇到了這個問題,它好像有關於回答一些混亂。以下是使用Swift 3獲取位置信息的廣泛途徑,僅限於任何未來的讀者。
此功能碼使用didUpdateLocations
功能和reverseGeocodeLocation()
將位置轉換爲人類可讀地址。它還將地圖視圖設置爲當前用戶位置。這當然假設你已經設置了你的位置管理器對象。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Get first location item returned from locations array
let userLocation = locations[0]
// Convert location into object with human readable address components
CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in
// Check for errors
if error != nil {
print(error ?? "Unknown Error")
} else {
// Get the first placemark from the placemarks array.
// This is your address object
if let placemark = placemarks?[0] {
// Create an empty string for street address
var streetAddress = ""
// Check that values aren't nil, then add them to empty string
// "subThoroughfare" is building number, "thoroughfare" is street
if placemark.subThoroughfare != nil && placemark.thoroughfare != nil {
streetAddress = placemark.subThoroughfare! + " " + placemark.thoroughfare!
} else {
print("Unable to find street address")
}
// Same as above, but for city
var city = ""
// locality gives you the city name
if placemark.locality != nil {
city = placemark.locality!
} else {
print("Unable to find city")
}
// Do the same for state
var state = ""
// administrativeArea gives you the state
if placemark.administrativeArea != nil {
state = placemark.administrativeArea!
} else {
print("Unable to find state")
}
// And finally the postal code (zip code)
var zip = ""
if placemark.postalCode != nil {
zip = placemark.postalCode!
} else {
print("Unable to find zip")
}
print("\(streetAddress)\n\(city), \(state) \(zip)")
}
}
}
// Create a coordinate based on users location latitude and longitude
let coordinate = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,
longitude: userLocation.coordinate.longitude)
// Set the span (zoom) of the map view. Smaller number zooms in closer
let span = MKCoordinateSpan(latitudeDelta: 0.001, longitudeDelta: 0.001)
// Set the region, using your coordinates & span objects
let region = MKCoordinateRegion(center: coordinate, span: span)
// Set your map object's region to the region you just defined
map.setRegion(region, animated: true)
}
geoCoder在哪裏定義?它是你的視圖控制器的成員嗎? – xpereta