如何在MkMapView中计算两个点之间的距离?

8
在iPhone应用程序中,如何计算在MKMapView中两个点之间的距离,如下图所示? 第一个点将是mapview中可见地图的中心点。 第二个点将是地图视图可见矩形的任何角落(在这里,例如我已经选取了左上角)。 我想以米为单位计算这段距离。我该如何实现呢? 我的目标是计算MKMapview中可见地图矩形的比率。
3个回答

32

你可以通过以下方式获取中心的纬度/经度:

convertPoint:toCoordinateFromView:

loc1和loc2都是CLLocation对象。

CLLocationDistance dist = [loc1 distanceFromLocation:loc2];

那么这两个提示应该对你有所帮助。如果你需要一些代码,请告诉我:-)


谢谢回复,您能告诉我如何获取角点(第二个点)的经纬度或坐标吗?我已经获取了中心点(第一个点)的坐标。 - ios
这个答案告诉了如何获取MKMapView的角点的纬度/经度。 - progrmr
当我与谷歌进行交叉检查时,发现使用MapKit计算距离不正确。 - Vineesh TP

3

Swift 3+

let distance: CLLocationDistance = location1.distance(from: location2)

2
以下是您可以计算所需距离的方法:
// 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];

7
要让distanceFromLocation函数正常工作,centerCoordinate和cornerCoordinate需要是CLLocation类型。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接