5

我正在尝试学习如何在 ios6 中使用折线连接地图上的两个点。首先,我已经阅读了关于这个主题的每一个教程,一个简单的谷歌搜索出现了,并且由于一个原因不能让折线工作。我看到的每个教程总是将折线添加到地图并调整地图的缩放以适应整条线。如果我希望地图以恒定距离保持放大并且仅在大于当前视图时才显示多段线的末端,我将如何在 ios6 中制作和添加多段线到地图中?例如,假设我有一条一英里长的折线,并希望地图保持放大的恒定距离,相当于:

MKCoordinateRegion userRegion = MKCoordinateRegionMakeWithDistance(self.currentLocation.coordinate, 1000, 1000);
    [self.mainMap setRegion:[self.mainMap regionThatFits:userRegion] animated:YES];

我该怎么做呢?请提供完整的代码示例或我可以下载的示例项目!

4

1 回答 1

0

MKMapPoint * malloc / 分配:

MKMapPoint *newPoints = malloc((sizeof (MKMapPoint) * nbPoints));
newPoints[index] = varMKMapPoint;
free(newPoints);

MKPolyline 必须在您需要的地方初始化:

MKPolyline *polyline  = [MKPolyline polylineWithPoints:newPoints count:nbPoints];
[self.mapView addOverlay:polyline];

要显示您的 MKPolyline,您必须使用 viewForOverlay :

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKOverlayView* overlayView = [[MKOverlayView alloc] initWithOverlay:overlay];        
    if([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineView *backgroundView = [[MKPolylineView alloc] initWithPolyline:overlay];
        backgroundView.fillColor = [UIColor blackColor];
        backgroundView.strokeColor = backgroundView.fillColor;
        backgroundView.lineWidth = 10;
        backgroundView.lineCap = kCGLineCapSquare;
        overlayView = backgroundView;
    }
    return overlayView;
}

要使用此方法,您必须将您的点转换为 CLLocation,它将返回一个您将设置为 mapView 的 MKCoordinateRegion:

- (MKCoordinateRegion)getCenterRegionFromPoints:(NSArray *)points
{
    CLLocationCoordinate2D topLeftCoordinate;
    topLeftCoordinate.latitude = -90;
    topLeftCoordinate.longitude = 180;
    CLLocationCoordinate2D bottomRightCoordinate;
    bottomRightCoordinate.latitude = 90;
    bottomRightCoordinate.longitude = -180;
    for (CLLocation *location in points) {
        topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, location.coordinate.longitude);
        topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, location.coordinate.latitude);
        bottomRightCoordinate.longitude = fmax(bottomRightCoordinate.longitude, location.coordinate.longitude);
        bottomRightCoordinate.latitude = fmin(bottomRightCoordinate.latitude, location.coordinate.latitude);
    }
    MKCoordinateRegion region;
    region.center.latitude = topLeftCoordinate.latitude - (topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 0.5;
    region.center.longitude = topLeftCoordinate.longitude + (bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 1.2; //2
    region.span.longitudeDelta = fabs(bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 1.2; //2
//    NSLog(@"zoom lvl : %f, %f", region.span.latitudeDelta, region.span.latitudeDelta);
    return region;
}

希望这可以帮助。

于 2012-12-28T12:24:06.207 回答