Exemplo 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)

    # 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)
Exemplo n.º 2
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
Exemplo n.º 3
0
def download_osm(args):
    bbox_coord = tuple(args.bbox)
    filename = args.outfile
    # test  coordinates: north, south, east, west = 30.33622 ,30.34384,78.03883,78.05268
    north, south, east, west = bbox_coord[0], bbox_coord[1], bbox_coord[
        2], bbox_coord[3]
    print("Downloading: " + args.tags)
    if args.tags == "roads":
        tags = {'highway': True}
    elif args.tags == "buildings":
        tags = {'building': True}
    gdf = ox.geometries_from_bbox(north, south, east, west, tags)
    gdf = gdf.apply(lambda c: c.astype(str) if c.name != 'geometry' else c,
                    axis=0)
    gdf.to_file(filename, driver='GeoJSON')
    print("Data downloaded and saved in " + filename)
Exemplo n.º 4
0
def osm_gdf_from_bbox(north, south, east, west, tags):
    """Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box.

    Args:
        north (float): Northern latitude of bounding box.
        south (float): Southern latitude of bounding box.
        east (float): Eastern longitude of bounding box.
        west (float): Western longitude of bounding box.
        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.

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

    gdf = ox.geometries_from_bbox(north, south, east, west, tags)
    return gdf
Exemplo n.º 5
0
    def _get_city_data_within_rectangle(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_bbox(self.north,
                                            self.south,
                                            self.east,
                                            self.west,
                                            network_type='drive')
        if self.city_dict['water'] is True:
            self.water = ox.geometries.geometries_from_bbox(
                self.north,
                self.south,
                self.east,
                self.west,
                tags=self.water_tags)
        if self.city_dict['green'] is True:
            self.green = ox.geometries.geometries_from_bbox(
                self.north,
                self.south,
                self.east,
                self.west,
                tags=self.green_tags)
        if self.city_dict['buildings'] is True:
            self.buildings = ox.geometries.geometries_from_bbox(
                self.north,
                self.south,
                self.east,
                self.west,
                tags={
                    "building": True,
                    'landuse': 'construction'
                })
        if self.city_dict['railways'] is True:
            self.railways = ox.geometries_from_bbox(self.north,
                                                    self.south,
                                                    self.east,
                                                    self.west,
                                                    tags=self.railway_tags)
Exemplo n.º 6
0
    for node_id in rou:
        x = projected_graph.nodes[node_id]['x']
        y = projected_graph.nodes[node_id]['y']
        points.append([x, y])

    route_coorindates.append(points)

n_routes = len(route_coorindates)

print("Extracted routes: ", n_routes)
max_route_len = max([len(x) for x in route_coorindates])

# Prepare the layout
gdf = ox.geometries_from_bbox(1.3763,
                              1.3007,
                              103.6492,
                              103.7840,
                              tags={"building": True})
gdf_proj = ox.project_gdf(gdf, to_crs="EPSG:3395")

fig, ax = ox.plot_graph(projected_graph,
                        node_size=0,
                        edge_linewidth=1.5,
                        edge_color='#2C2E2C',
                        show=False,
                        close=False,
                        bgcolor='#12830E')  #figsize=(12,8) for larger plots

gdf_proj.plot(ax=ax, linewidth=1, alpha=0.8, color='#F5F5DC')

scatter_list = []
Exemplo n.º 7
0
def download_osm_buildings(
    output_dir,
    polygon=None,
    bbox=None,
    data_crs=None,
    keep_fields=["osmid", "building", "name", "geometry"],
    suffix="",
    overwrite=False
):
    """
    Uses an Overpass query to fetch the OSM building polygons within a
    specified bounding box or the bounding box of a provided shapefile.
    
    Args:
        output_dir (str): Path to output directory.
        polygon (str): path to a shapefile or geojson object readable by geopandas
        bbox (dict): default=None; A dictionary with keys 'south', 'west', 'north', and 'east' of
            EPSG:4326-style coordinates, defining a bounding box for the area from which to fetch
            OSM features. Only required when `study_area_polygon_path` is not provided. See module
            notes for performance and suggestions on usage.
        data_crs (int): integer value representing an EPSG code
        keep_fields (list): list of fields to keep in output dataset
        suffix (str): string value to be added to the end of the output folder
        overwrite (bool): if set to True, delete the existing copy of buildings
    
    Returns:
        buildings_gdf (gpd.GeoDataFrame): A gdf of OSM building features. By default, the CRS of
            the gdf will be EPSG:4326 unless a tranformation is specified using `transfor_epsg` or
            a shape file with a differnt CRS is provided as `study_area_polygon_path`.
    
    Notes:
        OSM building polygons features will automatically be saved in the `output_dir`s
        `OSM_Buildings_{YYYYMMDDHHMMSS}.shp` where `YYYYMMDDHHMMSS` is the date and time at which
        the Overpass query was pushed. This is done for record keeping purposes.
    """

    # Validation of inputs
    # TODO: separate polygon and bbox validation
    bounding_box = validate_inputs(
        study_area_poly=polygon, bbox=bbox, data_crs=data_crs
    )

    # - Output location
    output_dir = validate_directory(make_path(output_dir, f"buildings_{suffix}"))

    # Data read in and setup -------------------------------------------------
    print("...Pulling building data from Overpass API...")
    buildings_gdf = ox.geometries_from_bbox(
        north=bounding_box["north"],
        south=bounding_box["south"],
        east=bounding_box["east"],
        west=bounding_box["west"],
        tags={"building": True},
    )
    # drop non-polygon features and subset fields
    print("...Dropping non-polygon features and unneeded fields")
    buildings_gdf = buildings_gdf[
        buildings_gdf.geom_type.isin(["MultiPolygon", "Polygon"])
    ]
    drop_cols = [col for col in buildings_gdf.columns if col not in keep_fields]
    buildings_gdf.drop(labels=drop_cols, axis=1, inplace=True)
    buildings_gdf.reset_index()

    # Saving -----------------------------------------------------------------
    print("...Saving...")
    dt = datetime.now().strftime("%Y%m%d")
    file_name = "OSM_Buildings_{}.shp".format(dt)
    save_path = make_path(output_dir, file_name)
    check_overwrite_path(output=save_path, overwrite=overwrite)
    buildings_gdf.to_file(save_path)
    print("-- saved to: " + save_path)

    return buildings_gdf
Exemplo n.º 8
0
def create_map_from_osm(outfile: str, c_osm: int, north: float, south: float,
                        west: float, east: float):
    dpi = 200
    default_width = 6
    network_type = 'drive'

    fp = f'./images/{outfile}-osm-{c_osm}.png'

    tag_building = TagTypes.building
    tag_nature = TagTypes.nature
    tag_water = TagTypes.water

    ax = None

    G = ox.graph_from_bbox(north,
                           south,
                           east,
                           west,
                           network_type=network_type,
                           truncate_by_edge=True,
                           retain_all=True,
                           clean_periphery=False)

    gdf_building = ox.geometries_from_bbox(north,
                                           south,
                                           east,
                                           west,
                                           tags=tag_building)
    gdf_nature = ox.geometries_from_bbox(north,
                                         south,
                                         east,
                                         west,
                                         tags=tag_nature)
    gdf_water = ox.geometries_from_bbox(north,
                                        south,
                                        east,
                                        west,
                                        tags=tag_water)

    fig, ax = ox.plot_figure_ground(G,
                                    default_width=default_width,
                                    dpi=dpi,
                                    filepath=fp,
                                    show=False)
    if not gdf_nature.empty:
        fig, ax = ox.plot_footprints(gdf_nature,
                                     ax=ax,
                                     color='green',
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)
    if not gdf_water.empty:
        fig, ax = ox.plot_footprints(gdf_water,
                                     ax=ax,
                                     color='blue',
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)
    if not gdf_building.empty:
        fig, ax = ox.plot_footprints(gdf_building,
                                     ax=ax,
                                     filepath=fp,
                                     dpi=dpi,
                                     save=True)