gpt4 book ai didi

ios - SwiftUI Map 不以注释为中心

转载 作者:行者123 更新时间:2023-12-05 02:40:02 27 4
gpt4 key购买 nike

我使用下面的代码加载 map ,但在结果出现后, map 仍然以用户位置为中心,而不是在注释周围,因此我必须滚动到图钉才能看到。

Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: searchResults) { dest in
MapAnnotation(coordinate: dest.coordinate, anchorPoint: CGPoint(x: 0.5, y: 0.5)) {
MapPin(coordinate)
}
}

最佳答案

要更改 map 显示的内容,您只需更改它绑定(bind)的区域 (coordinateRegion: $region)。改变它的 center 移动 map 。要对缩放进行操作,您必须对 span 属性进行操作。

我已经建议您将卡片移动到 searchResults 数组的第一个元素:

Map(coordinateRegion: $region, annotationItems: searchResults) {result in
MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) {newValue in
if let result = newValue.first {
region.center = result.coordinate
}
}

但是如果你想移动(和放大/缩小) map 以使其包含所有结果:

Map(coordinateRegion: $region, annotationItems: searchResults) { result in
MapMarker(coordinate: result.coordinate)
}
.onChange(of: searchResults) { _ in
if !searchResults.isEmpty {
region = regionThatFitsTo(coordinates: searchResults.map { $0.coordinate })
}
}

以及计算适合区域的函数:

func regionThatFitsTo(coordinates: [CLLocationCoordinate2D]) -> MKCoordinateRegion {
var topLeftCoord = CLLocationCoordinate2D(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D(latitude: 90, longitude: -180)
for coordinate in coordinates {
topLeftCoord.longitude = fmin(topLeftCoord.longitude, coordinate.longitude)
topLeftCoord.latitude = fmax(topLeftCoord.latitude, coordinate.latitude)
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, coordinate.longitude)
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, coordinate.latitude)
}

var region: MKCoordinateRegion = MKCoordinateRegion()
region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5
region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.4
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.4
return region
}

关于ios - SwiftUI Map 不以注释为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68815758/

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