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

时间:2011-03-15 00:59:45

标签: cocoa-touch mkmapview

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

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

4 个答案:

答案 0 :(得分: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 :(得分: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)
}

答案 2 :(得分: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都会从布局指南中返回覆盖地图视图的面板高度

答案 3 :(得分: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)


    }