Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the radius in meters using mapkit

Tags:

iphone

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

like image 427
gerardpg Avatar asked Jul 06 '10 15:07

gerardpg


2 Answers

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)

like image 63
krzyspmac Avatar answered Oct 16 '22 06:10

krzyspmac


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()
like image 26
Arsonik Avatar answered Oct 16 '22 06:10

Arsonik