Esempio n. 1
0
def test_geometries():

    # geometries_from_bbox - bounding box query to return empty GeoDataFrame
    gdf = ox.geometries_from_bbox(0.009, -0.009, 0.009, -0.009, tags={"building": True})

    # geometries_from_bbox - successful
    north, south, east, west = ox.utils_geo.bbox_from_point(location_point, dist=500)
    tags = {"landuse": True, "building": True, "highway": True}
    gdf = ox.geometries_from_bbox(north, south, east, west, tags=tags)
    fig, ax = ox.plot_footprints(gdf)

    # geometries_from_point - tests multipolygon creation
    gdf = ox.geometries_from_point((48.15, 10.02), tags={"landuse": True}, dist=2000)

    # geometries_from_place - includes test of list of places
    tags = {"amenity": True, "landuse": ["retail", "commercial"], "highway": "bus_stop"}
    gdf = ox.geometries_from_place(place1, tags=tags)
    gdf = ox.geometries_from_place([place1], tags=tags)

    # geometries_from_address - includes testing overpass settings and snapshot from 2019
    ox.settings.overpass_settings = '[out:json][timeout:200][date:"2019-10-28T19:20:00Z"]'
    gdf = ox.geometries_from_address(address, tags=tags)

    # geometries_from_xml - tests error handling of clipped XMLs with incomplete geometry
    gdf = ox.geometries_from_xml("tests/input_data/planet_10.068,48.135_10.071,48.137.osm")

    # test loading a geodataframe from a local .osm xml file
    with bz2.BZ2File("tests/input_data/West-Oakland.osm.bz2") as f:
        handle, temp_filename = tempfile.mkstemp(suffix=".osm")
        os.write(handle, f.read())
        os.close(handle)
    for filename in ("tests/input_data/West-Oakland.osm.bz2", temp_filename):
        gdf = ox.geometries_from_xml(filename)
        assert "Willow Street" in gdf["name"].values
    os.remove(temp_filename)
Esempio n. 2
0
def _download_geometries(place, download_method, tags, crs, distance = 500.0):
    """
    The function downloads certain geometries from OSM, by means of OSMNX functions.
    It returns a GeoDataFrame, that could be empty when no geometries are found, with the provided tags.
    
    Parameters
    ----------
    place: string
        name of cities or areas in OSM: when using "OSMpolygon" please provide the name of a "relation" in OSM as an argument of "place"; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string {"polygon", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data.
    tag: dict 
        the desired OSMN tags
    crs: string
        the coordinate system of the case study area
        
    Returns
    -------
    geometries_gdf: GeoDataFrame
        the resulting GeoDataFrame
    """    
    if download_method == 'distance_from_address': 
        geometries_gdf = ox.geometries_from_address(place, tags = tags, dist = distance)
    elif download_method == 'OSMplace': 
        geometries_gdf = ox.geometries_from_place(place, tags = tags)
    else: 
        geometries_gdf = ox.geometries_from_polygon(place, tags = tags)
    
    geometries_gdf = geometries_gdf.to_crs(crs)
    return geometries_gdf
Esempio n. 3
0
def get_pois(selected_poi):
    """ Returns a GeoDataFrame containing all the POI categories in select_poi.

        This function takes a list of POIs as input and returns a GeoDataFrame containing
        all inputted types. If a POI input is not already existing in the POIs folder, the
        function queries OSM and creates the file in the expected folder."""
    poi_filenames = [poi + '.csv' for poi in selected_poi]
    poi_paths = [
        data_folder / 'POIs' / poi_filename for poi_filename in poi_filenames
    ]
    place = 'Canton de Genève, Switzerland'
    print('get_pois is running')
    for poi, path, filename in zip(selected_poi, poi_paths, poi_filenames):
        if os.path.exists(path):
            print(path, 'File existed')
        else:
            print(path, 'Querying OSM for the missing tag')
            if 'bakery' in filename:
                type_poi = 'shop'
            elif 'tree' in filename:
                type_poi = 'natural'
            else:
                type_poi = 'amenity'
            tags = {type_poi: poi}
            print(tags)
            gdf = ox.geometries_from_place(place, tags)
            gdf.index = gdf.index.map(int)
            gdf['id'] = gdf.index
            if 'element_type' in gdf.columns:
                gdf = gdf[gdf.element_type == 'node']
            gdf['lon'] = gdf.geometry.x
            gdf['lat'] = gdf.geometry.y
            gdf.to_csv(path, index=False)
    df_poi = pd.concat(
        (pd.read_csv(f) for f in poi_paths)).reset_index(drop=True)
    df_poi['category'] = 'Unhealthy'
    if 'natural' in df_poi.columns:
        df_poi.loc[df_poi.natural == 'tree', 'category'] = 'Healthy'
        df_poi.loc[df_poi.natural == 'tree', 'poi_category'] = df_poi.natural
    else:
        df_poi['natural'] = np.NaN
    if 'shop' in df_poi.columns:
        df_poi.loc[(df_poi.shop.isnull() == False),
                   'poi_category'] = df_poi.shop
    else:
        df_poi['shop'] = np.NaN
    if 'amenity' in df_poi.columns:
        df_poi.loc[(df_poi.amenity.isnull() == False),
                   'poi_category'] = df_poi.amenity
    else:
        df_poi['amenity'] = np.NaN

    geometry = [Point(xy) for xy in zip(df_poi.lon, df_poi.lat)]
    crs = 'epsg:4326'
    df_poi = gpd.GeoDataFrame(df_poi, crs=crs, geometry=geometry)
    df_poi = df_poi.to_crs('epsg:2056')
    return df_poi
Esempio n. 4
0
def getOSMFootprints(bbox=[],
                     place='',
                     save=True,
                     fileName='',
                     workDir='tmp',
                     overwrite=False):
    """Function for downloading a building footprints.

    Args:
        place (str): Name of the city or county.
        save (bool): Save file locally.
        fileName (str): Path of the file.

    Returns:
        allFootprints (geopandas dataframe): Footprints
        fileName (str): Path to the footprint file.

    """

    if fileName == '':

        if len(bbox) > 0:
            fileName = Path(
                f'{workDir}/{bbox[0]}_{bbox[1]}_{bbox[2]}_{bbox[3]}_footprints.geojson'
            )
        else:
            fileName = Path(
                f'{workDir}/{place}_footprints_OSM.geojson'.replace(
                    ' ', '_').replace(',', '_'))

    if os.path.exists(fileName) and not overwrite:
        print('{} already exists.'.format(fileName))
        allFootprints = gpd.read_file(fileName)

    else:
        if len(bbox) > 0:
            allFootprints = ox.geometries_from_bbox(
                bbox[0], bbox[2], bbox[3], bbox[1], tags={
                    'building': True
                })  # (north,west,south,east)->(north, south, east, west, tags)
        else:
            allFootprints = ox.geometries_from_place(place,
                                                     tags={'building': True})

        allFootprints = allFootprints[['geometry']]
        allFootprints = allFootprints[allFootprints['geometry'].type ==
                                      'Polygon']

        # save
        if allFootprints.shape[0] < 1:
            print('Didn\'t find footprints for this region.')
        else:
            allFootprints.to_file(fileName, driver='GeoJSON')
            print('Footprint saved at {}'.format(fileName))

    return allFootprints, fileName
def setup_osm(place_name):
    graph = ox.graph_from_place(place_name)
    buildings = ox.geometries_from_place(place_name, tags={'building': True})
    buildings_dict = {}
    for index, row in buildings.iterrows():
        if row['name'] not in buildings_dict:
            buildings_dict[row['name']] = {}
            buildings_dict[row['name']]['x'] = float(
                '-' + str(row['geometry']).split('-')[1].split(' ')[0])
            buildings_dict[row['name']]['y'] = float(
                str(row['geometry']).split('-')[1].split(' ')[1].split(',')[0]
                [:-1])
    return graph, buildings_dict
Esempio n. 6
0
def get_urban_rail_fromOSM(place, download_method, epsg, distance=7000):
    """
    The function downloads and creates a simplified OSMNx graph for a selected area's urban rail network. 
    Afterwards, GeoDataFrames for nodes and edges are created, assigning new nodeID and edgeID identifiers.
        
    Parameters
    ----------
    place: string
        name of cities or areas in OSM: when using "OSMpolygon" please provide the name of a "relation" in OSM as an argument of "place"; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string {"polygon", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data. When 'polygon' the shape to get network data within. coordinates should be in
        unprojected latitude-longitude degrees (EPSG:4326).
    epsg: int
        epsg of the area considered; if None OSMNx is used for the projection
    distance: float
        it is used only if download_method == "distance from address"
        
    Returns
    -------
    nodes_gdf, edges_gdf: Tuple of GeoDataFrames
        the nodes and edges GeoDataFrames
    """

    crs = 'EPSG:' + str(epsg)
    tag = {'railway': True}

    if download_method == 'distance_from_address':
        railways_gdf = ox.geometries_from_address(place,
                                                  tags=tag,
                                                  dist=distance)
    elif download_method == 'OSMplace':
        railways_gdf = ox.geometries_from_place(place, tags=tag)
    else:
        railways_gdf = ox.geometries_from_polygon(place, tags=tag)

    print(railways_gdf.columns)
    railways_gdf = railways_gdf.to_crs(crs)
    to_keep = ["rail", "light_rail", "subway"]
    railways_gdf = railways_gdf[railways_gdf.railway.isin(to_keep)]
    railways_gdf['type'] = railways_gdf['railway']

    railways_gdf['length'] = railways_gdf.geometry.length
    railways_gdf = railways_gdf[[
        "geometry", "length", "name", "type", "bridge", "tunnel"
    ]]
    railways_gdf.reset_index(inplace=True, drop=True)
    railways_gdf['edgeID'] = railways_gdf.index.values.astype(int)
    railways_gdf.index.name = None
    return railways_gdf
Esempio n. 7
0
    def _get_city_data_within_city_limits(self):

        if self.city_dict['cycleways'] is True:
            self.cycleways = self._get_cycleways()
        if self.city_dict['roads'] is True:
            self.roads = ox.graph_from_place(self.city_name,
                                             network_type='drive')
        if self.city_dict['water'] is True:
            self.water = ox.geometries_from_polygon(self.city_area.unary_union,
                                                    tags=self.water_tags)
        if self.city_dict['green'] is True:
            self.green = ox.geometries_from_polygon(self.city_area.unary_union,
                                                    tags=self.green_tags)
        if self.city_dict['buildings'] is True:
            self.buildings = ox.geometries_from_place(self.city_name,
                                                      tags={
                                                          "building": True,
                                                          'landuse':
                                                          'construction'
                                                      })
        if self.city_dict['railways'] is True:
            self.railways = ox.geometries_from_place(self.city_name,
                                                     tags=self.railway_tags)
Esempio n. 8
0
def cityBoundary(locality):                                  
    locality =  locality + ", Australia"
    tags = {"boundary": "administrative"}
    boundaryOSM = ox.geometries_from_place(locality, tags)
    boundary_gdf = gpd.GeoDataFrame(boundaryOSM)
    #extract useful columns
    boundary_gdf = boundary_gdf.iloc[:, 0:10:9]
    #explode multypoligons in polygons 
    boundary_gdf=explode(boundary_gdf)
    #searching for boundaries referring to PA
    query_search ='short_name == "Cairns"'
    city_boundaries = boundary_gdf.query(query_search)
    city_boundaries = city_boundaries.reset_index(drop=True)
    return city_boundaries 
Esempio n. 9
0
    def set_up(self):
        def name(names):
            if not names:
                return ''
            elif isinstance(names, str):
                return names
            else:
                return ' '.join(names)

        tags = {'amenity': "vending_maching", "vending": "parking_tickets"}
        self.vending_machines_gdf = ox.geometries_from_place(self.place, tags)
        G = ox.graph_from_place(self.place, network_type='drive', retain_all = True, simplify=True)
        nearest_edges = ox.get_nearest_edges(G, self.vending_machines_gdf['geometry'].x, self.vending_machines_gdf['geometry'].y , method='balltree')
        self.vending_machines_gdf['street'] = [*map(lambda x: name(G.edges[(x[0], x[1], x[2])].get("name")).lower(), nearest_edges)]
Esempio n. 10
0
def osm_gdf_from_place(query, tags, which_result=None, buffer_dist=None):
    """Create GeoDataFrame of OSM entities within boundaries of geocodable place(s).

    Args:
        query (str | dict | list): Query string(s) or structured dict(s) to geocode.
        tags (dict): Dict of tags used for finding objects in the selected area. Results returned are the union, not intersection of each individual tag. Each result matches at least one given tag. The dict keys should be OSM tags, (e.g., building, landuse, highway, etc) and the dict values should be either True to retrieve all items with the given tag, or a string to get a single tag-value combination, or a list of strings to get multiple values for the given tag. For example, tags = {‘building’: True} would return all building footprints in the area. tags = {‘amenity’:True, ‘landuse’:[‘retail’,’commercial’], ‘highway’:’bus_stop’} would return all amenities, landuse=retail, landuse=commercial, and highway=bus_stop.
        which_result (int, optional): Which geocoding result to use. if None, auto-select the first (Multi)Polygon or raise an error if OSM doesn't return one. to get the top match regardless of geometry type, set which_result=1. Defaults to None.
        buffer_dist (float, optional): Distance to buffer around the place geometry, in meters. Defaults to None.

    Returns:
        GeoDataFrame: A GeoDataFrame of OSM entities.
    """
    check_package("osmnx",
                  "https://osmnx.readthedocs.io/en/stable/#installation")
    import osmnx as ox

    ox.config(use_cache=True, log_console=True)

    gdf = ox.geometries_from_place(query, tags, which_result, buffer_dist)
    return gdf
Esempio n. 11
0
def binsTable(locality):   #call this function in registration if it is made correctly bin_table(municipality)
    locality =  locality + ", Australia"
    tags = {'amenity': 'waste_basket'}
    binsOSM = ox.geometries_from_place(locality, tags)
    bins_gdf = gpd.GeoDataFrame(binsOSM)

    # create the columns of longitude and latitude from the geometry attribute
    bins_gdf['lon'] = bins_gdf['geometry'].x
    bins_gdf['lat'] = bins_gdf['geometry'].y
    # create the columns of datetime and set it
    bins_gdf['date'] = datetime.datetime(2018, 5, 1)
    bins_gdf['buffer'] = None
	

    #adding buffer attribute
    for i, row in bins_gdf.iterrows():
        bins_gdf.loc[i, 'buffer'] = geodesic_point_buffer(bins_gdf.loc[i, 'lat'], bins_gdf.loc[i, 'lon'], 200.0)

    #setup db connection 
    engine = customized_engine()
	
    #import in PostgreSQL
    bins_gdf.to_postgis('bins_temp', engine, if_exists = 'replace', index=False)

    #add data to DB bins table using the temporary table
    conn = get_dbConn()
    cur = conn.cursor()
    cur.execute(
        'INSERT INTO bins (lon,lat,geom,bin_date,buffer) SELECT lon,lat,geometry,date,buffer FROM bins_temp'
    )
    cur.execute(
        'DROP TABLE IF EXISTS bins_temp'
    )
    cur.close()
    conn.commit()
    conn.close()
    
    return
Esempio n. 12
0
def add_edge_nearest_POIs(road_network, region, radius):
    ### POIs ###
    food_amenities = ['pub', 'bar', 'restaurant', 'cafe', 'food_court'
                      ]  # https://wiki.openstreetmap.org/wiki/Key:amenity
    education_amenities = [
        'college', 'kindergarten', 'library', 'school', 'university'
    ]
    service_amenities = [
        'bank', 'clinic', 'hospital', 'pharmacy', 'marketplace', 'post_office'
    ]
    shops = ['department_store', 'mall',
             'supermarket']  # https://wiki.openstreetmap.org/wiki/Key:shop
    leisure = ['stadium',
               'park']  # https://wiki.openstreetmap.org/wiki/Key:leisure
    railway = ['station']  # https://wiki.openstreetmap.org/wiki/Key:railway
    aeroway = ['aerodrome']  # https://wiki.openstreetmap.org/wiki/Key:aeroway
    highway = ['traffic_signals', 'stop',
               'crossing']  # https://wiki.openstreetmap.org/wiki/Key:highway

    map__poi_type__poi = {
        'amenity': food_amenities + education_amenities + service_amenities,
        'leisure': leisure,
        'shop': shops,
        'railway': railway,
        'aeroway': aeroway,
        'highway': highway
    }

    map__poi__poi_category = {
        'pub': 'food',
        'bar': 'food',
        'restaurant': 'food',
        'cafe': 'food',
        'food_court': 'food',
        'college': 'education',
        'kindergarten': 'education',
        'library': 'education',
        'school': 'education',
        'university': 'education',
        'bank': 'service',
        'clinic': 'service',
        'hospital': 'service',
        'pharmacy': 'service',
        'marketplace': 'service',
        'post_office': 'service',
        'stadium': 'leisure',
        'park': 'leisure',
        'department_store': 'retail',
        'mall': 'retail',
        'supermarket': 'retail',
        'station': 'transport',
        'aerodrome': 'transport',
        'traffic_signals': 'signage',
        'stop': 'signage',
        'crossing': 'signage'
    }

    ###
    #start_time = time.time()

    # querying all the POIs of certain types in the region
    gdf_pois = ox.geometries_from_place(region, map__poi_type__poi)
    # gdf_pois = ox.geometries_from_bbox(north, south, east, west, map__poi_type__poi)

    set_edges_missing_geometry = set()
    for u, v, key, edge_data in road_network.edges(keys=True, data=True):
        # taking the centroid of the road
        try:
            road_centroid = edge_data['geometry'].centroid
        except KeyError:
            set_edges_missing_geometry.add((u, v, key))
            # adding as attributes to the edge with None
            for poi_cat in set(map__poi__poi_category.values()):
                edge_data[poi_cat] = None
            continue

        # taking all the POIs in the gdf that are distant no more than radius from the centroid
        gdf_pois['dist'] = list(
            map(
                lambda k: ox.distance.great_circle_vec(
                    gdf_pois.loc[k]['geometry'].centroid.y, gdf_pois.loc[k]
                    ['geometry'].centroid.x, road_centroid.y, road_centroid.x),
                gdf_pois.index))
        gdf_nearest_pois = gdf_pois[gdf_pois['dist'] <= radius]

        # creating dictionary with categories of POIs and counts
        map__poi_cat__num_of_poi = {
            'food': 0,
            'education': 0,
            'service': 0,
            'leisure': 0,
            'retail': 0,
            'transport': 0,
            'signage': 0
        }
        for poi_type, poi_list in map__poi_type__poi.items():
            if poi_type in gdf_nearest_pois.columns:
                c_df = getattr(gdf_nearest_pois, poi_type).value_counts()
                for poi in [poi for poi in c_df.index if poi in poi_list]:
                    poi_category = map__poi__poi_category[poi]
                    # if poi_category not in map__poi_cat__num_of_poi:
                    #    map__poi_cat__num_of_poi[poi_category] = 0
                    map__poi_cat__num_of_poi[poi_category] += c_df[poi]

        # adding as attributes to the edge
        for poi_cat, num_of_poi in map__poi_cat__num_of_poi.items():
            edge_data[poi_cat] = num_of_poi

    #runtime = time.time() - start_time
    #print('runtime: ', time.time() - start_time)
    #print('')
    print(
        '> There were %s out of %s total edges with missing geometry attribute.'
        % (len(set_edges_missing_geometry), road_network.size()))

    return road_network
Esempio n. 13
0
from scripts.utils import pixel2poly
# Plotting defaults
plt.style.use('ggplot')
px.defaults.height = 400; px.defaults.width = 620
plt.rcParams.update({'font.size': 16, 'axes.labelweight': 'bold', 'figure.figsize': (6, 6), 'axes.grid': False})

## 1. Spatial visualization
<hr>

### 1.1. Geopandas

We saw last chapter how to easily plot geospatial data using the `geopandas` method `.plot()`. This workflow is useful for making quick plots, exploring your data, and easily layering geometries. Let's import some data of UBC buildings using `osmnx` (our Python API for accessing OpenStreetMap data) and make a quick plot:

ubc = (ox.geometries_from_place("University of British Columbia, Canada", tags={'building':True})
         .loc[:, ["geometry"]]                 # just keep the geometry column for now
         .query("geometry.type == 'Polygon'")  # only what polygons (buidling footprints)
         .assign(Label="Building Footprints")  # assign a label for later use
         .reset_index(drop=True)               # reset to 0 integer indexing
      )
ubc.head()

Recall that we can make a plot using the `.plot()` method on a `GeoDataFrame`:

ax = ubc.plot(figsize=(8, 8), column="Label", legend=True,
              edgecolor="0.2", markersize=200, cmap="rainbow")
plt.title("UBC");

Say I know the "point" location of my office but I want to locate the building footprint (a "polygon"). That's easily done with `geopandas`!

First, I'll use `shapely` (the Python geometry library `geopandas` is built on) to make my office point, but you could also use the `geopandas` function `gpd.points_from_xy()` like we did last chapter:
Esempio n. 14
0
def get_historical_buildings_fromOSM(place,
                                     download_method,
                                     epsg=None,
                                     distance=1000):
    """    
    The function downloads and cleans buildings footprint geometries and create a buildings GeoDataFrames for the area of interest.
    The function exploits OSMNx functions for downloading the data as well as for projecting it.
    The land use classification for each building is extracted. Only relevant columns are kept.   
            
    Parameters
    ----------
    place: string, tuple
        name of cities or areas in OSM: when using "from point" please provide a (lat, lon) tuple to create the bounding box around it; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string, {"from_point", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data.
    epsg: int
        epsg of the area considered; if None OSMNx is used for the projection
    distance: float
        Specify distance from address or point
    
    Returns
    -------
    GeoDataFrames
    """

    columns = ['geometry', 'historic']

    if download_method == "distance_from_address":
        historic_buildings = ox.geometries_from_address(
            address=place, dist=distance, tags={"building": True})
    elif download_method == "OSMplace":
        historic_buildings = ox.geometries_from_place(place,
                                                      tags={"building": True})
    elif download_method == "from_point":
        historic_buildings = ox.geometries_from_point(center_point=place,
                                                      dist=distance,
                                                      tags={"building": True})
    else:
        raise downloadError(
            'Provide a download method amongst {"from_point", "distance_from_address", "OSMplace"}'
        )

    if 'heritage' in historic_buildings:
        columns.append('heritage')
    historic_buildings = historic_buildings[columns]

    if 'heritage' in historic_buildings:
        historic_buildings = historic_buildings[~(
            historic_buildings.historic.isnull()
            & historic_buildings.heritage.isnull())]
    else:
        historic_buildings = historic_buildings[~historic_buildings.historic.
                                                isnull()]

    if epsg is None:
        historic_buildings = ox.projection.project_gdf(historic_buildings)
    else:
        crs = 'EPSG:' + str(epsg)
        historic_buildings = historic_buildings.to_crs(crs)

    historic_buildings["historic"] = 1
    historic_buildings["historic"][historic_buildings["historic"] != 0] = 1
    historic_buildings = historic_buildings[['geometry', 'historic']]
    historic_buildings['area'] = historic_buildings.geometry.area

    return historic_buildings
Esempio n. 15
0
def get_buildings_fromOSM(place, download_method, epsg=None, distance=1000):
    """    
    The function downloads and cleans buildings footprint geometries and create a buildings GeoDataFrames for the area of interest.
    The function exploits OSMNx functions for downloading the data as well as for projecting it.
    The land use classification for each building is extracted. Only relevant columns are kept.   
            
    Parameters
    ----------
    place: string, tuple
        name of cities or areas in OSM: when using "from point" please provide a (lat, lon) tuple to create the bounding box around it; when using "distance_from_address"
        provide an existing OSM address; when using "OSMplace" provide an OSM place name
    download_method: string, {"from_point", "distance_from_address", "OSMplace"}
        it indicates the method that should be used for downloading the data.
    epsg: int
        epsg of the area considered; if None OSMNx is used for the projection
    distance: float
        Specify distance from address or point
    
    Returns
    -------
    buildings_gdf: Polygon GeoDataFrame
        the buildings GeoDataFrame
    """

    columns_to_keep = [
        'amenity', 'building', 'geometry', 'historic', 'land_use_raw'
    ]

    if download_method == "distance_from_address":
        buildings_gdf = ox.geometries_from_address(address=place,
                                                   dist=distance,
                                                   tags={"building": True})
    elif download_method == "OSMplace":
        buildings_gdf = ox.geometries_from_place(place,
                                                 tags={"building": True})
    elif download_method == "from_point":
        buildings_gdf = ox.geometries_from_point(center_point=place,
                                                 dist=distance,
                                                 tags={"building": True})
    elif download_method == "OSMpolygon":
        buildings_gdf = ox.geometries_from_polygon(place,
                                                   tags={"building": True})
    else:
        raise downloadError(
            'Provide a download method amongst {"from_point", "distance_from_address", "OSMplace", "OSMpolygon}'
        )

    if epsg is None:
        buildings_gdf = ox.projection.project_gdf(buildings_gdf)
    else:
        crs = 'EPSG:' + str(epsg)
        buildings_gdf = buildings_gdf.to_crs(crs)

    buildings_gdf['land_use_raw'] = None
    for column in buildings_gdf.columns:
        if column.startswith('building:use:'):
            buildings_gdf.loc[pd.notnull(buildings_gdf[column]),
                              'land_use_raw'] = column[13:]
        if column not in columns_to_keep:
            buildings_gdf.drop(column, axis=1, inplace=True)

    buildings_gdf = buildings_gdf[~buildings_gdf['geometry'].is_empty]
    buildings_gdf['building'].replace('yes', np.nan, inplace=True)
    buildings_gdf['building'][
        buildings_gdf['building'].isnull()] = buildings_gdf['amenity']
    buildings_gdf['land_use_raw'][
        buildings_gdf['land_use_raw'].isnull()] = buildings_gdf['building']
    buildings_gdf['land_use_raw'][
        buildings_gdf['land_use_raw'].isnull()] = 'residential'

    buildings_gdf = buildings_gdf[['geometry', 'historic', 'land_use_raw']]
    buildings_gdf['area'] = buildings_gdf.geometry.area
    buildings_gdf = buildings_gdf[buildings_gdf['area'] >= 50]

    # reset index
    buildings_gdf = buildings_gdf.reset_index(drop=True)
    buildings_gdf['buildingID'] = buildings_gdf.index.values.astype('int')

    return buildings_gdf
Esempio n. 16
0
def setup_osm(place_name):
    graph = ox.graph_from_place(place_name)
    buildings = ox.geometries_from_place(place_name, tags={'building': True})
    area = ox.geocode_to_gdf(place_name)
    nodes, edges = ox.graph_to_gdfs(graph)
    return graph, buildings, area, edges
Esempio n. 17
0
    simplify=True)
graph = nx.compose(graph, graph2)  # gráfok egyesítése - networkx.compose

# A hálózat megjelenítése
fig1, ax = ox.plot_graph(graph,
                         bgcolor='white',
                         node_color='red',
                         node_edgecolor='black',
                         edge_color='blue')

# Befoglaló terület
area = ox.geocode_to_gdf(place_name)
#area.plot()

# Point of Interest lekérdezés a területen belül
poi = ox.geometries_from_place(
    place_name, tags={'building': ['university', 'college', 'transportation']})

# Hálózat GeoDataFrame (gdf) konverziója
# gráf csúcsai (nodes) és élei (edges)
nodes, edges = ox.graph_to_gdfs(graph)

# GDF plot
# Élek és POI-k  megjelenítése
fig2, ax = plt.subplots()
edges.plot(ax=ax)
poi.plot(ax=ax, facecolor='red')

# Hálózat vetítése HD72 rendszerbe
graph_proj = ox.project_graph(graph, to_crs=23700)

# Élek és csúcsok leválogatása