MapKit- How to add location constraints for dropping a pin?

Viewed 213

I have an application that allows users to drop a pin anywhere on their map (MapKit), and it currently identifies and displays their current location. I would like to set a constraint so that users are unable drop a pin any further than 10 miles from their current location. Is this doable? I am somewhat new to dev, so I am not sure where to begin doing this. Here's a bit of the code that deals with dropping pin:

@IBOutlet weak var mapView: MKMapView!


//addpin
@IBAction func addPin(sender: UILongPressGestureRecognizer) {


//locating where to drop the pin
    let location = sender.locationInView(self.mapView)
    let locCoord = self.mapView.convertPoint(location, toCoordinateFromView:
         self.mapView)

    let annotation = MKPointAnnotation()
    annotation.coordinate = locCoord
    annotation.title = "Test"
    annotation.subtitle = "subtext"

//remove map point (use later)

     self.mapView.removeAnnotations(mapView.annotations)

     self.mapView.addAnnotation(annotation)

}
1 Answers

You can use distance(from: ) method.

See: https://developer.apple.com/documentation/corelocation/cllocation/1423689-distance

@IBAction func addPin(sender: UILongPressGestureRecognizer) {

    //locating where to drop the pin
    let location = sender.locationInView(self.mapView)
    let locCoord = self.mapView.convertPoint(location, toCoordinateFromView:
     self.mapView)

    // Get distance between pressed location and user location
    let pressedLocation = CLLocation(latitude: locCoord.latitude, longitude: locCoord.longitude)
    // let distanceInMeters = self.mapView.userLocation.location?.distance(from: pressedLocation) // >= Swift 3
    let distanceInMeters = self.mapView.userLocation.location?.distanceFromLocation(pressedLocation) // < Swift 3

    // You get here distance in meter so 10 miles = 16090 meter
    if let distanceInMeters = distanceInMeters, distanceInMeters > 16090 {
        // out of 10 mile (don't drop pin)
        return
    }

    let annotation = MKPointAnnotation()
    annotation.coordinate = locCoord
    annotation.title = "Test"
    annotation.subtitle = "subtext"

    //remove map point (use later)

    self.mapView.removeAnnotations(mapView.annotations)

    self.mapView.addAnnotation(annotation)

}

However, there are couple of things that you need to put in place first.

  • You need to ask the user for permission to use their location. That includes calling CLLocationManager's requestWhenInUseAuthorization and checking for the asynchronous result.
  • Adding NSLocationWhenInUseUsageDescription entry to your info (described in the link above) to tell the user what you want to do with the information
Related