Получить привязанные координаты с помощью iphone mapkit
Я создаю приложение, используя фреймворк apple mapkit. Я хочу сделать, чтобы получить долготу и широту от того места, которое вы нажимаете. Я получаю координаты от текущего местоположения пользователей, используя этот код:
- (IBAction)longpressToGetLocation:(id)sender {
CLLocationCoordinate2D location = [[[self.mapView userLocation] location] coordinate];
NSLog(@"Location found from Map: %f %f",location.latitude,location.longitude);
}
Как мне получить этот код, чтобы отображать нажатое местоположение вместо userlocation?
Ответы
Ответ 1
Прежде всего, используйте UIGestureRecognizer
вместо IBAction
- (void)longpressToGetLocation:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
CLLocationCoordinate2D location =
[self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
NSLog(@"Location found from Map: %f %f",location.latitude,location.longitude);
}
Swift 2:
@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.Began { return }
let touchLocation = sender.locationInView(protectedMapView)
let locationCoordinate = protectedMapView.convertPoint(touchLocation, toCoordinateFromView: protectedMapView)
print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
}
Swift 3:
@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.began { return }
let touchLocation = sender.location(in: protectedMapView)
let locationCoordinate = protectedMapView.convert(touchLocation, toCoordinateFrom: protectedMapView)
print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
}
Ответ 2
class mapviewCtrl: UIViewController, UIGestureRecognizerDelegate
{
@IBOutlet var mapViewVar: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let lpgr = UILongPressGestureRecognizer(target: self, action:"handleLongPress:")
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
self.mapViewVar.addGestureRecognizer(lpgr)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.Ended {
let touchLocation = gestureReconizer.locationInView(mapViewVar)
let locationCoordinate = mapViewVar.convertPoint(touchLocation,toCoordinateFromView: mapViewVar)
println("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
return
}
if gestureReconizer.state != UIGestureRecognizerState.Began {
return
}
}
Ответ 3
Другим способом для swift 3 будет следующий: это mashup из нескольких фрагментов - с переопределением вы только обновляете код в одном месте, что может быть удобным, повысить модульность и удалить допущений и потенциальных аварийных ситуаций.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Let put in a log statement to see the order of events
print(#function)
for touch in touches {
let touchPoint = touch.location(in: self.mapView)
let location = self.mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
print ("\(location.latitude), \(location.longitude)")
}
}