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

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



Solution 1:[1]

According to their documentation it appears that you just need to construct your MGLCoordinateBounds from the list of geo positions similar to the workflow of Apple Maps and then call https://docs.mapbox.com/ios/maps/api/6.3.0/Classes/MGLMapView.html#/c:objc(cs)MGLMapView(im)setVisibleCoordinateBounds:animated: on your map box view.

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krysov
Solution 2 Val Moratalla