1
我使用CLLocationManager來請求用戶的位置。但是,如果他們不在紐約市,我想默認爲某些座標。有沒有辦法檢查他們是否在某個城市?Swift + CLLocationManager:如何判斷用戶是否在特定的城市?
import UIKit
import CoreLocation
import GoogleMaps
private let kDefaultLatitude: Double = 40.713
private let kDefaultLongitude: Double = -74.000
private let kDefaultZoomLevel: Float = 16.0
class RootMapViewController: UIViewController {
@IBOutlet weak var mapView: GMSMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
fetchLocation()
}
private func fetchLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
// MARK: CLLocationManagerDelegate
extension RootMapViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
let userCoordinates = locations[0].coordinate
// How do I check if the user is in NYC?
// if user is in nyc
centerMapOn(userCoordinates)
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
// else default to Times Square
}
}
這樣的問題,我在這樣的方式實現的 - 每個城市都有中心點和半徑,然後只需比較,如果用戶位置是在距離中心點的半徑最近的城市與否。如果你需要更詳細地實現這樣的問題,你需要一個具有所有座標的多邊形,所以一切都取決於你的主要任務是什麼以及它應該有多準確。 –