def test_merge_write(self): osm2 = pyosm.OSMXMLFile(filename='osmfiles/josm_download.osm') log.info('osm2 stat befor merge') osm2.statistic() osm2.merge(self.osm) log.info('osm2 stat after merge') osm2.statistic() osm2.write('testoutput/result_merge_write.osm')
def test_geometry(self): log.info('geometry tests:') w = list(self.osm.ways.values())[0] # get first way log.info(' distance way0: %f' % w.distance()) log.info(' bbox way0: %s' % str(w.bbox())) r = list(self.osm.relations.values())[0] # get first relation log.info(' distance rel0: %f' % r.distance()) log.info(' bbox rel0: %s' % str(r.bbox())) germany = pyosm.OSMXMLFile('osmfiles/germany_borders.osm') rb = germany.relations[1111111] log.info(' border bbox %s' % str(rb.bbox())) log.info(' border bbox %s' % str(rb.bbox(recursive=True))) log.info(' border length %f' % rb.distance()) log.info(' border length recursive %f' % rb.distance(recursive=True)) log.info(' border length recursive %f' % rb.distance(recursive=True, roles=['outer', '']))
def setUp(self): self.osm_file = 'osmfiles/multipolygon1.osm' self.osm = pyosm.OSMXMLFile(self.osm_file)
#!/usr/bin/python # Program created by Peter Chin, May, 2014. [email protected], Open Source license pending import sys import os sys.path.append('ENTER folder location for pyosm.py and geocoder.py here. e.g. /home/peter/osmnodes/lib/ or in Windows... C:\\osmnodes\\lib') import pyosm from geocoder import geocode_node osm = pyosm.OSMXMLFile('ENTER location of your .osm data file here. e.g. /home/peter/osmnodes/new-york-small.osm, or in Windows... C:\\osmnodes\\new-york-small.osm') import re def distance_nodes(x1,y1,x2,y2): return ((x2-x1)**2+(y2-y1)**2)**0.5 def nearest_node_tagged(nodeID, qry): try: #arbitrarily large starting distance for comparison nearestDist = 100000000 for node in osm.nodes: match = re.search('\''+qry+'(.*)', str(osm.nodes[node].tags)) newDist = distance_nodes(osm.nodes[nodeID]['lon'], osm.nodes[nodeID]['lat'], osm.nodes[node]['lon'], osm.nodes[node]['lat']) if match and newDist < nearestDist and node != nodeID: nearestDist = newDist nearestNode = node nearestTag = match.group(1) print '\n Your starting node is http://www.openstreetmap.org/node/'+str(nodeID) print '\n Nearest tagged node for your query is http://www.openstreetmap.org/node/'+str(nearestNode) print '\n Nearest node\'s tagged info is:'+str(nearestTag) except: e = sys.exc_info()[0] l = sys.exc_traceback.tb_lineno print 'The following error ocurred: ', e, l
def convert(self): self.logger.info("Converting %s" % self.delta) osm = pyosm.OSMXMLFile(self.delta) #check relations for relations of type "associatedStreet" and build dict self.relationMembers = {} for relation in osm.relations.values(): if len(relation.tags) > 0: #print relation.tags if "type" in relation.tags: if relation.tags["type"] == "associatedStreet": try: name = relation.tags["name"] #print "got associatedStreet %s" % name except: print "no name for associatedStreet" for mem in relation.members: #print mem[0].id self.relationMembers[mem[0].id] = name for node in osm.nodes.values(): rec = OARecord() rec.osmid = node.id try: pt = asPoint([float(node.lon), float(node.lat)]) rec.wkt = pt.wkt except: continue hasRelation = False hasTag = False if len(node.tags) == 0: continue if "addr:housenumber" in node.tags: rec.housenum = node.tags["addr:housenumber"].encode( 'utf-8', 'ignore') hasTag = True if "addr:street" in node.tags: try: rec.street = node.tags["addr:street"].encode( 'utf-8', 'ignore') hasTag = True except: print node.tags self.logger.error("error") raise Exception("ERROR GETTING STREETNAME") if "addr:city" in node.tags: rec.city = node.tags["addr:city"].encode('utf-8', 'ignore') hasTag = True if "addr:country" in node.tags: rec.country = node.tags["addr:country"].encode( 'utf-8', 'ignore') hasTag = True #if we got a streetname in a relation, it has the priority if int(node.id) in self.relationMembers.keys(): #print "node in relation" #if len(rec.street)>0: # print rec.street +" vs "+ self.relationMembers[node.id].encode('utf-8','ignore') rec.street = self.relationMembers[node.id].encode( 'utf-8', 'ignore') hasTag = True if hasTag: self.rows.append(rec) for way in osm.ways.values(): rec = OARecord() rec.osmid = way.id # rec.lon=way.lon # rec.lat=way.lat ##use shapely to create polygon and get centroid coords = [] for node in way.nodes: coord = [] try: coord.append(float(node.lon)) coord.append(float(node.lat)) coords.append(coord) except: continue if len(coords) > 3: pg = asPolygon(coords) pt = pg.centroid elif len(coords) > 1: pl = asLineString(coords) pt = pl.centroid elif len(coords) == 1: pt = asPoint(coords) else: continue rec.wkt = pt.wkt hasTag = False if "addr:housenumber" in way.tags: rec.housenum = way.tags["addr:housenumber"].encode( 'UTF-8', 'ignore') hasTag = True if "addr:street" in way.tags: try: rec.street = way.tags["addr:street"].encode( 'utf-8', 'ignore') hasTag = True except: print way.tags self.logger.error("error") raise Exception("ERROR GETTING STREETNAME") if "addr:city" in way.tags: rec.city = way.tags["addr:city"].encode('UTF-8', 'ignore') hasTag = True if "addr:country" in way.tags: rec.country = way.tags["addr:country"].encode( 'UTF-8', 'ignore') hasTag = True #if we got a streetname in a relation, it has the priority if way.id in self.relationMembers.keys(): #print "way in relation" if len(rec.street) > 0: print rec.street + " vs " + self.relationMembers[ way.id].encode('utf-8', 'ignore') rec.street = self.relationMembers[way.id].encode( 'utf-8', 'ignore') #print rec.street hasTag = True if hasTag: self.rows.append(rec) #TODO os.remove(self.delta) return self.rows
#!/usr/bin/python import sys, filelocations import logging log = logging.getLogger("pyosm") sys.path.append(filelocations.LIB_LOCATION) import argparse import pyosm from geocoder import * from pyosm import OSMXMLFile OSML = OSMXMLFile() osm = pyosm.OSMXMLFile(filelocations.OSM_DATA_LOCATION) from matplotlib import pyplot as plt import networkx as nx def error_info(): e = sys.exc_info()[0] l = sys.exc_traceback.tb_lineno print 'The following error ocurred: ', e, l if 'exceptions.KeyError' in str(e): print 'You entered a value that was not found in the map.' elif 'exceptions.UnboundLocalError' in str(e): print 'You entered a value that was not found in the map.' elif 'sre_constants.error' in str(e): print 'You entered invalid symbols such as [ and ]' """Lets the user enter simple search key words, e.g. user enters 'cafe' and data becomes the OSM tag value 'amenity\': u\'cafe' for processing"""
import urllib try: opts, args = getopt.getopt(sys.argv[1:], 'o:r', ['outfile=', 'relations']) except getopt.GetoptError: usage() sys.exit() outfile='out.gpx' mode = None for o, a in opts: if o in ['-o', '--outfile']: outfile = a elif o in ['-r', 'relations']: mode = 'relations' if mode == 'relations': API='http://www.openstreetmap.org/api/0.6' gpx_exp = osm_gpx_exporter(outfile) for relid in args: osmfile = urllib.urlopen('%s/relation/%s/full' %(API,relid)) osmobj = pyosm.OSMXMLFile(osmfile) gpx_exp.append_relations(osmobj.relations.values()) gpx_exp.write()
#!/usr/bin/python import sys, os PYOSM_DIR = os.path.join(os.path.dirname(__file__), '../src/osm/') sys.path.append(PYOSM_DIR) import pyosm import multipolygon osm = pyosm.OSMXMLFile('xx.osm') osm2 = pyosm.OSMXMLFile('../../../Grenzen/Bodenseekreis.osm') osm.statistic() r = osm.relations.values()[6] print '\nSingle relation representation\n', r w = osm.ways.values()[-1] print '\nSingle way representation\n', w n = osm.nodes.values()[1] print '\n', n print '\nNodes of a Way:\n', w.nodes print '\nNodeids of a Way:\n', w.nodeids print '\nMember Data of a Relation:\n', r.member_data print '\nMembers of a Relation:\n', r.members print '\nmerge 2 osm files and print statistic:' osm.merge(osm2) osm.statistic() osm.write('xx_writetest.osm')