我知道这已经很晚了,但我会发布我的解决方案,以防有人需要。
首先,我声明了 URL(调用 google maps api 的那个)
#define DST_API @"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=%@&destinations=%@&units=%@&sensor=false"
接下来我创建了一个包含此 URL 的字符串:
NSString *URL = [NSString stringWithFormat:DST_API, source, destination, units];
source、destination 是包含起点和终点的字符串。单位可以是@"imperial" 或@"metric"。
现在我有了 URL,我会得到一个 xml 字符串。为了解析这个,我使用了 TBXML。关于使用哪个 XML Parser 总是存在很大的争论。我使用了TBXML,因为它很简单,而且是fastest。
TBXML *directionsParser = [[TBXML alloc] initWithURL:[NSURL URLWithString:URL]];
// Check if the Overall status is OK
TBXMLElement *root = directionsParser.rootXMLElement;
TBXMLElement *element = [TBXML childElementNamed:@"status" parentElement:root];
NSString *value = [TBXML textForElement:element];
if ([value caseInsensitiveCompare:@"OK"] != NSOrderedSame) {
[directionsParser release];
return result;
}
检查根状态OK后,获取XPath表达式的结果://row/element/distance/value
element = [TBXML childElementNamed:@"row" parentElement:root];
element = [TBXML childElementNamed:@"element" parentElement:element];
element = [TBXML childElementNamed:@"status" parentElement:element];
value = [TBXML textForElement:element];
// Check if the Element status is OK
if ([value caseInsensitiveCompare:@"OK"] != NSOrderedSame) {
[directionsParser release];
return result;
}
element = element->parentElement;
element = [TBXML childElementNamed:@"distance" parentElement:element];
//Note if you want the result as text, replace 'value' with 'text'
element = [TBXML childElementNamed:@"value" parentElement:element];
NSString *result = [TBXML textForElement:element];
[directionsParser release];
//Do what ever you want with result
如果有人想要一个包含路径点的 URL,那么这里就是
#define DIR_API @"http://maps.googleapis.com/maps/api/directions/xml?origin=%@&destination=%@&waypoints=%@&units=%@&sensor=false"
但要使用航路点,正如 Jano 指出的那样,事情的运作方式会有所不同。