首次尝试使用基于Swift的MapKit / CoreLocation iOS应用。很明显,这个难度似乎在第一期就出现了!
该应用程序专注于高尔夫球场。所以我希望能够在球场上选择一个洞,地图将平移,缩放和放大旋转,以便:
显然,每个洞的大小,形状和方向都不同。
我使用Google地图获取了一些坐标,并拥有当前的[基本]代码:
@IBAction func buttonHole10Tap(_ sender: UIButton) {
let hole10nw = CLLocationCoordinate2D(latitude: 53.873931, longitude: -1.482514)
let hole10sw = CLLocationCoordinate2D(latitude: 53.870293, longitude: -1.480026)
let hole10se = CLLocationCoordinate2D(latitude: 53.870341, longitude: -1.479719)
let hole10ne = CLLocationCoordinate2D(latitude: 53.874079, longitude: -1.481551)
let hole10Rect = createMKMapRect(nw: hole10nw, se: hole10se)
let hole10Bearing = getBearing(from: CLLocationCoordinate2D(latitude: 53.870363, longitude: -1.479884), to: CLLocationCoordinate2D(latitude: 53.874023, longitude: -1.482110))
print("bearing: \(hole10Bearing), \(360+hole10Bearing)") // = -19, rather than 360-19 = 340 degrees...
mapView.camera.heading = 360 + hole10Bearing
mapView.setVisibleMapRect(hole10Rect, edgePadding: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: false)
}
func createMKMapRect(nw: CLLocationCoordinate2D, se: CLLocationCoordinate2D) -> MKMapRect {
let nwPoint = MKMapPointForCoordinate(nw)
let nwRect = MKMapRectMake(nwPoint.x, nwPoint.y, 0, 0)
let sePoint = MKMapPointForCoordinate(se)
let seRect = MKMapRectMake(sePoint.x, sePoint.y, 0, 0)
let rect = MKMapRectUnion(nwRect, seRect)
return rect
}
func getBearing(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> Double {
let fromLat = degreesToRadians(degrees: from.latitude)
let fromLon = degreesToRadians(degrees: from.longitude)
let toLat = degreesToRadians(degrees: to.latitude);
let toLon = degreesToRadians(degrees: to.longitude);
let deltaLon = toLon - fromLon;
let y = sin(deltaLon) * cos(toLat);
let x = cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(deltaLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radians: radiansBearing)
}
func degreesToRadians(degrees: Double) -> Double { return degrees * Double.pi / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / Double.pi }
我希望这张图片显示我想要实现的目标...目前正在获取红色框,但我想获得绿色框。