开发者

Calculate the radius in meters using mapkit

I need to know the distance (in kilometers) from center map to the other side of the screen, (and if the zoom change the distance will change).

I need to implement this feature in this function

- (void)mapView:(MKMapView *)mapView regionDidChange开发者_运维问答Animated:(BOOL)animated{
}

Any ideas how i can do this?

Thanks


MkMapView has properties named centerCoordinate(CLLocationCoordinate2D) and region (MKCoordinateRegion). Region is a struct that:

typedef struct {
    CLLocationDegrees latitudeDelta;
    CLLocationDegrees longitudeDelta;
}MKCoordinateSpan

You should be able to create another point, based on centerCoordinate, let's say, by adding latitudeDelta to you latitude property or centerCoordinate, and calculate distance using the method of CLLocation:

- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location

Something like this

MkMapView * mapView; // init somewhere
MKCoordinateRegion region = mapView.region;
CLLocationCoordinate2D centerCoordinate = mapView.centerCoordinate;
CLLocation * newLocation = [[[CLLocation alloc] initWithLatitude:centerCoordinate.latitude+region.span.latitudeDelta longitude:centerCoordinate.longitude] autorelease];
CLLocation * centerLocation = [[[CLLocation alloc] initWithLatitude:centerCoordinate.latitude:longitude:centerCoordinate.longitude] autorelease];
CLLocationDistance distance = [centerLocation distanceFromLocation:newLocation]; // in meters

And just calculate each time a delegate fires a certain method (decide which you need: MKMapViewDelegate)


Because rectangles aren't circles you can't get a radius.

But you can still get the furthest distance from the center of a region. Reusing the same idea as above but embeded in a swift extension.

extension MKCoordinateRegion {
    func distanceMax() -> CLLocationDistance {
        let furthest = CLLocation(latitude: center.latitude + (span.latitudeDelta/2),
                             longitude: center.longitude + (span.longitudeDelta/2))
        let centerLoc = CLLocation(latitude: center.latitude, longitude: center.longitude)
        return centerLoc.distanceFromLocation(furthest)
    }
}

Usage

let radius = mapView.region.distanceMax()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜