ios - SwiftUI Map 不以注释为中心

标签 ios swift swiftui mapkit

我使用下面的代码加载 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/

相关文章:

objective-c - 为什么在 Safari 中打开 URL 时 Table Cell 不会立即取消选择?

ios - 打开位置设置在 iOS 11 中不起作用

ios - UIAlertView 在 iOS7 上有可滚动的标题和消息

ios - 在 UISegmentedControl 中,如何将正常颜色与所选颜色分开?

swiftui - 如何将全局应用程序状态桥接到模型 View (使用@ObservedObject)?

ios - Swift 不同版本的二进制兼容性

ios - 如何在 CollectionView 中创建这个布局

swift - CAGradientLayer 位置为负值

ios - Canvas SwiftUI 崩溃

ios - Xcode 12 - 当有另一个 Swift 包作为依赖项时,SwiftUI 预览在 Swift 包上不起作用 - 'previewInstances' 给代理的消息