gpt4 book ai didi

swift - 缩放 MapView 以显示 180 度经线的注释

转载 作者:行者123 更新时间:2023-11-30 12:55:12 25 4
gpt4 key购买 nike

我有一个带有 <5 个注释的 MapView。加载 map 时,我想放大以使 map 在这些注释上居中,例如 this 。但是,当注释分布在第 180 条经线(经度从 -180 到 +180 的范围内)时,链接方法不起作用。即使注释聚集在本初子午线周围,如何才能稳健地缩放注释?

例如,如果我有 x(0,179) 和 y(0,-179),那么我想要一个宽度为两度经度的包含矩形,而不是 358。

最佳答案

iOS 版 MapKit 实际上在 MKMapView 中有一个内置函数,可以执行以下操作:

showAnnotations(annotations: [MKAnnotation], animated: Bool)

但是,这个函数不提供对缩放级别的控制,所以我仍然必须创建自己的函数。这是伪代码:

zoomToAnnotations(annotations, zoomLimit) {
// calculate the midpoint as the average latitude and longitude
average_latitude = mean(a.coordinate.latitude for a in annotations)
average_longitude = atan2(mean(sin(a.coordinate.longitude) for a in annotations), mean(cos(a.coordinate.longitude) for a in annotations)) // be careful with degrees and radians in real code
regular_midpoint = coordinate(average_latitude, average_longitude)
// subtract 180 from longitude for the midpoint of the region crossing the meridian
meridian_midpoint = coordinate(average_latitude, average_longitude - 180.0)
if (meridian_midpoint.longitude < -180) {
meridian_midpoint.longitude += 360.0
}

// work out which region will be smaller and center map there
meridian_sum = sum(a.coordinate.distance(meridian_midpoint) for a in annotations)
regular_sum = sum(a.coordinate.distance(regular_midpoint) for a in annotations)
regular_max_distance = max(a.coordinate.distance(regular_midpoint) for a in annotations)
if meridian_sum < regular_sum {
meridian_max_distance = max(a.coordinate.distance(meridian_midpoint) for a in annotations)
centerMapWithRadius(meridian_midpoint, max(zoomLimit, meridian_max_distance))
} else {
regular_max_distance = max(a.coordinate.distance(regular_midpoint) for a in annotations)
centerMapWithRadius(regular_midpoint, max(zoomLimit, regular_max_distance))
}
}

此方法并不完美,因为它以点的平均值为中心,而不是让最远的点与边缘的距离相等。

关于swift - 缩放 MapView 以显示 180 度经线的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500679/

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