【问题标题】:SwiftUI Map is not centered around the annotationsSwiftUI Map 不以注释为中心
【发布时间】:2021-10-19 06:26:14
【问题描述】:

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

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

【问题讨论】:

  • 如果您希望您的问题得到解答,您需要让专家尽快获得具有可重现问题的工作样本。完美地,我应该将您的代码粘贴到我的示例项目中,并在我运行它时尽快看到问题。请将您的代码更新为minimal reproducible example

标签: ios swift swiftui mapkit


【解决方案1】:

要更改地图显示的内容,您只需更改其绑定的region (coordinateRegion: $region)。 更改其center 会移动地图。要对缩放进行操作,您必须对 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(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
    }

【讨论】:

  • 移动到第一个元素的方法不正确,我希望 Map 正确聚焦所有引脚并缩放,我需要计算
  • 计算结果为 here。我调整了该函数以使其在您的代码中可用。我编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
相关资源
最近更新 更多