Tarvo Mäesepp Tarvo Mäesepp - 6 months ago 39
Swift Question

Near given coordinates, print hello in Swift, MapKit and corelocation

I would like to know how to check if person is near some coordinates and then do something like say hello into console for testing. Right now I have already got user location and it is going to update every time person moves but how to know if he is near some coordinates or address? For example:

func sayHello(){
if mapView.userLocation.coordinate.latitude == 26{
print("Hello")
}


Code I've done already:

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)
}
}

Answer

What I would do is every time you update the user's location, check the distance between your user's location and the address location(s) you have stored. If the user is within x meters, print "Hello".

Below is code I would use to get the distance between your user and the address. If you have an array of objects that contain your addresses and their coordinates you could loop through each address and print Hello for each address that is within x meters.

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)