在 MapView 上绘制矩形

cas*_*las 2 mapkit ios

我的应用程序获取以下覆盖区域中的数据。我想使用这些边界值在地图上绘制矩形。你有什么主意吗?提前致谢

左上边界:30.439217,-95.899668;

右上边界:30.443953,-94.685679;

左按钮边界:28.930662,-95.908595;

右臀边界:28.930061,-94.690486;

lio*_*dar 5

如果你想用线条画一些基本的东西,你可以使用这个 MKPolyline

试试下面的代码,确保你的委托与你的 mapview 对象连接

- (void) drawRect
{

    CLLocation *coordinates1 =  [[CLLocation alloc] initWithLatitude:30.439217 longitude:-95.899668];

    CLLocation *coordinates2 =  [[CLLocation alloc] initWithLatitude:30.443953 longitude:-94.685679];

    CLLocation *coordinates3 =  [[CLLocation alloc] initWithLatitude:28.930061 longitude:-94.690486];

    CLLocation *coordinates4 =  [[CLLocation alloc] initWithLatitude:28.930662 longitude:-95.908595];


    NSMutableArray *locationCoordinates = [[NSMutableArray alloc] initWithObjects:coordinates1,coordinates2,coordinates3,coordinates4,coordinates1, nil];

    int numberOfCoordinates = [locationCoordinates count];

    CLLocationCoordinate2D coordinates[numberOfCoordinates];


    for (NSInteger i = 0; i < [locationCoordinates count]; i++) {

        CLLocation *location = [locationCoordinates objectAtIndex:i];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[i] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfCoordinates];
    [self.myMapView addOverlay:polyLine];


}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {

    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor redColor];
    polylineView.lineWidth = 1.0;

    return polylineView;
}
Run Code Online (Sandbox Code Playgroud)

更新:这是 drawRect 函数的快速版本

func drawRect() {
    let coordinates1 = CLLocation(latitude: 30.439217, longitude: -95.899668)
    let coordinates2 = CLLocation(latitude: 30.443953, longitude: -94.685679)
    let coordinates3 = CLLocation(latitude: 28.930061, longitude: -94.690486)
    let coordinates4 = CLLocation(latitude: 28.930662, longitude: -95.908595)
    let locationCoordinates = [coordinates1,coordinates2,coordinates3,coordinates4,coordinates1]

    let coordinates = locationCoordinates.map { $0.coordinate }

    let polyLine = MKPolyline(coordinates: coordinates, count: coordinates.count)
    mapView.addOver(polyLine)
}
Run Code Online (Sandbox Code Playgroud)

更换

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay (deprecated)
Run Code Online (Sandbox Code Playgroud)

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer
Run Code Online (Sandbox Code Playgroud)