我有一个应用程序,允许用户在地图上的任何地方放置一个引脚(MapKit),它当前识别并显示它们的当前位置。我想设置一个约束,以便用户无法在距当前位置10英里的范围内丢弃一个引脚。这可行吗?我对dev很新,所以我不知道从哪里开始这样做。这里有一些处理drop 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)
}
答案 0 :(得分:1)
您可以使用distance(from: )
方法。
请参阅: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)
}
但是,您需要先做好几件事。