8

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

enter image description here

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.

ali_m
  • 71,714
  • 23
  • 223
  • 298
ios
  • 6,134
  • 20
  • 71
  • 103

3 Answers3

32

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

progrmr
  • 75,956
  • 16
  • 112
  • 147
danielreiser
  • 5,292
  • 5
  • 31
  • 43
  • Thanks for reply can u tell me how to get lat-long or coordinate of corner point (2nd point) I could get the coordinate of center point (1st point) – ios Nov 03 '11 at 11:24
  • [This answer](http://stackoverflow.com/questions/2081753/getting-the-bounds-of-an-mkmapview/2082247#2082247) tells how to get the lat/lon of the corner points. – progrmr Nov 03 '11 at 11:58
  • When I cross check with google. find distance using mapKit is not correct. – Vineesh TP Sep 12 '14 at 11:20
3

Swift 3+

let distance: CLLocationDistance = location1.distance(from: location2)
Maverick
  • 3,209
  • 1
  • 34
  • 40
2

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];
Oliver
  • 23,072
  • 33
  • 138
  • 230
  • 7
    centerCoordinate and cornerCoordinate need be of type CLLocation for distanceFromLocation to work – Daniel Oct 31 '13 at 20:04