def test_gdf_from_place(): # test loading spatial boundaries and plotting city = ox.gdf_from_place(place1) city_projected = ox.projection.project_gdf(city, to_crs="epsg:3395") city = ox.gdf_from_place(place1, buffer_dist=100) ox.plot_shape(city)
def getChangchunReign(): city = ox.gdf_from_places( ['南关区,长春,中国', '朝阳区,长春,中国', '二道区,长春,中国', '绿园区,长春,中国', '宽城区,长春,中国']) city = ox.project_gdf(city) ox.save_gdf_shapefile(city, filename='test1') #save ox.plot_shape(city) #show
def test_gdf_shapefiles(): # test loading spatial boundaries, saving as shapefile, and plotting city = ox.gdf_from_place('Manhattan, New York City, New York, USA') city_projected = ox.project_gdf(city, to_crs={'init': 'epsg:3395'}) ox.save_gdf_shapefile(city_projected) city = ox.gdf_from_place('Manhattan, New York City, New York, USA', buffer_dist=100) ox.plot_shape(city)
def test_gdf_shapefiles(): city = ox.gdf_from_place('Manhattan, New York City, New York, USA') city_projected = ox.project_gdf(city, to_crs={'init':'epsg:3395'}) ox.save_gdf_shapefile(city_projected) city = ox.gdf_from_place('Manhattan, New York City, New York, USA', buffer_dist=100) ox.plot_shape(city)
def test_gdf_shapefiles(): # test loading spatial boundaries, saving as shapefile, and plotting city = ox.gdf_from_place('Manhattan, New York City, New York, USA') city_projected = ox.project_gdf(city, to_crs={'init':'epsg:3395'}) ox.save_gdf_shapefile(city_projected) city = ox.gdf_from_place('Manhattan, New York City, New York, USA', buffer_dist=100) ox.plot_shape(city)
def test_gdf_shapefiles(): with httmock.HTTMock(get_mock_response_content()): city = ox.gdf_from_place('Manhattan, New York City, New York, USA') city_projected = ox.project_gdf(city, to_crs={'init':'epsg:3395'}) ox.save_gdf_shapefile(city_projected) with httmock.HTTMock(get_mock_response_content()): city = ox.gdf_from_place('Manhattan, New York City, New York, USA', buffer_dist=100) ox.plot_shape(city)
def plot_india_map(state_dict: dict): all_states = [] for k in state_dict: all_states.append({"state": k}) try: values = [x / max(state_dict.values()) for x in state_dict.values()] except ZeroDivisionError: values = [0] * len(all_states) places = ox.gdf_from_places(all_states) places = ox.project_gdf(places) ox.plot_shape(places, ec="w", fc=get_colors(values))
def make_map(n_californias, all_colors, color_keywords): counties = cache_result(COUNTIES_FILENAME, fetch_counties_gdf) projected = cache_result(PROJECTED_FILENAME, ox.project_gdf, counties) geom_list = list(counties.itertuples()) geom_list = counties["geometry"].tolist() neighbors = cache_result(NEIGHBORS_FILENAME, compute_neighbors, geom_list) n_californias = min(n_californias, len(COUNTIES)) n_californias = min(n_californias, len(all_colors)) remaining = set(range(len(geom_list))) californias = [] for _ in range(n_californias): temp = random.choice(list(remaining)) remaining.remove(temp) californias.append([temp]) while remaining: which_california = random.randrange(n_californias) new_neighbor_choices = set() for county_id in californias[which_california]: for neighbor_id in neighbors[county_id]: if neighbor_id in remaining: new_neighbor_choices.add(neighbor_id) if not new_neighbor_choices: continue new_neighbor = random.choice(list(new_neighbor_choices)) californias[which_california].append(new_neighbor) remaining.remove(new_neighbor) face_colors = [None] * len(geom_list) palette = random.sample(all_colors, n_californias) for color, california in zip(palette, californias): for county_id in california: face_colors[county_id] = color fig, ax = ox.plot_shape(projected, fc=face_colors) bio = io.BytesIO() fig.savefig(bio) bio.seek(0) number_word = num2words(n_californias) text = "{} Californias".format(number_word[:1].upper() + number_word[1:]) if color_keywords is None: description = ("A map of California, where the counties are {} " "different colors".format(n_californias)) else: if len(color_keywords) == 1: kws_joined = color_keywords[0] elif len(color_keywords) == 2: kws_joined = " and ".join(color_keywords) else: kws_joined = "{}, and {}".format(", ".join(color_keywords[:-1]), color_keywords[-1]) description = ("A map of California, where the counties are {} " "different shades of {}".format(n_californias, kws_joined)) return text, bio, description
location_point = (-17.1010286, 145.7753749) gdf = ox.buildings_from_point(point=location_point, distance=5000) gdf_proj = ox.project_gdf(gdf) bbox = ox.bbox_from_point(point=location_point, distance=5000, project_utm=True) fig, ax = ox.plot_buildings(gdf_proj) import osmnx as ox, geopandas as gpd ox.config(log_file=True, log_console=True, use_cache=True) place_names = ['Gordonvale, Queensland, Australia'] east_bay = ox.gdf_from_places(place_names) ox.save_gdf_shapefile(east_bay) east_bay = ox.project_gdf(east_bay) fig, ax = ox.plot_shape(east_bay) import osmnx as ox ox.config(log_file=True, log_console=True, use_cache=True) city = ox.gdf_from_place('Sydney, New South Wales, Australia') city ox.save_gdf_shapefile(city) city = ox.project_gdf(city) fig, ax = ox.plot_shape(city) import osmnx as ox from IPython.display import Image ox.config(log_console=True, use_cache=True) # configure the inline image display img_folder = 'images'
import osmnx as ox import networkx as nx import folium import pandas as pd from geopandas.io import file UBC = ox.gdf_from_place('UBC') toshow = ox.project_gdf(UBC) ox.plot_shape(toshow) unified = UBC.unary_union.convex_hull G = ox.graph_from_polygon(unified, network_type='walk', truncate_by_edge=True, clean_periphery=False, simplify=True) ox.plot_graph(ox.project_graph(G)) def plot_route(fn): dataframe = pd.read_csv(fn) loa = list(dataframe['Location']) routes = [] for index, address in enumerate(loa): if index + 1 <= len(loa) - 1: origin = ox.utils.geocode(address)
#!/usr/bin/env python # coding: utf-8 # In[5]: import osmnx as ox city = ox.gdf_from_place('Berkeley, California') ox.plot_shape(ox.project_gdf(city)) # In[10]: places = ox.gdf_from_places(['Botswana', 'Zambia', 'Zimbabwe']) places = ox.project_gdf(places) ox.save_gdf_shapefile(places) ox.plot_shape(ox.project_gdf(places)) # In[11]: G = ox.graph_from_bbox(37.79, 37.78, -122.41, -122.43, network_type='drive') G_projected = ox.project_graph(G) ox.plot_graph(G_projected) # In[12]:
#matplotlib inline #ox.config(log_file=True, log_console=True, use_cache=True) #For converting unicode string of chracters to string cname = place_name.encode('utf-8') filename = filename.encode('utf-8') location = location.encode('utf-8') # create the street network within the city borders G = ox.load_graphml(filename, folder=location) # you can project the network to UTM (zone calculated automatically) G = ox.project_graph(G) fig, ax = ox.plot_graph(G) # get the street network for a place, and its area in square meters gdf = ox.gdf_from_place(cname) gdf = ox.project_gdf(gdf) fig, ax = ox.plot_shape(gdf) area = ox.project_gdf(gdf).unary_union.area # calculate basic and extended network stats, merge them together, and display stats = ox.basic_stats(G, area=area) df = pd.DataFrame.from_dict(stats, orient="index") df.to_csv("/home/osmjit/Desktop/testdata/data.csv") ex_stats = ox.extended_stats(G, connectivity=False, anc=False, ecc=False, bc=False, cc=False) dfe = pd.DataFrame(ex_stats) dfe.to_csv("/home/osmjit/Desktop/testdata/data_extended.csv")
import osmnx as ox, geopandas as gpd, networkx as nx from networkx.algorithms import centrality as cen from itertools import chain from collections import defaultdict import matplotlib.pyplot as plt import matplotlib.pyplot as plt import pandas as pd import progressbar import shapefile import progressbar import pyproj import json import shp2osmnx as s2nx Name_of_Place=str(Name_of_Place) # get the boundary polygon for project it to UTM, and plot it city = ox.gdf_from_place(Name_of_Place) city = ox.project_gdf(city) fig, ax = ox.plot_shape(city, figsize=(3,3)) figpoly=folder_to_save_graphml+str('/polygon.pdf') plt.savefig(figpoly) G = ox.graph_from_place(Name_of_Place,network_type='drive') G_projected = ox.project_graph(G) fig, ax = ox.plot_graph(G_projected) fignet=folder_to_save_graphml+str('/network.pdf') plt.savefig(fignet) #save graph ox.save_load.save_graphml(G, filename=graphml_file_name, folder=folder_to_save_graphml)
# save the retrieved data as a shapefile ox.save_gdf_shapefile(city, u'雁塔区', r'./data/') #Get building footprints within the boundaries of some place. aaaBuilding = ox.buildings.buildings_from_place(place=u'雁塔区, 西安, 中国') #gdf = ox.buildings_from_place(place='Piedmont, California, USA') ox.save_gdf_shapefile(aaaBuilding, 'test', r'./data/') #Get building footprints within some distance north, south, east, and west of an address. #address_rect = ox.buildings.buildings_from_address('钟楼, 南大街, 南院门街道, 碑林区, 西安市, 陕西省, 710001, 中国', 3000) point_rect = ox.buildings.buildings_from_point((34.374944, 107.129382), 300, retain_invalid=False) #Get building footprints within some distance north, south, east, and west of a lat-long point. ox.plot_shape(point_rect) #道路网下载保存 #osmnx.core.graph_from_place(query, network_type='all_private', simplify=True, retain_all=False, truncate_by_edge=False, name='unnamed', which_result=1, buffer_dist=None, timeout=180, memory=None, max_query_area_size=2500000000, clean_periphery=True, infrastructure='way["highway"]', custom_filter=None) street_graph = ox.graph_from_place("金台区, 宝鸡市, 陕西省", network_type='all_private', which_result=2) #返回结果为graph 对象 street_gdfs = ox.save_load.graph_to_gdfs( street_graph, nodes=False, edges=True, node_geometry=True, fill_edge_geometry=True) #将graph_转化为_gdf 对象 ox.save_load.save_graph_shapefile(street_graph, filename='Baoji_jintai', folder=None,
path = 'data/bikes_streets/{}/'.format(name) assure_path_exists(path) path_simple = 'data/bikes_streets/{}/simple/'.format(name) assure_path_exists(path_simple) print('Starting with: {}'.format(name)) # Download the shape city_shape = area(city) city_shape = ox.project_gdf(city_shape) ox.save_gdf_shapefile(city_shape, filename='{}_shape'.format(name), folder=path) print('Saved') ox.plot_shape(city_shape) # Drive ''' G_drive = get_network(city, n_type='drive') ox.save_graphml(G_drive, filename='{}_drive.graphml'.format(name), folder=path) print('{} Drive downloaded and saved. Elapsed time {} s\nSimplifying the network...'.format( name, round(time.time()-start_0, 2))) G_simple = simplify_graph(G_drive) nx.write_edgelist(G_simple, path=path_simple+'{}_drive_simple.txt'.format(name)) print('{} Drive simplified and saved. Elapsed time {} s'.format( name, round(time.time()-start_0, 2))) # Pedestrian G = get_network(city, n_type='walk') ox.save_graphml(G, filename='{}_pedestrian.graphml'.format(name), folder=path)
place_names = ['Ho Chi Minh City, Vietnam', #'Beijing, China', #'Jakarta, Indonesia', 'London, UK', 'Los Angeles, California, USA', 'Manila, Philippines', #'Mexico City, Mexico', 'New Delhi, India', 'Sao Paulo, Brazil', 'New York, New York, USA', 'Seoul', 'Singapore', #'Tokyo, Japan', #'Nairobi, Kenya', #'Bangalore, India' ] # In this for-loop, we save all the shapefiles for the valid cities. for city in place_names: city_admin_20kmbuff = ox.gdf_from_place(city, gdf_name = 'global_cities', buffer_dist = 20000) fig, ax = ox.plot_shape(city_admin_20kmbuff) ox.save_gdf_shapefile(city_admin_20kmbuff, filename = city) # In this for-loop, we save all the street networks for the valid cities. for city in place_names: grid = ox.graph_from_place(city, network_type = 'drive', retain_all = True) grid_projected = ox.project_graph(grid) ox.save_graph_shapefile(grid_projected, filename = city + '_grid') ox.plot_graph(grid_projected)
import osmnx as ox S = ox.gdf_from_place("Island of Montreal, Canada") ox.plot_shape(S)
# Export to shapefile city_graph = ox.project_graph(city_graph) ox.save_graph_shapefile(city_graph, filename="osm_" + city.replace(", ", "")) # # # save street network as GraphML file # ox.save_graphml(city_graph, filename='network.graphml') # # g = igraph.Graph.Read_GraphML("D:/Dropbox/EarthArtAustralia/data/network.graphml") # igraph.plot(g) # # # # G2 = ox.load_graphml('network.graphml') # fig, ax = ox.plot_graph(G2) # import igraph # import networkx gdf = ox.gdf_from_place(city) G = ox.graph_from_point(gdf["geometry"], distance_type="bbox") ox.plot_shape(ox.project_gdf(gdf)) G = ox.graph_from_address(city, distance=3000) ox.plot_graph(G) import osmnx as ox gdf = ox.gdf_from_place('Povo, Italy') G = ox.graph_from_point('Povo, Italy', distance=3000)