简体   繁体   中英

MapKit Rotate Rectangle Around Center

I need to rotate rectangle around it's center, rectangle is a polygon on map kit, I have 4 points and center. I rotate every point separately and then create new polygon.

I use this code:

    if let rotation = rotation, let center = zoneCenter {
        let radians = Double(rotation) * (Double.pi/180.0)
        print(radians)
        var newPoints: [CLLocationCoordinate2D] = []
        for point in squarePoints {
            let latitude: CLLocationDegrees = center.latitude + (point.longitude - center.longitude) * sin(radians) + (point.latitude - center.latitude) * cos(radians)

            let longitude: CLLocationDegrees = center.longitude + (point.longitude - center.longitude) * cos(radians) - (point.latitude - center.latitude) * sin(radians)

            newPoints.append(CLLocationCoordinate2DMake(latitude, longitude))
        }

        squarePointsWithRotation = newPoints
        squareOverlay = MKPolygon(coordinates: &newPoints, count: squarePoints.count)
        mapView.add(squareOverlay)
    }
}

Where "let rotation" can be from 0 to 180. I have the next result

在此处输入图片说明

在此处输入图片说明

As you can see rectangle becomes a diamond and angles is not 90 degrees like it have to be. Can't figure out how to keep all angles 90 degrees. I use this formula for rotation

/// X = x0 + (x - x0) * cos(a) - (y - y0) * sin(a);
/// Y = y0 + (y - y0) * cos(a) + (x - x0) * sin(a);
/// where x0, y0 - center, a - rotation angle, x, y  - point to rotate`

Hope for help!

I found out what's wrong, formula was wrong, because Earth is not flat. Now it's working properly. Code:

let latitude: CLLocationDegrees = center.latitude + sin(radians) * (point.longitude - center.longitude) * abs(cos(center.latitude * (Double.pi/180.0))) + cos(radians) * (point.latitude - center.latitude)

let longitude: CLLocationDegrees = center.longitude + cos(radians) * (point.longitude - center.longitude) - sin(radians) * (point.latitude - center.latitude) / abs(cos((center.latitude * (Double.pi/180.0))))

And formula:

/// X = x0 + cos(a) * (x - x0) - sin(a) * (y - y0) / abs(cos(y0 * pi/180));
/// Y = y0 + cos(a) * (y - y0) + sin(a) * (x - x0) * abs(cos(y0 * pi/180));
/// where x0, y0 - center, a - rotation angle, x, y  - point to rotate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM