如何从JSON输出中分离纬度和经度值?

我正在尝试两个位置之间的两个绘制路线,为此,我从Google Map API Web服务( JSON输出格式)中获取所有点。 parsingJSON数据和logging点后,我将所有点存储在NSMutableArray 。 每个索引数组都包含这种types的值。

 "<+10.90180969, +76.19167328> +/- 0.00m (speed -1.00 mps / course -1.00) @ 12/04/12 10:18:10 AM India Standard Time", 

现在我想分离经度和纬度值。

 latitude : +10.90180969 longitude : +76.19167328 

如何从数组的每个索引获取这个值?

这里是一个非常粗糙的forms,我想它是一个蛮横的解决scheme

 NSString* str = @"<+10.90180969, +76.19167328> +/- 0.00m (speed -1.00 mps course -1.00) @ 12/04/12 10:18:10 AM India Standard Time"; NSArray* arr = [str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; if ([arr count] > 1) { NSString* coordinateStr = [arr objectAtIndex:1]; NSArray* arrCoordinate = [coordinateStr componentsSeparatedByString:@","]; NSLog(@"%@",arrCoordinate); } 

看看string,它显示你正在打印一个CLLocation对象的描述“ someObject ”,你也可以访问经纬度,如

  CLLocationCoordinate2D location = [someObject coordinate]; NSLog(@" \nLatitude: %.6f \nLongitude: %.6f",location.latitude,location.longitude); 

OutPut将是:纬度:28.621873经度:77.388897

但是这不会给你的符号,即“+”或“ – ”

希望能帮助到你。

这只是一个方法来做到这一点:

 NSString* str = @"<+10.90180969, +76.19167328> +/- 0.00m (speed -1.00 mps / course -1.00) @ 12/04/12 10:18:10 AM India Standard Time";//you already have this string. str = (NSString*)[[str componentsSeparatedByString:@">"] objectAtIndex:0]; // after above performed step, str equals "<+10.90180969, +76.19167328" str = [str substringFromIndex:1]; // after above performed step, str equals "+10.90180969, +76.19167328" NSString* strLat = (NSString*)[[str componentsSeparatedByString:@","] objectAtIndex:0]; NSString* strLon = (NSString*)[[str componentsSeparatedByString:@","] objectAtIndex:1]; // after above performed step, strLat equals "+10.90180969" // after above performed step, strLon equals " +76.19167328" strLon = [strLon substringFromIndex:1];//<-- to remove the extra space at index=0 

这就是我在代码中的做法 – 试图去适应你的情况:

头文件:

 @interface CLLocation (String) + (instancetype) clLocationWithString:(NSString *)location; @end 

并执行:

 @implementation CLLocation (String) + (instancetype)clLocationWithString:(NSString *)location { static NSRegularExpression *staticRegex; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSError *error = NULL; //ex: <41.081445,-81.519005> ... staticRegex = [NSRegularExpression regularExpressionWithPattern:@"(\\-?\\d+\\.?\\d*)+" options:NSRegularExpressionCaseInsensitive error:&error]; }); NSArray *matches = [staticRegex matchesInString:location options:NSMatchingReportCompletion range:NSMakeRange(0, location.length)]; if (matches.count >= 2) { return [[CLLocation alloc] initWithLatitude:[[location substringWithRange:((NSTextCheckingResult *)[matches objectAtIndex:0]).range] doubleValue] longitude:[[location substringWithRange:((NSTextCheckingResult *)[matches objectAtIndex:1]).range] doubleValue]]; } else { return [[CLLocation alloc] init]; } }