使用mapkit确定距离

use*_*949 5 iphone cocoa-touch mapkit

如何使用mapkit确定1000英尺或1/2英里的距离?来自某个引脚的半径或两个引脚之间的距离.

例如,我将地图集中在引脚A上.引脚B,C和D也位于地图上,距离引脚A的距离不同.B和C距离A不到1/2英里,但D距离1英里.我想知道B和C距离A不到1/2英里.我怎么能算出来?

Arc*_*ite 13

既然你已经说过两个不同的点是"引脚",我将假设你正在使用MKPinAnnotationView(或其他一些注释视图).如果没有,你将不得不以其他方式获得该位置.

如果您有指向这些位置的注释对象的指针,则可以轻松调用-coordinate它们,从这些坐标创建CLLocations(使用-initWithLatitude:longitude:),然后使用该方法-getDistanceFrom检索以米为单位的距离.从那里,它很容易转换为英里.总而言之,代码看起来像这样:

CLLocationCoordinate2D pointACoordinate = [pointAAnnotation coordinate];
CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.longitude];
CLLocationCoordinate2D pointBCoordinate = [pointBAnnotation coordinate];
CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:pointBCoordinate.latitude longitude:pointBCoordinate.longitude];
double distanceMeters = [pointALocation getDistanceFrom:pointBLocation];
double distanceMiles = (distanceMeters / 1609.344);
Run Code Online (Sandbox Code Playgroud)

你将以英里为距离结束,并可以从那里进行比较.希望这可以帮助.


con*_*fin 12

getDistanceFrom 现在已被弃用,所以对于任何想要这样做的人来说,这是另一种选择.

CLLocationCoordinate2D pointACoordinate = [pointAAnnotation coordinate];
CLLocation *pointALocation = [[CLLocation alloc] initWithLatitude:pointACoordinate.latitude longitude:pointACoordinate.longitude];  

CLLocationCoordinate2D pointBCoordinate = [pointBAnnotation coordinate];
CLLocation *pointBLocation = [[CLLocation alloc] initWithLatitude:pointBCoordinate.latitude longitude:pointBCoordinate.longitude];  

float distanceMeters = [pointALocation distanceFromLocation:pointBLocation];
float distanceMiles = (distanceMeters / 1609.344);  

[pointALocation release];
[pointBLocation release];  
Run Code Online (Sandbox Code Playgroud)

如上所述,您可以使用float而不是,double如果您不需要float类似的精度,您可以将结果转换为int :

int distanceCastToInt = (int) [pointALocation distanceFromLocation:pointBLocation];
Run Code Online (Sandbox Code Playgroud)

int,如果你想给远方的一个粗略的想法,像这样的注解是很方便的:

pointAAnnotation.title = @"Point A";
pointAAnnotation.subtitle = [NSString stringWithFormat: @"Distance: %im",distanceCastToInt];
Run Code Online (Sandbox Code Playgroud)

例如,注释的副标题为"距离:50米".