Home > Back-end >  How To Zoom In Using northeast, southwest and center coordinate In SwiftUI Map
How To Zoom In Using northeast, southwest and center coordinate In SwiftUI Map

Time:10-11

I have the coordinate for northeast, southwest and center coordinates for a country Philippines

but it does not zoom in there. This is the code I am using in OnAppear in the map view

@State private var region = MKCoordinateRegion()

var body: some View {
    Map(coordinateRegion: $region)
    .edgesIgnoringSafeArea(.all)
    .onAppear() {
      region = MapTool.getPARCoordinateRegion()
    }
  }
static func getPARCoordinateRegion() -> MKCoordinateRegion {
    let ph = getPHCountryPlaceMark()
    let southWestPoint = MKMapPoint(x: ph.southWestLongitude, y: ph.southWestLatitude)
    let northEastPoint = MKMapPoint(x: ph.northEastLongitude, y: ph.northEastLatitude)
    let northWestPoint = MKMapPoint(x: southWestPoint.x, y: northEastPoint.y)
    let mapRectWidth = northEastPoint.x - northWestPoint.x
    let mapRectHeight = northWestPoint.y - southWestPoint.y
    return MKCoordinateRegion(MKMapRect(x: southWestPoint.x, y: southWestPoint.y, width: mapRectWidth, height: mapRectHeight))
  }
static func getPHCountryPlaceMark() -> CountryPlaceMark {
    let countryPlaceMark = CountryPlaceMark()
    countryPlaceMark.longName = "Philippines"
    countryPlaceMark.shortName = "PH"
    countryPlaceMark.centerLatitude = 12.879721
    countryPlaceMark.centerLongitude = 121.774017
    countryPlaceMark.southWestLatitude = 4.613444
    countryPlaceMark.southWestLongitude = 116.931557
    countryPlaceMark.northEastLatitude = 19.574024
    countryPlaceMark.northEastLongitude = 126.604384
    return countryPlaceMark
  }

But instead zooms here. Thoughts?

CodePudding user response:

I don't work with MKMapPoints but give this a try:

let coordinates = [CLLocationCoordinate2D(latitude: 4.613444, longitude: 116.931557), CLLocationCoordinate2D(latitude: 19.574024, longitude: 126.604384)]

func getPARCoordinateRegion() -> MKCoordinateRegion {
    return MKCoordinateRegion(makeRect(coordinates: coordinates))
}

func makeRect(coordinates: [CLLocationCoordinate2D]) -> MKMapRect {
    let rects = coordinates.lazy.map { MKMapRect(origin: MKMapPoint($0), size: MKMapSize()) }
    let fittingRect = rects.reduce(MKMapRect.null) { $0.union($1) }
    return fittingRect
}
  • Related