NSString *urlPath=[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false",coordinate1.latitude,coordinate1.longitude,coordinate2.latitude,coordinate2.longitude];
//NSLog(@"the url for searching is : %@",urlPath);
NSURL *url=[NSURL URLWithString:urlPath];
NSData *data=[NSData dataWithContentsOfURL:url];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSNumber *results = [[[[object valueForKey:@"routes"]valueForKey:@"legs"]valueForKey:@"distance"]valueForKey:@"value"];
NSLog(@"Count %@",results);
结果如下:
(
(
12078
)
)
是否可以将数字输出?
答案 0 :(得分:1)
在Google API上查看地图我可以看出,路线包含腿和腿都有距离属性。
{
"status": "OK",
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy@P"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
因此第一条路线第一站的距离应为:
NSNumber *distance = object[@"routes"][0][@"legs"][0][@"distance"][@"value"];
答案 1 :(得分:0)
请勿将其另存为NSNumber
,因为它是字符串值。
使用NSNumberFormatter
将NSString
保存为NSNumber
。
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *results = [f numberFromString:[[[[object valueForKey:@"routes"] valueForKey:@"legs"] valueForKey:@"distance"] valueForKey:@"value"]];
答案 2 :(得分:0)
NSString *urlPath = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=12.9715,77.045&destination=12.7152,77.888&sensor=false"];
//NSLog(@"the url for searching is : %@", urlPath);
NSURL *url = [NSURL URLWithString:urlPath];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *results = [[[[object valueForKey:@"routes"] valueForKey:@"legs"] valueForKey:@"distance"] valueForKey:@"value"];
NSLog(@"Count %@", results);
NSLog(@"Count %@", results[0][0]);