0

I'm trying to implement map navigation from source to destination in app. I just want to dynamically calculate latitudedelta and longitudedelta based on center coords.

let midLat = (self.source.coordinate.latitude + self.destination.coordinate.latitude)/2
let midLang = (self.source.coordinate.longitude + self.destination.coordinate.longitude)/2
let centerCoordinate = CLLocationCoordinate2DMake(midLat, midLang)
self.mapView.setRegion(MKCoordinateRegionMake(centerCoOrdinate, MKCoordinateSpanMake(0.09, 0.09)), animated: true)
Karthik
  • 21
  • 7

1 Answers1

0

First of all you have a problem calculating the mid location, you must check this answer Determining Midpoint Between 2 Cooridinates using the extension proposed there

import Foundation
import MapKit
extension CLLocationCoordinate2D {
    // MARK: CLLocationCoordinate2D+MidPoint
    func middleLocationWith(location:CLLocationCoordinate2D) -> CLLocationCoordinate2D {

        let lon1 = longitude * M_PI / 180
        let lon2 = location.longitude * M_PI / 180
        let lat1 = latitude * M_PI / 180
        let lat2 = location.latitude * M_PI / 180
        let dLon = lon2 - lon1
        let x = cos(lat2) * cos(dLon)
        let y = cos(lat2) * sin(dLon)

        let lat3 = atan2( sin(lat1) + sin(lat2), sqrt((cos(lat1) + x) * (cos(lat1) + x) + y * y) )
        let lon3 = lon1 + atan2(y, cos(lat1) + x)

        let center:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat3 * 180 / M_PI, lon3 * 180 / M_PI)
        return center
    }
}

then you use it like this

let middleLocation = self.source.coordinate.middleLocationWith(location: self.destination.coordinate)
self.mapView.setRegion(MKCoordinateRegionMake(middleLocation, MKCoordinateSpanMake(0.09, 0.09)), animated: true)

I hope this helps you

Community
  • 1
  • 1
Reinier Melian
  • 20,519
  • 3
  • 38
  • 55