我正在尝试在基于View的应用程序中部署以下代码,但在尝试运行时遇到以下错误:
GPSViewController.h
CLLocationManager *lm;
CLLocation *firstLocation;
CLLocation *secondLocation;
CLLocationDistance *distance;
NSString *distanceString;
GPSViewController.m
firstLocation = [[[CLLocation alloc] initWithLatitude:lat1 longitude:lon1] autorelease];
secondLocation = [[[CLLocation alloc] initWithLatitude:lat2 longitude:lon2] autorelease];
distance = [secondLocation distanceFromLocation:firstLocation]; //CLLocation may not respond to distanceFromLocation
double dist = distance / 1000; //invalid operands to binary
distanceString = [[NSString alloc] stringWithFormat: @"%f", dist];
NSLog(@"the distance between the two points is: %@", distanceString);
在上面的示例代码中,如何将变量“distance”从“CLLocationDistance”类型转换为“double”类型?
我只是尝试使用两个不同的CLLocation对象计算两点之间的距离,然后将其打印到控制台。 lat1,lon1,lat2,lon2是双打。
谁能看到我哪里出错了?
答案 0 :(得分:2)
CLLocationDistance是一个双精度数,因此您无需尝试转换为double或其他任何内容。
你可以像这样计算你的数据,它会起作用:
CLLocationDistance distance = [secondLocation distanceFromLocation:firstLocation]; // distance is expressed in meters
CLLocationDistance kilometers = distance / 1000.0;
NSString *distanceString = [[NSString alloc] initWithFormat: @"%f", kilometers];