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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With