XCode的MapView (2)

如何在地圖上長按著某個位置不放,然後自動在長按的位置加入指針?

  1. 首先在viewDidLoad中為我們的mapview加入長按功能UILongPressGestureRecognizer。並於長按後自動執行longPress這個method.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UILongPressGestureRecognizer *lpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        lpress.minimumPressDuration = 0.5;
        lpress.allowableMovement = 10.0;
        [mapview addGestureRecognizer:lpress];
    }
  2. 我們在longPress中取得我們在mapview長按的位置,存入touchPoint,再使用touchPoint來建立位置touchMapCoordinate。然後建立指針pointAnnotation,並將剛才建立的位置touchMapCoordinate加入到指針中,最後將指針加入到mapview.
    - (void)longPress:(UIGestureRecognizer*)gestureRecognizer
    {
        if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
            return;
        }
        
        CGPoint touchPoint = [gestureRecognizer locationInView:mapview];
        CLLocationCoordinate2D touchMapCoordinate =
        [mapview convertPoint:touchPoint toCoordinateFromView:mapview];
        
        MKPointAnnotation *pointAnnotation = nil;
        pointAnnotation = [[MKPointAnnotation alloc] init];
        pointAnnotation.coordinate = touchMapCoordinate;
        pointAnnotation.title = @"title";
        pointAnnotation.subtitle=@"subtitle";
        
        [mapview addAnnotation:pointAnnotation];
    }
如何取得我們現時身處的位置。
  1. 啟動showsUserLocation,即可使用userLocation取得即時的位置。
    -(IBAction)goUserLocation:(id)sender
    {
    mapView.showsUserLocation = YES;
      CLLocationCoordinate2D userLoc;

    userLoc.latitude = mapView.userLocation.location.coordinate.latitude;
    userLoc.longitude = mapView.userLocation.location.coordinate.longitude;
    mapView.region = MKCoordinateRegionMakeWithDistance(userLoc, 50000, 50000);
    }


3 則留言:

匿名 提到...
作者已經移除這則留言。
匿名 提到...

請問小弟照著您的方法做

可是在觸發了長按的事件 出現了標記後

小弟只要移動手指

會出現一大堆的標記

請問這個要如何解決@@?

貧血軟派羅傑君 提到...

Hi Chen Yuan.

試著用在longPress事件中加入

if (gestureRecognizer.state == UIGestureRecognizerStateChanged ){
return;
}
看看