简体   繁体   English

计算坐标数组的距离

[英]Calculate distance from array of coordinates

Currently I can calculate the distance between two coordinates which are NSString s. 目前我可以计算两个坐标之间的距离,即NSString s。

I am now trying to calculate a list of coordinates which are in a NSMutableArray but I'm stuck. 我现在正在尝试计算一个NSMutableArray中的坐标列表但是我被卡住了。
I somehow need to calculate the distance between all loc or is there a better way of doing this? 我不知何故需要计算所有loc之间的距离,或者有更好的方法吗?

for (int i=0; i < self.trackArray.count; i++)
{
    CGFloat latitude  = [[self.trackArray objectAtIndex:0] doubleValue];
    CGFloat longitude = [[self.trackArray objectAtIndex:1] doubleValue];

    CLLocation *loc = [[CLLocation alloc]  initWithLatitude:latitude longitude:longitude];

    CLLocationDistance distance = [loc distanceFromLocation:loc];
    CLLocationDistance kilometers = distance / 1000.0;
    self.distanceString = [NSString stringWithFormat:@"%f", kilometers];
}

Update. 更新。 An example of how the array looks from the NSLog. 数组如何从NSLog查看的示例。

(
"37.335009,-122.032722",
"37.334977,-122.032813",
"37.334948,-122.032921",
"37.334922,-122.033042",
"37.334892,-122.033184",
"37.334858,-122.033344",
"37.334821,-122.033509",
"37.334780,-122.033696"
)

Sorry for not making it clear what Im trying to do, I have an app that tracks a users location and draws a line behind them, above are coordinates that were tracked from the user, I want to find the distance travelled, currently the calculated distance is as the crow fly's which is the first line of the coordinates and the last line. 很抱歉没有说明我想要做什么,我有一个应用程序跟踪用户位置并在它们后面画一条线,上面是从用户跟踪的坐标,我想找到行进的距离,当前计算的距离就像乌鸦飞行一样,它是坐标的第一行和最后一行。 I want to eg calculate the distance between the first 2 lines of coordinates then add that distance to the next 2 lines of coordinates etc. So if the user walks in a circle I want to know the distance. 我想例如计算前2行坐标之间的距离,然后将该距离添加到接下来的2行坐标等。因此,如果用户走进一个圆圈,我想知道距离。

Try this: 尝试这个:

-(void) test {
  CLLocationDistance totalKilometers = 0;
  for (int i = 0; i < (self.trackArray.count - 1); i++) // <-- count - 1
  {
     CLLocation *loc1 = [self cLLocationFromString:[self.trackArray objectAtIndex:i]];
     CLLocation *loc2 = [self cLLocationFromString:[self.trackArray objectAtIndex:(i + 1)]];

     CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
     CLLocationDistance kilometers = distance / 1000.0;
     totalKilometers += kilometers;
  }
  self.distanceString = [NSString stringWithFormat:@"%f", totalKilometers];
}

-(CLLocation*) cLLocationFromString:(NSString*)string
{
    NSArray *coordinates = [string componentsSeparatedByString:@","];
    CGFloat latitude  = [[coordinates objectAtIndex:0] doubleValue];
    CGFloat longitude = [[coordinates objectAtIndex:1] doubleValue];
    return [[CLLocation alloc]  initWithLatitude:latitude longitude:longitude];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM