MapKit+E.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // MapKit+E.swift
  3. // Pods
  4. //
  5. // Created by Groot on 2025/5/14.
  6. //
  7. import MapKit
  8. import Foundation
  9. extension MKMapView {
  10. // 按比例 按padding适应annotation
  11. public func fitsAllPoints(
  12. points: [MKMapPoint],
  13. padding: UIEdgeInsets,
  14. aspectRatio: Double? = nil,
  15. animated: Bool = true
  16. ) {
  17. var zoomRect: MKMapRect = .null
  18. for point in points {
  19. let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
  20. if zoomRect.isNull {
  21. zoomRect = pointRect
  22. } else {
  23. zoomRect = zoomRect.union(pointRect)
  24. }
  25. }
  26. // Calculate the desired size based on the aspect ratio
  27. let aspectRatio = aspectRatio ?? 1.0
  28. let width = zoomRect.size.width
  29. let height = zoomRect.size.height
  30. let desiredWidth = max(width, height * aspectRatio)
  31. let desiredHeight = max(height, width / aspectRatio)
  32. // Calculate the center of the annotations
  33. let center = MKMapPoint(x: zoomRect.midX, y: zoomRect.midY)
  34. // Create a new MKMapRect with the desired aspect ratio and centered on the annotations
  35. let newMapRect = MKMapRect(
  36. x: center.x - desiredWidth / 2,
  37. y: center.y - desiredHeight / 2,
  38. width: desiredWidth,
  39. height: desiredHeight
  40. )
  41. setVisibleMapRect(newMapRect, edgePadding: padding, animated: animated)
  42. }
  43. func calculateMapRect(points: [MKMapPoint], padding: UIEdgeInsets = .zero) -> MKMapRect {
  44. var zoomRect: MKMapRect = .null
  45. for point in points {
  46. let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
  47. if zoomRect.isNull {
  48. zoomRect = pointRect
  49. } else {
  50. zoomRect = zoomRect.union(pointRect)
  51. }
  52. }
  53. return mapRectThatFits(zoomRect, edgePadding: padding)
  54. }
  55. func takeSnapShot(option: MKMapSnapshotter.Options, completion: @escaping (MKMapSnapshotter.Snapshot?) -> Void) {
  56. let shotter = MKMapSnapshotter(options: option)
  57. shotter.start(with: .global()) { shot, _ in
  58. completion(shot)
  59. }
  60. }
  61. }