iOS MapBox fit camera to multiple coordinates [latitude and longitude] or annotations

Viewed 197

in MapBox documentation for android there is LatLngBounds, but for iOS there are nothing, is there any way todo it for iOS

2 Answers

As of Mapbox v10.4.3, this solution works for me, basically you need 4 coordinates that will serve as the rect bounds for the camera.

https://docs.mapbox.com/ios/maps/guides/migrate-to-v10/#fit-the-camera-to-a-given-shape

Sample Snippet

class Coordinate {
  var longitude: Double = 0
  var latitude: Double = 0

  init(longitude: Double, latitude: Double) {
    self.longitude = longitude
    self.latitude = latitude
    self.datasetId = datasetId
  }

  func coordinates() -> CLLocationCoordinate2D {
    return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
  }
}

func setCoordinateBounds(bounds: [Coordinate]) -> CoordinateBounds {
    var flyTo = MKMapRect.null
      for bound in bounds {
        let point: MKMapPoint = MKMapPoint(bound.coordinates())
        let pointRect = MKMapRect(x: point.x, y: point.y, width: 0, height: 0)
        flyTo = flyTo.isNull ? pointRect : flyTo.union(pointRect)
      }
    let coordNE = MKMapPoint(x: flyTo.origin.x, y: flyTo.maxY).coordinate
    let coordSW = MKMapPoint(x: flyTo.maxX, y: flyTo.origin.y).coordinate
    return CoordinateBounds(southwest: coordSW, northeast: coordNE)
  }

// Implementation
let coordinates = [
    CLLocationCoordinate2DMake(24, -89),
    CLLocationCoordinate2DMake(24, -88),
    CLLocationCoordinate2DMake(26, -88),
    CLLocationCoordinate2DMake(26, -89),
    CLLocationCoordinate2DMake(24, -89)
]
let coordinateBounds = setCoordinateBounds(bounds: coordinates)
let cameraOptions = self.mapView.mapboxMap.camera(for: coordinateBounds, padding: UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20), bearing: self.mapView.cameraState.bearing, pitch: 0)
      self.mapView.camera.fly(to: cameraOptions, duration: 0.3, completion: nil)
Related