如何从MKmapview的可见区域获取半径?
我能够获得地图视图的可见矩形以及地图视图的中心点和跨度增量也可以从mkmaap视图方法获得:要获得可见的:使用mapView.visibleMapRect
。 要获得中心点:使用map view.centerCoordinate
并获取span:使用mapView.region.span
。
现在我掌握了所有信息,如何计算可见半径是否使用计算? 任何人都可以详细解释我吗?
我已经看到了这个问题,但答案是给我跨度而不是可见区域的半径。
要获得半径,请遵循以下步骤:
- (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; }
它将以米为单位返回半径。
获得中心坐标
- (CLLocationCoordinate2D)getCenterCoordinate { return [self.mapView centerCoordinate]; }
获得半径取决于你想获得第二点的位置。 让我们走顶级中心
- (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]; }
使用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) } }
使用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) } }