计算CLLocation数组的中心坐标点

时间:2016-12-14 11:13:15

标签: ios swift3 cllocation

如果我们有多个CLLocation点,如何计算MapView的中心点?

1 个答案:

答案 0 :(得分:1)

func zoomToFitPolyLine(pointsArr : NSArray) {
    if (pointsArr.count == 0) {
        return
    }
    var topLeftCoord : CLLocationCoordinate2D? = CLLocationCoordinate2DMake(-90, 180 )

    var bottomRightCoord : CLLocationCoordinate2D? = CLLocationCoordinate2DMake(90, -180 )

    for (index,_) in (pointsArr.enumerated()) {

        let tempLoc : CLLocation? = pointsArr.object(at: index) as? CLLocation

        topLeftCoord?.latitude = fmax((topLeftCoord?.latitude)!, (tempLoc?.coordinate.latitude)!)
        topLeftCoord?.longitude = fmin((topLeftCoord?.longitude)!, (tempLoc?.coordinate.longitude)!)

        bottomRightCoord?.latitude = fmin((bottomRightCoord?.latitude)!, (tempLoc?.coordinate.latitude)!)
        bottomRightCoord?.longitude = fmax((bottomRightCoord?.longitude)!, (tempLoc?.coordinate.longitude)!)
    }

    var centerCoordinate : CLLocationCoordinate2D? = CLLocationCoordinate2DMake(0, 0)

    centerCoordinate?.latitude = (topLeftCoord?.latitude)! - ((topLeftCoord?.latitude)! - (bottomRightCoord?.latitude)!) * 0.5;
    centerCoordinate?.longitude = (topLeftCoord?.longitude)! + ((bottomRightCoord?.longitude)! - (topLeftCoord?.longitude)!) * 0.5;
    self.zoomToRegion(location: centerCoordinate!)
}

func zoomToRegion(location:CLLocationCoordinate2D)
{
    let camera : MKMapCamera = MKMapCamera.init(lookingAtCenter: location, fromEyeCoordinate: location, eyeAltitude: CLLocationDegrees(10));
    myMap?.setCamera(camera, animated: true);
}