Reputation: 6164
In an iPhone App how can you calculate distance between two points in MKMapView
as shown in the image below?
The first point would be the center point of the visible map in the mapview.
The 2nd point would be any of corner of the visible rectangle of the mapview (here, for example I have taken the top left point).
I want to calculate this distance in meters. How can I achieve that?
My goal is to calculate the ratios of the visible Map rectangle in MKMapview
.
Upvotes: 8
Views: 20397
Reputation: 3269
Swift 3+
let distance: CLLocationDistance = location1.distance(from: location2)
Upvotes: 3
Reputation: 23550
Here is how you can calculate the wanted distance :
// You first have to get the corner point and convert it to a coordinate
MKMapRect mapRect = self.mapView.visibleMapRect;
MKMapPoint cornerPointNW = MKMapPointMake(mapRect.origin.x, mapRect.origin.y);
CLLocationCoordinate2D cornerCoordinate = MKCoordinateForMapPoint(cornerPointNW);
// Then get the center coordinate of the mapView (just a shortcut for convenience)
CLLocationCoordinate2D centerCoordinate = self.mapView.centerCoordinate
// And then calculate the distance
CLLocationDistance distance = [cornerCoordinate distanceFromLocation:centerCoordinate];
Upvotes: 2
Reputation: 5360
You can get lat/lon of the center with:
convertPoint:toCoordinateFromView:
loc1 and loc2 are both CLLocation objs.
CLLocationDistance dist = [loc1 distanceFromLocation:loc2];
So these two tips should help you. if you need some code, let me know :-)
Upvotes: 32