我想知道如何检查人是否在某个坐标附近,然后做一些事情,比如打个招呼进入测试台。现在我已经有了用户位置,每次人移动时它都会更新但是如何知道他是否靠近某些坐标或地址?例如:
func sayHello(){
if mapView.userLocation.coordinate.latitude == 26{
print("Hello")
}
代码I已经完成:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
}
答案 0 :(得分:2)
我要做的是每当您更新用户的位置时,请检查用户位置与您存储的地址位置之间的距离。如果用户在x米范围内,则打印“Hello”。
下面是我用来获取用户和地址之间距离的代码。如果您有一个包含地址及其坐标的对象数组,则可以遍历每个地址并为x米内的每个地址打印Hello。
let userLocation:CLLocation = CLLocation(latitude: 10.000, longitude: 29.000)
let addressLocation:CLLocation = CLLocation(latitude: 15.000, longitude: 20.000)
let meters:CLLocationDistance = userLocation.distanceFromLocation(addressLocation)
答案 1 :(得分:0)
获取两个坐标之间的距离,如果小于5米,则匹配show print statement
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
CLLocationDistance distance = [locA distanceFromLocation:locB];