Determining Midpoint Between 2 Coordinates

后端 未结 5 1437
深忆病人
深忆病人 2020-12-15 04:55

I am trying to determine the midpoint between two locations in an MKMapView. I am following the method outlined here (and here) and rewrote it in Objective-C,

5条回答
  •  渐次进展
    2020-12-15 05:17

    In case someone need code in Swift, I have written library function in Swift to calculate the midpoint between MULTIPLE coordinates:

    //        /** Degrees to Radian **/
    class func degreeToRadian(angle:CLLocationDegrees) -> CGFloat {
        return (  (CGFloat(angle)) / 180.0 * CGFloat(M_PI)  )
    }
    
    //        /** Radians to Degrees **/
    class func radianToDegree(radian:CGFloat) -> CLLocationDegrees {
        return CLLocationDegrees(  radian * CGFloat(180.0 / M_PI)  )
    }
    
    class func middlePointOfListMarkers(listCoords: [CLLocationCoordinate2D]) -> CLLocationCoordinate2D {
    
        var x = 0.0 as CGFloat
        var y = 0.0 as CGFloat
        var z = 0.0 as CGFloat
    
        for coordinate in listCoords{
            var lat:CGFloat = degreeToRadian(coordinate.latitude)
            var lon:CGFloat = degreeToRadian(coordinate.longitude)
            x = x + cos(lat) * cos(lon)
            y = y + cos(lat) * sin(lon)
            z = z + sin(lat)
        }
    
        x = x/CGFloat(listCoords.count)
        y = y/CGFloat(listCoords.count)
        z = z/CGFloat(listCoords.count)
    
        var resultLon: CGFloat = atan2(y, x)
        var resultHyp: CGFloat = sqrt(x*x+y*y)
        var resultLat:CGFloat = atan2(z, resultHyp)
    
        var newLat = radianToDegree(resultLat)
        var newLon = radianToDegree(resultLon)
        var result:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: newLat, longitude: newLon)
    
        return result
    
    }
    

    Detailed answer can be found here

    Updated For Swift 5

    func geographicMidpoint(betweenCoordinates coordinates: [CLLocationCoordinate2D]) -> CLLocationCoordinate2D {
    
        guard coordinates.count > 1 else {
            return coordinates.first ?? // return the only coordinate
                CLLocationCoordinate2D(latitude: 0, longitude: 0) // return null island if no coordinates were given
        }
    
        var x = Double(0)
        var y = Double(0)
        var z = Double(0)
    
        for coordinate in coordinates {
            let lat = coordinate.latitude.toRadians()
            let lon = coordinate.longitude.toRadians()
            x += cos(lat) * cos(lon)
            y += cos(lat) * sin(lon)
            z += sin(lat)
        }
    
        x /= Double(coordinates.count)
        y /= Double(coordinates.count)
        z /= Double(coordinates.count)
    
        let lon = atan2(y, x)
        let hyp = sqrt(x * x + y * y)
        let lat = atan2(z, hyp)
    
        return CLLocationCoordinate2D(latitude: lat.toDegrees(), longitude: lon.toDegrees())
    }
    

    }

提交回复
热议问题