19

Appleのmapkitフレームワークを使用してアプリを作成しています。私がやりたいのは、あなたが押した場所から経度と緯度を取得することです。このコードを使用して、ユーザーの現在地から座標を取得します。

- (IBAction)longpressToGetLocation:(id)sender {
    CLLocationCoordinate2D location = [[[self.mapView userLocation] location] coordinate];
    NSLog(@"Location found from Map: %f %f",location.latitude,location.longitude);
}

ユーザーの場所ではなく、押された場所を表示するコードを取得するにはどうすればよいですか?

4

3 に答える 3

60

まず、UIGestureRecognizer代わりにa を使用します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);

}

スウィフト 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)")
}

スウィフト 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)")
}
于 2013-01-29T10:28:03.983 に答える
3

Swift 3のもう 1 つの方法は 次のとおりです。これはいくつかのスニペットのマッシュアップです。オーバーライドを使用すると、コードを 1 か所で更新するだけで、便利になり、モジュール性が向上し、仮定と潜在的なクラッシュ ポイントが削除されます。

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Let's 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)")
    }
}
于 2017-08-23T12:18:53.820 に答える