gerardpg
gerardpg

Reputation: 61

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 regionDidChangeAnimated:(BOOL)animated{
}

Any ideas how i can do this?

Thanks

Upvotes: 6

Views: 4394

Answers (2)

Arsonik
Arsonik

Reputation: 2316

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()

Upvotes: 4

krzyspmac
krzyspmac

Reputation: 605

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)

Upvotes: 18

Related Questions