如何根据选定的注释移动MKMapView

问题描述 投票:11回答:4

我有一个MKMapView填充了我的整个视图,但是当选择了一个引脚时,我正在向上滑动地图顶部的另一个视图。我想移动地图,以便引脚显示在地图可见区域的中心。

很难解释,但希望它有意义!提前致谢。

cocoa-touch mkmapview
4个回答
33
投票

您可以尝试从visibleMapRect获取MKMapRect作为地图视图,将注释的坐标转换为MKMapPoint,重置MKMapRect的原点以使MKMapPoint处于适当的位置,然后使用setVisibleMapRect:animated:将可见区域设置为新的MKMapRect。

例如,如果要移动地图以使注释水平居中并垂直向下25%,则可以执行以下操作:

MKMapRect r = [mapView visibleMapRect];
MKMapPoint pt = MKMapPointForCoordinate([annotation coordinate]);
r.origin.x = pt.x - r.size.width * 0.5;
r.origin.y = pt.y - r.size.height * 0.25;
[mapView setVisibleMapRect:r animated:YES]; 

1
投票

使用MKMapViewDelegate方法:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

    // center the mapView on the selected pin
    let region = MKCoordinateRegion(center: view.annotation!.coordinate, span: mapView.region.span)
    mapView.setRegion(region, animated: true)
}

0
投票

我最终得到了以下程序:

**以注释为中心:**

- (void) centerOnSelection:(id<MKAnnotation>)annotation
{
    MKCoordinateRegion region = self.mapView.region;
    region.center = annotation.coordinate;

    CGFloat per = ([self sizeOfBottom] - [self sizeOfTop]) / (2 * self.mapView.frame.size.height);
    region.center.latitude -= self.mapView.region.span.latitudeDelta * per;

    [self.mapView setRegion:region animated:YES];
}

**缩放注释:**

- (void) zoomAndCenterOnSelection:(id<MKAnnotation>)annotation
{
    DLog(@"zoomAndCenterOnSelection");

    MKCoordinateRegion region = self.mapView.region;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.005, 0.005);

    region.center = annotation.coordinate;

    CGFloat per = ([self sizeOfBottom] - [self sizeOfTop]) / (2 * self.mapView.frame.size.height);
    region.center.latitude -= self.mapView.region.span.latitudeDelta * span.latitudeDelta / region.span.latitudeDelta * per;

    region.span = span;

    [self.mapView setRegion:region animated:YES];
}

-(CGFloat) sizeOfBottom-(CGFloat) sizeOfTop都从布局指南返回覆盖mapview的面板高度


0
投票

我根据这里的答案在Swift 4上构建了它

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {

        // center the mapView on the selected pin
        var dest = view.annotation!.coordinate
        if view.annotation?.title == "Name of Annotation View"{//This is for move a little down depending on the MKAnnotationView size
            dest.latitude = dest.latitude + 0.002
        }
        let span = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01)
        let region = MKCoordinateRegion(center: dest, span: span)
        mapView.setRegion(region, animated: true)


    }
© www.soinside.com 2019 - 2024. All rights reserved.