gpt4 book ai didi

swift - 计算 MKMapView 中 MKPolygon 的面积

转载 作者:可可西里 更新时间:2023-10-31 23:57:07 25 4
gpt4 key购买 nike

我只是不知道如何计算 MKMapView 上的面积。有谁解决过这个问题吗?

这是我的代码,但它返回的太多了:

func ringArea() -> Double{
var area: Double = 0

if templocations.count > 2 {
var p1,p2:CLLocationCoordinate2D

for var i = 0; i < templocations.count - 1; i++ {
var loc = templocations[i] as CLLocation
p1 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)

loc = templocations[i+1] as CLLocation
p2 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)

var sinfunc: Float = (2 + sinf(Float(degreeToRadiant(p1.latitude))) + sinf(Float(degreeToRadiant(p2.latitude))))

area += degreeToRadiant(p2.longitude - p1.longitude) * Double(sinfunc)
}
area = area * kEarthRadius * kEarthRadius / 2;
}
return area
}

最佳答案

Stefan 在 Swift 5.0 中的回答:

import MapKit
let kEarthRadius = 6378137.0

func radians(degrees: Double) -> Double {
return degrees * .pi / 180
}

func regionArea(locations: [CLLocationCoordinate2D]) -> Double {

guard locations.count > 2 else { return 0 }
var area = 0.0

for i in 0..<locations.count {
let p1 = locations[i > 0 ? i - 1 : locations.count - 1]
let p2 = locations[i]

area += radians(degrees: p2.longitude - p1.longitude) * (2 + sin(radians(degrees: p1.latitude)) + sin(radians(degrees: p2.latitude)) )
}
area = -(area * kEarthRadius * kEarthRadius / 2)
return max(area, -area) // In order not to worry about is polygon clockwise or counterclockwise defined.
}

关于swift - 计算 MKMapView 中 MKPolygon 的面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com