示例#1
0
def parseAll(pfad, bildpfad = None, substractMin=True, minimumHeight = 0.0, maximumHeight = 100.0, curveRadius=8):
    global topoParameter
    setHeights(minimumHeight, maximumHeight)
    topoParameter = convertTopoMap(bildpfad, pfad)
    minLongitude = -1
    maxLongitude = 9
    minLatitude = -1
    maxLatitude = 55
    #create rNodedict with counter
    for entity in parse_file(pfad):
        if isinstance(entity, Node):
            #if minLongitude <entity.lon< maxLongitude and minLatitude <entity.lat< maxLatitude:   # approximate longitude and latitude of Wuppertal
                 rNode(entity, substractMin=topoParameter)
    #create streetrNodedict and count rNodeuse
    for entity in parse_file(pfad):
        if isinstance(entity, Way):
            for word in ["highway"]:#, "lanes", "oneway", "cycleway", "foot", "sidewalk",  "footway"]:
                if word in entity.tags and not "stairs" in entity.tags["highway"] and not "steps" in entity.tags["highway"] and not  "pedestrian" in entity.tags["highway"] and not "elevator" in entity.tags["highway"] and not "footway" in entity.tags["highway"] and not "bridleway" in entity.tags["highway"] and not "cycleway" in entity.tags["highway"] and not "path" in entity.tags["highway"]:
                    OSMPreWay(entity)
    for preWay in OSMPreWay.allWays.values():
        preWay._evaluate()
    for node in rNode.allrNodes.values():
        for way in node.incomingWays:
            node.createConnections(way)
        for way in node.outgoingWays:
            node.createConnections(way)
    for node in rNode.allrNodes.values():
        node.createOpenDriveElements(r=curveRadius)
        node.createOpenDriveLanesAndInternalRoadConnections() 
    for node in rNode.allrNodes.values():
        node.connectOpenDriveLanes()
示例#2
0
def parseAll(pfad):
    minLongitude = -1
    maxLongitude = 9
    minLatitude = -1
    maxLatitude = 55
    #create Nodedict with counter
    for entity in parse_file(pfad):
        if isinstance(entity, Node):
            if minLongitude < entity.lon < maxLongitude and minLatitude < entity.lat < maxLatitude:  # approximate longitude and latitude of Wuppertal
                OSMNode(entity)
    #create streetnodedict and count nodeuse
    for entity in parse_file(pfad):
        if isinstance(entity, Way):
            for word in [
                    "highway"
            ]:  #, "lanes", "oneway", "cycleway", "foot", "sidewalk",  "footway"]:
                if word in entity.tags and not "stairs" in entity.tags[
                        "highway"] and not "steps" in entity.tags[
                            "highway"] and not "pedestrian" in entity.tags[
                                "highway"] and not "elevator" in entity.tags[
                                    "highway"] and not "footway" in entity.tags[
                                        "highway"] and not "bridleway" in entity.tags[
                                            "highway"] and not "cycleway" in entity.tags[
                                                "highway"] and not "path" in entity.tags[
                                                    "highway"]:
                    OSMPreWay(entity)
    for preWay in OSMPreWay.allWays.values():
        preWay._evaluate()
    for node in OSMNode.allOSMNodes.values():
        node._evaluate()
def load_osm(filename):
    parsed = parse_file(filename)

    print("Parsed File")

    ways = {}
    nodes = {}
    relation = {}

    min_lat, max_lat, min_lon, max_lon = 360, 0, 90, -90

    for entity in parsed:
        if isinstance(entity, Way):
            ways[entity.id] = entity
        elif isinstance(entity, Node):
            nodes[entity.id] = entity
            min_lat = min(min_lat, entity.lat)
            max_lat = max(max_lat, entity.lat)
            min_lon = min(min_lon, entity.lon)
            max_lon = max(max_lon, entity.lon)

        elif isinstance(entity, Relation):
            relation[entity.id] = entity
        else:
            print("Unknown entity: " + str(type(entity)))

    highways = {}
    for id, way in ways.items():
        if "highway" in way.tags:
            highways[id] = way

    return highways, nodes, (min_lat, max_lat, min_lon, max_lon)
示例#4
0
def create_walk_network_from_osm(osm_file):
    walk_network = networkx.Graph()
    assert (os.path.exists(osm_file))
    ways = []
    for i, entity in enumerate(parse_file(osm_file)):
        if isinstance(entity, Node):
            walk_network.add_node(entity.id, lat=entity.lat, lon=entity.lon)
        elif isinstance(entity, Way):
            if "highway" in entity.tags:
                if entity.tags["highway"] in OSM_HIGHWAY_WALK_TAGS:
                    ways.append(entity)
    for way in ways:
        walk_network.add_path(way.nodes)
    del ways

    # Remove all singleton nodes (note that taking the giant component does not necessarily provide proper results.
    for node, degree in walk_network.degree().items():
        if degree is 0:
            walk_network.remove_node(node)

    node_lats = networkx.get_node_attributes(walk_network, 'lat')
    node_lons = networkx.get_node_attributes(walk_network, 'lon')
    for source, dest, data in walk_network.edges(data=True):
        data["distance"] = wgs84_distance(node_lats[source], node_lons[source],
                                          node_lats[dest], node_lons[dest])
    return walk_network
示例#5
0
def convert_osmtogeojson(filename):
    _get_all_coordinates(filename)

    feature_collection = []

    for item in parse_file(filename):  # generator!!
        if isinstance(item, Node) and item.tags != {}:
            point = Point(dict_of_coords[item.id])
            feature = Feature(geometry=point, id=item.id, properties=item.tags)
            feature_collection.append(feature)
        elif isinstance(item, Way) and 'highway' in item.tags:
            coords = _get_coords_of_edge(item.nodes)
            line_string = LineString(coords)
            feature = Feature(geometry=line_string,
                              id=item.id,
                              properties=item.tags)
            feature_collection.append(feature)

        print_info("\rParsing features - feature count: {:,}".format(
            len(feature_collection)).replace(",", " "),
                   end='')
    print("")

    geojson_file = FeatureCollection(feature_collection)

    # with open('data/output.geojson', 'w') as outfile:
    #     geojson.dump(geojson_file, outfile)
    # outfile.close()
    return geojson_file
示例#6
0
 def read_osm(self):
     print 'begin reading osm', datetime.datetime.now()
     osm_objs = {Node: [], Way: [], Relation: []}
     for obj in parse_file(self.osm_path):
         osm_objs[type(obj)].append(obj)
     print 'finish reading osm', datetime.datetime.now()
     return osm_objs
示例#7
0
def decode_node_to_csv():
    for entry in parse_file('./data/denmark-latest.osm'):
        if (isinstance(entry, Node) and 'addr:street' in entry.tags
                and 'addr:postcode' in entry.tags
                and 'addr:housenumber' in entry.tags):

            yield entry
示例#8
0
def create_map_from_xml(fn, include_footways=False, include_parking=False):
    """Create an InMemMap from an OpenStreetMap XML file.

    Used for testing routes on OpenStreetMap.
    """
    from ..map.inmem import InMemMap
    map_con = InMemMap("map", use_latlon=True)
    cnt = 0
    ways_filter = ['bridleway', 'bus_guideway', 'track']
    if not include_footways:
        ways_filter += ['footway', 'cycleway', 'path']
    parking_filter = ['driveway']
    if not include_parking:
        parking_filter += ['parking_aisle']
    for entity in osmread.parse_file(str(fn)):
        if isinstance(entity, osmread.Way):
            tags = entity.tags
            if 'highway' in tags \
                and not (tags['highway'] in ways_filter) \
                and not ('access' in tags and tags['access'] == 'private') \
                and not ('landuse' in tags and tags['landuse'] == 'square') \
                and not ('amenity' in tags and tags['amenity'] == 'parking') \
                and not ('service' in tags and tags['service'] in parking_filter) \
                and not ('area' in tags and tags['area'] == 'yes'):
                for node_a, node_b in zip(entity.nodes, entity.nodes[1:]):
                    map_con.add_edge(node_a, node_b)
                    # Some roads are one-way. We'll add both directions.
                    map_con.add_edge(node_b, node_a)
        if isinstance(entity, osmread.Node):
            map_con.add_node(entity.id, (entity.lat, entity.lon))
    map_con.purge()
    return map_con
def get_footways():
  footways = []
  for entity in parse_file("map.osm"):
    if isinstance(entity, Way):
      if 'footway' in entity.tags:
        footways.append(entity)
  return footways
示例#10
0
def load():
    num_links = 0
    for entity in parse_file('novi_sad.osm.pbf'):
        if isinstance(entity, Node):
            node_dict[entity.id] = entity
        elif isinstance(
                entity, Way
        ) and 'highway' in entity.tags:  # and entity.tags['highway'] in ALLOWED_ROADS:
            highway_type = entity.tags['highway']
            typs[highway_type] = typs.get(highway_type, 0) + 1
            if highway_type not in ALLOWED_ROADS:
                continue
            if 'access' in entity.tags and entity.tags['access'] != 'yes':
                continue
            important_ways.append(entity)
            nodes.update(set(entity.nodes))
            for i, cur in enumerate(entity.nodes[1:]):
                prev = entity.nodes[i]
                node_neighbors[prev].append((cur, entity))
                if 'oneway' not in entity.tags or entity.tags['oneway'] == 'no':
                    node_neighbors[cur].append((prev, entity))
                num_links += 1

    for k, i in sorted(typs.items(), key=lambda x: -x[1]):
        print(i, k)

    print('nodes:', len(nodes))
    print('links:', num_links)
示例#11
0
def main(argv=sys.argv):
    argparser = ArgumentParser()

    argparser.add_argument('filename', type=str)

    argparser.add_argument('-f', dest='format', metavar='format', type=str,
        help='file format: xml or pbf')
    argparser.add_argument('-c', dest='compression', metavar='compression', type=str,
        help='override compression autodetection: bz2')
    argparser.add_argument('-d', dest='dump', action='store_true',
        help='dump elements to stdout (debug)')

    args = argparser.parse_args(argv[1:])

    element_count, node_count, way_count, relation_count = 0, 0, 0, 0
    for e in parse_file(args.filename):
        element_count += 1

        if isinstance(e, Node):
            node_count += 1

        elif isinstance(e, Way):
            way_count += 1

        elif isinstance(e, Relation):
            relation_count += 1

        if args.dump:
            print repr(e)

    print "%d elements read (nodes=%d, ways=%d, relations=%d)" % (element_count, node_count, way_count, relation_count)
示例#12
0
def process_osm_file(osm_file_path, limit):
    """Process OSM file, converting to a list of dict.

    Keyword arguments:
    osm_file_path          --  str path of the OSM file
    limit                  --  number of records to store

    Returns:
    entities_list          --  list of dict
    """
    entities_list = list()
    osm_file = parse_file(osm_file_path)
    for i, entity in enumerate(osm_file):
        print '|'.join([str(i), str(len(entities_list))])
        try:
            if len(entity.tags) > 0 and entity.lat and entity.lon:
                loc = ','.join([str(entity.lat), str(entity.lon)])

                entities = dict()

                response = list()
                indexable = set()

                if 'name' in entity.tags:
                    response.append(entity.tags['name'])

                if 'addr:housenumber' in entity.tags:
                    response.append(entity.tags['addr:housenumber'])

                if 'addr:street' in entity.tags:
                    response.append(entity.tags['addr:street'])

                if 'addr:city' in entity.tags:
                    response.append(entity.tags['addr:city'])

                if 'postal_code' in entity.tags:
                    response.append(entity.tags['postal_code'])

                if len(response) == 0:
                    continue
                response = ','.join(response)
                for key, value in entity.tags.iteritems():
                    indexable.add(value)
                indexable = ' '.join(indexable)

                entities['id'] = len(entities_list) + 1
                entities['fields'] = {}
                entities['fields']['response'] = response
                entities['fields']['indexable'] = indexable
                entities['fields']['location_field'] = loc
                entities['type'] = 'add'

                print entities
                entities_list.append(entities)
        except Exception, e:
            print e
            pass
        if len(entities_list) == limit:
            break
示例#13
0
文件: kd_mp.py 项目: tingyingwu2010/V
    def init(region):
        nodes = []
        for entity in parse_file(
                '/home/pouria/Downloads/osm/{}.osm'.format(region)):
            if isinstance(entity, Node):
                nodes.append([entity.lat, entity.lon])

        return cKDTree(nodes), {}
示例#14
0
def decode_node_to_csv():
    # Dictionary with geo-locations of each address to use as strings
    for entry in parse_file('./data/denmark-latest.osm'):
        if (isinstance(entry, Node) and 'addr:street' in entry.tags
                and 'addr:postcode' in entry.tags
                and 'addr:housenumber' in entry.tags):

            yield entry
示例#15
0
def decode_node_to_csv(filename):
    for entry in parse_file('/data/osm/' + filename):

        if (isinstance(entry, Node) and 'addr:street' in entry.tags
                and 'addr:postcode' in entry.tags
                and 'addr:housenumber' in entry.tags
                and 'addr:city' in entry.tags):
            yield entry
示例#16
0
 def read_osm(self):
     print 'begin reading osm', datetime.datetime.now()
     osm_objs = {'Node': [], 'Way': [], 'Relation': []}
     for obj in parse_file(self.osm_path):
         type_str = self.get_type_str(type(obj))
         osm_objs[type_str].append(obj)
     print 'finish reading osm', datetime.datetime.now()
     return osm_objs
示例#17
0
def _get_all_coordinates(filename):
    for item in parse_file(filename):  # generator!!
        if isinstance(item, Node):
            dict_of_coords[item.id] = (item.lon, item.lat)
            print_info("\rParsing all coordinates - node count: {:,}".format(
                len(dict_of_coords)).replace(",", " "),
                       end='')
    print("")
    def process_map_with_osmread(self, filename):
        """
        Process one map given its filename, using osmread
        """
        # This import is here since user doesn't have to have it (optional)
        from osmread import parse_file

        for raw_entity in parse_file(filename):
            self._entity_found(raw_entity)
示例#19
0
def file_to_map(filename, map_con):
    logger.debug("Parse OSM file ...")
    for entity in osmread.parse_file(str(filename)):
        if isinstance(entity, osmread.Way) and 'highway' in entity.tags:
            for node_a, node_b in zip(entity.nodes, entity.nodes[1:]):
                map_con.add_edge(node_a, node_b)
                # Some roads are one-way. We'll add both directions.
                map_con.add_edge(node_b, node_a)
        if isinstance(entity, osmread.Node):
            map_con.add_node(entity.id, (entity.lat, entity.lon))
    logger.debug("... done")
    logger.debug("Purging database ...")
    map_con.purge()
    logger.debug("... done")
示例#20
0
def create_map_osmread() -> None:
    xml_file = Path("./tests") / "osm.xml"
    map_con = InMemMap("myosm",
                       use_latlon=True,
                       use_rtree=True,
                       index_edges=True)
    for entity in osmread.parse_file(str(xml_file)):
        if isinstance(entity, osmread.Way) and 'highway' in entity.tags:
            for node_a, node_b in zip(entity.nodes, entity.nodes[1:]):
                map_con.add_edge(node_a, node_b)
                # Some roads are one-way. We'll add both directions.
                map_con.add_edge(node_b, node_a)
        if isinstance(entity, osmread.Node):
            map_con.add_node(entity.id, (entity.lat, entity.lon))
    map_con.purge()
示例#21
0
    def get(self):
        file_path = join(dirname(realpath(__file__)),
                         '../files/kansai-latest.osm.pbf')
        # print(file_path)
        shop_count = 0
        for entity in parse_file(file_path):
            if shop_count < 10:
                if isinstance(entity, Node) and 'shop' in entity.tags:
                    shop_count += 1
                    print(entity)
                    # データベースに追加
                    # ~~~~~~
        print(shop_count)

        return jsonify({"message": "OSM"})
示例#22
0
    def import_osm(self, debug=False):
        # Mysql prep
        add_node = ("INSERT INTO node "
                    "(id, lat, lng) "
                    "VALUES (%s, %s, %s)")


        add_edge = ("INSERT INTO edge "
                    "(n1id, n2id, oneway, speed, name, type, distance) "
                    "VALUES (%s, %s, %s, %s, %s, %s, %s)")

        count_nodes = 0
        count_edges = 0

        try:
            for entity in parse_file(self.file_path):

                # Find nodes
                if isinstance(entity, Node):
                    data_node = (str(entity.id), str(entity.lat), str(entity.lon))
                    self.cursor.execute(add_node, data_node)
                    count_nodes += 1
                    if debug: print("Node {} processed.".format(entity.id))

                # Find edges
                if isinstance(entity, Way) and 'highway' in entity.tags:
                    number_of_node_relationships = len(entity.nodes)

                    if number_of_node_relationships > 2:  # Must mean that the road is divided up between multiple nodes
                        for x in range(0, number_of_node_relationships - 1):
                            path = Path(entity, entity.nodes[x], entity.nodes[x + 1])
                            data_edge = (path.start_node, path.end_node, path.oneway, path.speed, path.name, path.type, "0")
                            self.cursor.execute(add_edge, data_edge)
                            count_edges += 1
                            if debug: print("Edge {} processed.".format(path.id))

                    elif number_of_node_relationships == 2:
                        path = Path(entity, entity.nodes[0], entity.nodes[1])
                        data_edge = (path.start_node, path.end_node, path.oneway, path.speed, path.name, path.type, "0")
                        self.cursor.execute(add_edge, data_edge)
                        count_edges += 1
                        if debug: print("Edge {} processed.".format(path.id))

        except mysql.connector.errors.IntegrityError:  # If entity already exists in db then skip
            pass

        self.cnx.commit()
        return "Number of nodes found: {}\nNumber of edges found: {}".format(count_nodes, count_edges)
示例#23
0
def decode_node_to_csv():
    mycount = 0
    postcodes = defaultdict(list)
    for entry in parse_file('./denmark-latest.osm'):
        mycount += 1
        if (isinstance(entry, Node) and 'addr:street' in entry.tags
                and 'addr:postcode' in entry.tags and 'addr:city' in entry.tags
                and 'lat' in entry and 'lon' in entry
                and 'addr:housenumber' in entry.tags):
            address_field = entry.tags['addr:city']
            zip_field = entry.tags['addr:postcode']
            search_address = ' '.join([zip_field, address_field])
            street_field = entry.tags['addr:street']
            houseno_field = entry.tags['addr:housenumber']
            search_street = ' '.join([street_field, houseno_field])
            my_tuple = (search_street, entry.lat, entry.lon)
            postcodes[search_address].append(my_tuple)
        print(mycount)
    return postcodes
示例#24
0
def findNearestBusStop(inputNode):
    """ Returns the nearest bus stop to the input node """

    busStops = []  # Empty list to store nodes representing bus stops

    mapData = osmread.parse_file("trimmed.osm")

    for entity in mapData:
        if isinstance(entity, osmread.Node) and 'highway' in entity.tags:
            if entity.tags["highway"] == "bus_stop":
                busStops.append(entity)

    shortestDistance = 100
    for busStop in busStops:
        distance = getNodeDist(inputNode, busStop)
        if distance < shortestDistance:
            shortestDistance = distance
            closestBusStop = busStop

    return closestBusStop
示例#25
0
def file_converter(osm_file):
    elements = []

    # Extract the nodes and the ways
    for entity in osmread.parse_file(osm_file):
        json_data = {}

        if isinstance(entity, osmread.Node):
            json_data = read_node(entity)

        elif isinstance(entity, osmread.Way):
            json_data = read_way(entity)

        elif isinstance(entity, osmread.Relation):
            json_data = read_relation(entity)

        elements.append(json_data)

    # response_jsons
    return [{'elements': elements}]
示例#26
0
def read_osm(filepath):

    nodes = {}
    ways = []
    # rels = []

    # Extract the nodes and the ways
    for entity in osmread.parse_file(filepath):

        if isinstance(entity, osmread.Node):
            # don't really need anything about the nodes except their lon and lat i don't think
            nodes[entity.id] = (entity.lon, entity.lat)

        elif isinstance(entity,
                        osmread.Way) and (not ways_filter(entity.tags)):

            # convert speed limit from string to int.
            # NOTE: assumes in US/all limits are in MPH
            if 'maxspeed' in entity.tags:
                try:
                    entity.tags['maxspeed'] = int(entity.tags['maxspeed'][:-4])
                except ValueError:
                    try:  # someone probably forgot to put a mph on it
                        entity.tags['maxspeed'] = int(entity.tags['maxspeed'])
                    except ValueError:  # blank maxspeed, probably
                        del entity.tags['maxspeed']

            # treat links like regular roads
            if entity.tags['highway'][-5:] == '_link':
                entity.tags['highway'] = entity.tags['highway'][:-5]

            # ensure consistency on lanes
            entity.tags['lanes'] = int(entity.tags.get('lanes', 0))

            ways.append(entity)

        # elif isinstance(entity, osmread.Relation) and (not rels_filter(entity.tags)):
        #     rels.append(entity) # TBD what to do with this

    # return nodes, ways, rels
    return nodes, ways
示例#27
0
def main(argv=sys.argv):
    argparser = ArgumentParser()

    argparser.add_argument('filename', type=str)

    argparser.add_argument('-f',
                           dest='format',
                           metavar='format',
                           type=str,
                           help='file format: xml or pbf')
    argparser.add_argument('-c',
                           dest='compression',
                           metavar='compression',
                           type=str,
                           help='override compression autodetection: bz2')
    argparser.add_argument('-d',
                           dest='dump',
                           action='store_true',
                           help='dump elements to stdout (debug)')

    args = argparser.parse_args(argv[1:])

    element_count, node_count, way_count, relation_count = 0, 0, 0, 0
    for e in parse_file(args.filename):
        element_count += 1

        if isinstance(e, Node):
            node_count += 1

        elif isinstance(e, Way):
            way_count += 1

        elif isinstance(e, Relation):
            relation_count += 1

        if args.dump:
            print(repr(e))

    print("%d elements read (nodes=%d, ways=%d, relations=%d)" %
          (element_count, node_count, way_count, relation_count))
示例#28
0
def _ways(name):
    try:
        with open(_dir + name + '.pkl', 'rb') as f:
            return pickle.load(f)
    except FileNotFoundError as e:
        __ways = {}
        for entity in parse_file(_dir + name + '.osm'):
            if isinstance(entity, Node):
                __ways[entity.id] = (entity.lat, entity.lon)
            if isinstance(entity, Way) and 'highway' in entity.tags:
                highway = entity.tags['highway']
                speed = int(entity.tags['maxspeed']
                            ) if 'maxspeed' in entity.tags else default.get(
                                highway, 20)
                nodes = entity.nodes
                nodes = [
                    nodes[i * 5:min(i * 5 + 5, len(nodes))]
                    for i in range(math.ceil(len(nodes) / 5))
                ]
                if len(nodes[-1]) == 1:
                    nodes[-2] = list(nodes[-2])
                    nodes[-2].append(nodes[-1][0])
                    nodes = nodes[:-1]
                for points in nodes:
                    __ways[(points[0], points[-1])] = {
                        'highway': highway,
                        'speed': [speed, speed],
                        'nodes': points
                    }
                    if 'oneway' not in entity.tags or entity.tags[
                            'oneway'] == 'no':
                        __ways[(points[-1], points[0])] = {
                            'highway': highway,
                            'speed': [speed, speed],
                            'nodes': tuple(reversed(points))
                        }
        with open(_dir + name + '.pkl', 'wb') as f:
            pickle.dump(__ways, f, pickle.HIGHEST_PROTOCOL)
    return __ways
示例#29
0
    def calculate_osm_stats(self, osm_path):
        """ reads the .osm file and captures certain stats like last update and number of ways, etc... 
        """
        log.info("calculating stats for {}".format(osm_path))
        self.osm_file = osm_path

        for entity in parse_file(osm_path):
            if isinstance(entity, Way):
                self.way_count += 1
                if 'highway' in entity.tags:
                    self.highway_count += 1
                if entity.timestamp > self.last.timestamp:
                    self.last.timestamp = entity.timestamp
                    self.last.id = entity.id
                    if entity.changeset > 0:
                        self.last.changeset = entity.changeset

        self.last.edit_date = date_utils.pretty_date_from_ms(self.last.timestamp * 1000, fmt="%B %d, %Y")
        self.last.file_date = file_utils.file_pretty_date(osm_path, fmt="%B %d, %Y")

        # if available, add the changeset url
        if self.last.changeset > 0:
            self.last.changeset_url = "http://openstreetmap.org/changeset/{}".format(self.last.changeset)
示例#30
0
def getNodesAndEdges():
    # nodes maps {ID:MapNode}
    nodes = dict()

    #edges maps {ID:[Edge....]}
    nodeEdges = dict()

    #edges {ID: Edge}
    edges = dict()

    for entity in parse_file('data/map.osm'):
        if isinstance(entity, Node):
            node = MapNode(entity.id, entity.lat, entity.lon)
            nodes[entity.id] = node
        if isinstance(entity, Way) and 'highway' in entity.tags:
            path = entity.nodes
            edgeID = entity.id
            for i in range(len(path) - 1):
                # dist = Utils.euclid(nodes[path[i]].point, nodes[path[i+1]].point)
                n1ID = path[i]
                n2ID = path[i + 1]
                edge = Edge(int(str(edgeID) + str(i)), nodes[n1ID],
                            nodes[n2ID])
                edges[int(str(edgeID) + str(i))] = edge
                if n1ID in nodeEdges:
                    nodeEdges[n1ID].append(edge)
                else:
                    nodeEdges[n1ID] = [edge]
                if n2ID in nodeEdges:
                    nodeEdges[n2ID].append(edge)
                else:
                    nodeEdges[n2ID] = [edge]
    prunedNodes = dict()
    for nID in nodes.keys():
        if nID in nodeEdges:
            prunedNodes[nID] = nodes[nID]
    return (prunedNodes, nodeEdges, edges)
示例#31
0
from osmread import parse_file, Way

hillcenters = 0
for entity in parse_file('Rutgers Pathways.osm'):
    if isinstance(entity, Way) and 'name' in entity.tags:
        #Now we check what the name of a given Way is to see the way that represents the hill center
        #entity.tags (in this case Way.tags because we are choosing ways) is a dictionary with a 
        # variety of info about the particular way, print out an entity.tags to see all the info
        if entity.tags['name'] == "Hill Center Bldg For The Mathematical Sciences":
           hillcenters += 1

print("%s hill centers found" % hillcenters)
示例#32
0
def getData(location):
    return parse_file(location)
示例#33
0
from osmread import parse_file, Way

highway_count = 0
for entity in parse_file('map_small.osm'):
    if isinstance(entity, Way) and 'highway' in entity.tags:
        highway_count += 1

print(highway_count)
示例#34
0
from osmread import parse_file, Way, Relation, Node
import json
from pprint import pprint



with open('../data/buildings.json') as f:
    data = json.load(f)

#datum of format {u'latitude': u'37.8723', u'name': u'Bancroft Library/University Archives', u'longitude': u'-122.2587'}
for datum in data:
    print(datum['latitude'], datum['longitude'])



build_count = 0
node_count = 0
for entity in parse_file('../data/berkeley_map.osm'):
    if 'building' in entity.tags.keys(): #if a building
        build_count += 1
        #print(entity.tags)
        if isinstance(entity, Node):
            node_count += 1



#print("%d buildings found, %d nodes found" % (build_count, node_count))
示例#35
0
import sys
import json
from osmread import parse_file, Way, Node, Relation

tic = time.clock()

# url = 'http://www.overpass-api.de/api/xapi_meta?*[building=yes][bbox=55.09094238281249,24.931898803604035,55.33538818359375,25.116067121686175]'
# fileOSM = urllib2.urlopen(url)
# with open('buildings.osm','wb') as output:
# 	output.write(fileOSM.read())
vecNodes = {}
geoJson = {}
geoJson['type'] = 'FeatureCollection'
geoJson['crs'] = { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }
geoJson['features'] = []
for entity in parse_file('buildings.osm'):
	if isinstance(entity, Node):
		vecNodes[str(entity.id)] = {'lat':entity.lat,'lng':entity.lon}
	elif isinstance(entity, Way):
		vecPolygon = []
		for node in entity.nodes:
			vecPolygon.append([vecNodes[str(node)]['lng'],vecNodes[str(node)]['lat']])
		dataFeature = {}
		dataFeature['type']='Feature'
		dataFeature['properties']={}
		dataFeature['geometry']={}
		dataFeature['geometry']['type']='Polygon'
		dataFeature['geometry']['coordinates']=[vecPolygon]
		geoJson['features'].append(dataFeature)
with open('data.geojson', 'w') as outfile:
    json.dump(geoJson, outfile)