如何从MKmapview的可见区域获取半径?

Poo*_*hah 5 mkmapview ios swift

我能够获得地图视图的可见矩形以及地图视图的中心点和跨度增量也可以从mkmaap视图方法获得:获得可见的是:mapView.visibleMapRect 使用.获得中心点:map view.centerCoordinate使用并获得span:mapView.region.span使用.

现在我掌握了所有的信息,如何计算可见光的半径?任何人都可以详细解释我吗?

我已经看到了这个问题,但答案是给我跨度不是可见区域的半径.

小智 10

要获得半径,请遵循以下步骤:

- (CLLocationDistance)getRadius
{
    CLLocationCoordinate2D centerCoor = [self getCenterCoordinate];
    // init center location from center coordinate
    CLLocation *centerLocation = [[CLLocation alloc] initWithLatitude:centerCoor.latitude longitude:centerCoor.longitude];

    CLLocationCoordinate2D topCenterCoor = [self getTopCenterCoordinate];
    CLLocation *topCenterLocation = [[CLLocation alloc] initWithLatitude:topCenterCoor.latitude longitude:topCenterCoor.longitude];

    CLLocationDistance radius = [centerLocation distanceFromLocation:topCenterLocation];

    return radius;
}
Run Code Online (Sandbox Code Playgroud)

它将以为单位返回半径.

获得中心坐标

- (CLLocationCoordinate2D)getCenterCoordinate
{
    return [self.mapView centerCoordinate];
}
Run Code Online (Sandbox Code Playgroud)

获得半径取决于你想获得第二点的位置.让我们走顶级中心

- (CLLocationCoordinate2D)getTopCenterCoordinate
{
    // to get coordinate from CGPoint of your map
    return [self.mapView convertPoint:CGPointMake(self.mapView.frame.size.width / 2.0f, 0) toCoordinateFromView:self.mapView];
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*nzo 10

使用Swift 3.0,您可以使用扩展来简化您的生活:

extension MKMapView {

    func topCenterCoordinate() -> CLLocationCoordinate2D {
        return self.convert(CGPoint(x: self.frame.size.width / 2.0, y: 0), toCoordinateFrom: self)
    }

    func currentRadius() -> Double {
        let centerLocation = CLLocation(coordinate: self.centerCoordinate)
        let topCenterCoordinate = self.topCenterCoordinate()
        let topCenterLocation = CLLocation(coordinate: topCenterCoordinate)
        return centerLocation.distance(from: topCenterLocation)
    }

}
Run Code Online (Sandbox Code Playgroud)

使用Swift 4.0:

extension MKMapView {

    func topCenterCoordinate() -> CLLocationCoordinate2D {
        return self.convert(CGPoint(x: self.frame.size.width / 2.0, y: 0), toCoordinateFrom: self)
    }

    func currentRadius() -> Double {
        let centerLocation = CLLocation(latitude: self.centerCoordinate.latitude, longitude: self.centerCoordinate.longitude)
        let topCenterCoordinate = self.topCenterCoordinate()
        let topCenterLocation = CLLocation(latitude: topCenterCoordinate.latitude, longitude: topCenterCoordinate.longitude)
        return centerLocation.distance(from: topCenterLocation)
    }

}
Run Code Online (Sandbox Code Playgroud)

  • **Swift 4**:将`CLLocation(coordinate:*)`更改为`CLLocation(纬度:self.centerCoordinate.latitude,经度:self.centerCoordinate.longitude) (2认同)