Skip to content

Instantly share code, notes, and snippets.

@taylanpince
Created March 5, 2010 14:48
Show Gist options
  • Save taylanpince/322765 to your computer and use it in GitHub Desktop.
Save taylanpince/322765 to your computer and use it in GitHub Desktop.
from lxml import etree
OSM_API_URL = "http://api.openstreetmap.org/api/0.6/map?bbox=%s"
def get_streets(bbox):
"""
Makes an OSM API request and parses the streets and their waypoints in the
XML response, returns a list
"""
tree = etree.parse(OSM_API_URL % bbox)
streets = []
for way in tree.xpath("//way"):
waypoints = []
for node in way.getchildren():
if node.tag == "nd":
point = tree.xpath("//node[@id=%s]" % node.attrib.get("ref"))[0]
waypoints.append((point.attrib.get("lat"), point.attrib.get("lon")))
streets.append(waypoints)
return streets
NSArray *PerformWayQuery(NSData *document) {
xmlDocPtr doc;
doc = xmlReadMemory([document bytes], [document length], "", NULL, XML_PARSE_RECOVER);
if (doc == NULL) {
NSLog(@"Unable to parse.");
return nil;
}
NSMutableArray *ways = [[NSMutableArray alloc] init];
NSArray *waysList = PerformXPathQuery(doc, @"//way");
int count = 0;
for (NSDictionary *way in waysList) {
if (count > 50) {
break;
}
NSMutableArray *coordinates = [[NSMutableArray alloc] init];
for (NSDictionary *node in [way objectForKey:@"nodeChildArray"]) {
if ([[node objectForKey:@"nodeName"] isEqualToString:@"nd"]) {
NSArray *nodeCoordinates = PerformXPathQuery(doc, [NSString stringWithFormat:@"//node[@id=%@]", [[[node objectForKey:@"nodeAttributeArray"] objectAtIndex:0] objectForKey:@"nodeContent"]]);
CLLocationCoordinate2D coordinate;
for (NSDictionary *attribute in [[nodeCoordinates objectAtIndex:0] objectForKey:@"nodeAttributeArray"]) {
if ([[attribute objectForKey:@"attributeName"] isEqualToString:@"lat"]) {
coordinate.latitude = [[attribute objectForKey:@"nodeContent"] doubleValue];
} else if ([[attribute objectForKey:@"attributeName"] isEqualToString:@"lon"]) {
coordinate.longitude = [[attribute objectForKey:@"nodeContent"] doubleValue];
}
}
CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
[coordinates addObject:location];
[location release];
}
}
Street *street = [[Street alloc] initWithDictionary:[NSDictionary dictionaryWithObject:coordinates forKey:@"coordinates"]];
[ways addObject:street];
[street release];
[coordinates release];
count++;
}
xmlFreeDoc(doc);
return ways;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment