How to move a MKAnnotation without adding/removing it from the map?

前端 未结 11 1164
情深已故
情深已故 2020-12-13 06:22

Is it possible to move the coordinate of a MKAnnotation without adding and removing the annotation from the map?

11条回答
  •  悲&欢浪女
    2020-12-13 07:06

    Most answers are based on fact that your Annotation has been made via MKPlacemark extending. But what about any other object (i.e. custom image for marker) which only implements MKAnnotation protocol? It wouldn't have the setCoordinate method. So here is the answer based on code, provided by 100grams

        MKAnnotationView *av = [self.mapView viewForAnnotation:user];
        //user is an object which implements 
        // You will probably get your MKAnnotationView in your own way
        if (av){
            // here user returns CLLocationCoordinate2D coordinate  
            MKMapPoint mapPoint = MKMapPointForCoordinate([user getLastLocation]); 
            // converting mapPoint to CGPoint 
            CGPoint newPos;
            CGFloat zoomFactor =  self.mapView.visibleMapRect.size.width / self.mapView.bounds.size.width;
            newPos.x = mapPoint.x/zoomFactor;
            newPos.y = mapPoint.y/zoomFactor;
            // animation for annotation's move
            static NSString *POSITION_KEY=@"positionAnimation";
        static NSString *PATH_ANIMATION_KEY=@"position";
        if (MKMapRectContainsPoint(self.mapView.visibleMapRect, mapPoint)) {
            CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:PATH_ANIMATION_KEY];
            animation.fromValue = [NSValue valueWithCGPoint:av.center];
            animation.toValue = [NSValue valueWithCGPoint:newPos];  
            animation.duration = 0.3;
            animation.delegate = av;
            animation.fillMode = kCAFillModeForwards;
            [av.layer addAnimation:animation forKey:POSITION_KEY];
        }
            // moving view
            av.center = newPos;
    

    so You basically need to get the corresponding MKAnnotationView which could be also achieved by iteration via all of annotations and it's new location. I made an array holder for all of it (NSMutableArray *mapAnnotaions) so now I could iterate just like:

    for (id annotation in mapAnnotaions) {call refresh method here for id}
    

提交回复
热议问题