Exemple #1
0
from overpass import API
import numpy as np
from collections import defaultdict
from geopy.distance import vincenty
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
api = API()
api.timeout = 900
response = api.Get(
    'way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps|crossing"](40.751872, -73.994120 ,40.762353, -73.979678);'
)
node_dic = {}
cor_dic = defaultdict(list)
x = 0
for features in response['features']:
    for coordinate in features['geometry']['coordinates']:
        node_dic[x] = (coordinate[1], coordinate[0])
        x += 1
for node_num in node_dic:
    cor_dic[node_dic[node_num]].append(node_num)

intersection_cor_dic = {
}  #key(노드번호) value(위도경도)  #{0: (40.752814, -73.981372), 259: (40.753481, -73.980888)
cor_intersection_dic = {
}  # key(위도경도) value(노드번호)    #(40.7572592, -73.9858201): [406, 416]

for a in cor_dic:
    if len(cor_dic[a]) >= 2:
        cor_intersection_dic[a] = cor_dic[a][0]
        intersection_cor_dic[cor_dic[a][0]] = a
Exemple #2
0
from overpass import API

api = API()

locations=(40.748164, -73.949755)

x = locations[0]
y = locations[1]

response = api.Get('way["highway"](around:50,{0},{1});'.format(x, y))

print(response.keys())
for a in response['features']:
    print(a)

print("-----------------------")

print(response['features'][0])
for a in response['features'][0]:
    print(a)

print("-----------------------")

print(response['features'][0]['properties'])

for a in response['features'][0]['properties']:
    print(a, ':' ,response['features'][0]['properties'][a])
Exemple #3
0
from overpass import API
from collections import defaultdict

api = API()
# response = api.Get('way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps"](40.751872, -73.994120 ,40.752353, -73.989678);',responseformat="xml")
response2 = api.Get(
    'way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps"](40.751872, -73.994120 ,40.752353, -73.989678);'
)

# print(response)
# print(response2)

way_dic = defaultdict

for a in response2["features"]:
    print(a["geometry"]["coordinates"])
Exemple #4
0
from overpass import API
import json, io

api = API()
api.timeout=900
# response = str(api.Get('way["tiger:county"= "New York, NY"]["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps'
#                    'crossing|construction"];'))

response = str(api.Get('way["tiger:county"= "New York, NY"]["highway"];'))


j_response = json.loads(response)

with io.open('data2.json', 'w', encoding='utf8') as outfile:
    str_ = json.dumps(j_response,
                      indent=4, sort_keys=True,
                      separators=(',', ':'), ensure_ascii=False)
    outfile.write(str(str_))
Exemple #5
0
from overpass import API
import numpy as np
from collections import defaultdict
from geopy.distance import vincenty
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx

api = API()
api.timeout = 900
# response = api.Get('way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps|crossing"](40.751872, -73.994120 ,40.762353, -73.979678);')
response = api.Get(
    'way["tiger:county"= "New York, NY"]["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps"];'
)

node_dic = {}
cor_dic = defaultdict(list)
x = 0
for features in response['features']:
    for coordinate in features['geometry']['coordinates']:
        node_dic[x] = (coordinate[1], coordinate[0])
        x += 1

for node_num in node_dic:
    cor_dic[node_dic[node_num]].append(node_num)

intersection_cor_dic = {
}  #key(노드번호) value(위도경도)  #{0: (40.752814, -73.981372), 259: (40.753481, -73.980888)
cor_intersection_dic = {
}  # key(위도경도) value(노드번호)    #(40.7572592, -73.9858201): [406, 416]
# overpass_ex1.py
# ENGSCI233: Computational Techniques and Computer Systems
# A simple overpass example, for inspecting and exploring the returned data structure.

from overpass import API

api = API()
dat = api.get('node["amenity"="pub"](-36.89,174.70,-36.83,174.80)', responseformat='json')

# set a breakpoint on the line below then run this script in debug mode
print(dat)
Exemple #7
0
def make_ARCS(lat1,lon1,lat2,lon2): #좌하 우상 위도경도 입력
    api = API() #overpass API객체 불러오기
    api.timeout=900 # 검색시간 default값이 60초라서 900로 늘려줌

    # response = api.Get('way["highway"]["highway"~"motorway|trunk"](40.701274, -74.033596, 40.807903, -73.931286);') 예시
    response = api.Get('way["highway"]["highway"~"motorway|trunk"]({}, {}, {}, {});'.format(lat1,lon1,lat2,lon2)) #위도경도 값을 넣어서 motorway와 trunk인 고속도로 return

################################################################################


    node_dic={}                     # key(노드번호) value(위도경도)         #{0: (40.752814, -73.981372), 1: (40.7527642, -73.9812537), 2: (40.7521797, -73.9798676), 3: (40.7521385, -73.9797698)
    cor_dic=defaultdict(list)       # key(위도경도) value(노드번호_list)    #(40.7572592, -73.9858201): [406, 416], (40.7507266, -73.9879255): [94], (40.7534284, -73.9807633): [527]
    x = 0
    for features in response['features']:
        for coordinate in features['geometry']['coordinates']:
            node_dic[x] = (coordinate[1], coordinate[0])
            x += 1
    for node_num in node_dic:
        cor_dic[node_dic[node_num]].append(node_num)
################################################################################

#같은 위도경도에 노드번호가 2개이상 이라면 intersection//
    #-> intersection들만 모아서 dictionary를 생성

    intersection_cor_dic = {} #key(노드번호) value(위도경도)  #{0: (40.752814, -73.981372), 259: (40.753481, -73.980888)
    cor_intersection_dic={}   # key(위도경도) value(노드번호)    #(40.7572592, -73.9858201): [406, 416]

    for a in cor_dic:
        if len(cor_dic[a])>=2:
            cor_intersection_dic[a]=cor_dic[a][0]
            intersection_cor_dic[cor_dic[a][0]]=a


###############################################################################
        #-> intersection갯수 만큼의 2차형 어레이 생성
    node_size = len(node_dic)
    distance_list = np.zeros((node_size,node_size),dtype='float')
###############################################################################

    #response안에 들어있는 좌표(coordinates)들을 꺼냄

    # (글로 설명하기 어렵습니다 제가 하나하나 확인해봤는데 잘 작동합니다..!
    for feature in response['features']:
        corlist = feature['geometry']['coordinates']
        i = 0                                                                       # i와 j를 먼저 생성
        j = 1
        for i in range(len(corlist)-1):
            distance=0
            for j in range(i+1,len(corlist)):
                cor_key1 = (corlist[i][1],corlist[i][0])
                cor_key2 = (corlist[j][1],corlist[j][0])
                distance += vincenty((corlist[j-1][1],corlist[j-1][0]), (corlist[j][1],corlist[j][0])).km * 100  # i1 j(n) 누적으로 더한 값들 // 단위는 m로 했습니다.
                if cor_key1 in cor_intersection_dic.keys():                         # i가 intersection노드 안에 포함이 되있고
                    if cor_key2 in cor_intersection_dic.keys():                     # j도 intersection노드 안에 포함이 되 있으면
                        distance_list[cor_intersection_dic[cor_key1]][cor_intersection_dic[cor_key2]] = distance # i 와 j 의 거리를 합한 값을 distance_list에 넣어준다
                        break
                else:
                    break

###############################################
    # populations = pd.read_csv("sub-est2015_all.csv")
    # print(populations)
    for i in intersection_cor_dic:
        print(i, intersection_cor_dic[i])
        url = "http://nominatim.openstreetmap.org/reverse?format=json&lat={}&lon={}&zoom=18&addressdetails=1".format(
            intersection_cor_dic[i][0], intersection_cor_dic[i][1])
        res = requests.get(url)
        print(res.json()['address'])
Exemple #8
0
from overpass import API

api = API()
api.timeout = 900

# response = api.Get('way["name"="6th Avenue"];')
# response = api.Get('way["highway"]["tiger:county"= "New York, NY"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps"];')

response = api.Get(
    'way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps"](40.752197, -73.993588 ,40.762937, -73.973621);'
)

# response = api.Get('way[highway][name="6th Avenue"];node(w)->.n1;way[highway][name="West 23rd Street"];node(w)->.n2;node.n1.n2;')

print(response)
# print(response.keys())
for a in response['features']:
    print(a['geometry']['coordinates'])
    print(a['properties'])

    try:
        print(a['properties']['oneway'])
    except:
        print('no')
    print("------")
Exemple #9
0
from overpass import API
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from geopy.distance import vincenty

api = API()
api.timeout = 900
response = api.Get(
    'way["highway"]["highway"~"motorway|trunk"](40.462335, -74.362618, 40.918417, -73.669106);'
)

node_dic = {}
x = 0
for features in response['features']:
    for coordinate in features['geometry']['coordinates']:
        node_dic[x] = (coordinate[1], coordinate[0])
        x += 1

cor_dic = defaultdict(list)
for node_num in node_dic:
    cor_dic[node_dic[node_num]].append(node_num)

node_size = len(node_dic)
arc_list = np.zeros((node_size, node_size), dtype='int')
distance_list = np.zeros((node_size, node_size), dtype='float')

print(arc_list)

x = 0
Exemple #10
0
def make_ARCS(lat1, lon1, lat2, lon2):  #좌하 우상 위도경도 입력
    api = API()  #overpass API객체 불러오기
    api.timeout = 900  # 검색시간 default값이 60초라서 900로 늘려줌

    # response = api.Get('way["highway"]["highway"~"motorway|trunk"](40.701274, -74.033596, 40.807903, -73.931286);') 예시
    response = api.Get(
        'way["highway"]["highway"~"motorway|trunk"]({}, {}, {}, {});'.format(
            lat1, lon1, lat2, lon2))  #위도경도 값을 넣어서 motorway와 trunk인 고속도로 return

    ################################################################################

    node_dic = {
    }  # key(노드번호) value(위도경도)         #{0: (40.752814, -73.981372), 1: (40.7527642, -73.9812537), 2: (40.7521797, -73.9798676), 3: (40.7521385, -73.9797698)
    cor_dic = defaultdict(
        list
    )  # key(위도경도) value(노드번호_list)    #(40.7572592, -73.9858201): [406, 416], (40.7507266, -73.9879255): [94], (40.7534284, -73.9807633): [527]
    x = 0
    for features in response['features']:
        for coordinate in features['geometry']['coordinates']:
            node_dic[x] = (coordinate[1], coordinate[0])
            x += 1
    for node_num in node_dic:
        cor_dic[node_dic[node_num]].append(node_num)
################################################################################

#같은 위도경도에 노드번호가 2개이상 이라면 intersection//
#-> intersection들만 모아서 dictionary를 생성

    intersection_cor_dic = {
    }  #key(노드번호) value(위도경도)  #{0: (40.752814, -73.981372), 259: (40.753481, -73.980888)
    cor_intersection_dic = {
    }  # key(위도경도) value(노드번호)    #(40.7572592, -73.9858201): [406, 416]

    for a in cor_dic:
        if len(cor_dic[a]) >= 2:
            cor_intersection_dic[a] = cor_dic[a][0]
            intersection_cor_dic[cor_dic[a][0]] = a

###############################################################################
#-> intersection갯수 만큼의 2차형 어레이 생성
    node_size = len(node_dic)
    distance_list = np.zeros((node_size, node_size), dtype='float')
    ###############################################################################

    #response안에 들어있는 좌표(coordinates)들을 꺼냄

    # (글로 설명하기 어렵습니다 제가 하나하나 확인해봤는데 잘 작동합니다..!
    for feature in response['features']:
        corlist = feature['geometry']['coordinates']
        i = 0  # i와 j를 먼저 생성
        j = 1
        for i in range(len(corlist) - 1):
            distance = 0
            for j in range(i + 1, len(corlist)):
                cor_key1 = (corlist[i][1], corlist[i][0])
                cor_key2 = (corlist[j][1], corlist[j][0])
                distance += vincenty(
                    (corlist[j - 1][1], corlist[j - 1][0]),
                    (corlist[j][1], corlist[j][0]
                     )).km * 100  # i1 j(n) 누적으로 더한 값들 // 단위는 m로 했습니다.
                if cor_key1 in cor_intersection_dic.keys(
                ):  # i가 intersection노드 안에 포함이 되있고
                    if cor_key2 in cor_intersection_dic.keys(
                    ):  # j도 intersection노드 안에 포함이 되 있으면
                        distance_list[cor_intersection_dic[cor_key1]][
                            cor_intersection_dic[
                                cor_key2]] = distance  # i 와 j 의 거리를 합한 값을 distance_list에 넣어준다
                        break
                else:
                    break


###############################################
# 데이터로 만들기 csv파일로 만들었습니다
# 패키지는 pandas를 이용하였습니다

    Arc_tuple_List = [
    ]  ##(0, 3), (0, 72), (3, 339), (18, 31), (18, 124), (19, 22), (19, 66), (22, 169), (22, 179)
    #(i,j) 입니다
    for x, y in enumerate(distance_list):
        for i, j in enumerate(y):
            if distance_list[x, i] != False:
                Arc_tuple_List.append((x, i))

    df = pd.DataFrame()

    arc_i_list = [arc[0] for arc in Arc_tuple_List]
    arc_j_list = [arc[1] for arc in Arc_tuple_List]
    arc_distace_list = [
        distance_list[arc[0]][arc[1]] for arc in Arc_tuple_List
    ]

    df["i"] = arc_i_list
    df["j"] = arc_j_list
    df["distance"] = arc_distace_list
    df.to_csv(
        "distance.csv"
    )  #@#@@##$@#@#$@#$@#%T%%%/<<----------- 빈 csv파일 생성하고 이름을 distance로 먼저 만들어 주셔야 합니다 그다음 실행시키면 저장이 됩니다.
Exemple #11
0
from overpass import API
import json, io
from uszipcode import ZipcodeSearchEngine

api = API()
api.timeout = 900

# response = str(api.Get('way["highway"]["highway"!~"footway|cycleway|path|track|pedestrian|steps|crossing'
#                        '|construction"](40.697655, -74.031030, 40.875447, -73.863863);'))
response = api.Get(
    'way["highway"]["highway"!~"footway|cycleway|path|track|pedestrian|steps|crossing'
    '|construction"](40.697655, -74.031030, 40.875447, -73.863863);')
# response = api.Get('way["highway"]["highway"!~"footway|cycleway|path|track|pedestrian|steps|crossing'
#                        '|construction"](40.760233, -74.026183, 40.767530, -73.985527);')

postcode_list = [
    "10025", "10024", "10040", "10009", "10027", "10003", "10014", "10012",
    "10005", "10004", "10019", "10023", "10006", "10035", "10010", "10016",
    "10032", "10002", "10038", "10013", "10278", "10018", "10036", "10128",
    "10280", "10037", "10028", "10115", "10029", "10031", "10039", "10026",
    "10044", "10021", "10007", "10011", "10034", "10030", "10111", "10022",
    "10119", "10199", "10001", "10033", "10282", "10065", "10075", "10173",
    "10165", "10168", "10174", "10112", "10020", "10103", "10017", "10069",
    "10167", "10154", "10170"
]

search = ZipcodeSearchEngine()
response2 = {"features": []}
for features in response['features']:
    # print(features['geometry'], features['properties'])
    coordinates = features['geometry']['coordinates']
import json

from overpass import API

api = API()


def get_coords(latitude, longitude):
    overpass_query = f"""
    (
    way
    (around:50,{latitude},{longitude})
    [highway~"^(primary|secondary|tertiary|residential)$"]
    [name];
    >;);out;
    """
    response = api.Get(overpass_query)

    coordinates = list()
    latitudes = list()
    longitudes = list()

    for feature in response['features']:
        if len(feature['geometry']['coordinates']):
            coordinates.append(feature['geometry']['coordinates'])
            longitudes.append(feature['geometry']['coordinates'][0])
            latitudes.append(feature['geometry']['coordinates'][1])
    return latitudes[:5], longitudes[:5]
Exemple #13
0
from overpass import API
from time import sleep
from sys import exc_info

api = API()

locations = [(50.406029, 30.619727), (27.988056, 86.925278)]
for loc in locations:
    xx, yy = loc[0], loc[1]
    try:
        response = api.Get('way["highway"](around:50,{0},{1});'.format(
            loc[0], loc[1]))
        print("For location with coordinates {0}, {1} found way IDs:".format(
            loc[0], loc[1]))
        if len(response['elements']) > 0:
            for way in response['elements']:
                print(way['id'])
        else:
            print("No ways")
        sleep(1)
    except:
        print("Got error: {0}".format(exc_info())[0])
Exemple #14
0
from overpass import API
import json, io

api = API()
api.timeout = 900
# response = str(api.Get('way["tiger:county"= "New York, NY"]["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps'
#                    'crossing|construction"];'))

response = str(
    api.Get(
        'way["tiger:county"= "New York, NY"]["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps'
        'crossing|construction"];'))

j_response = json.loads(response)

with io.open('data.json', 'w', encoding='utf8') as outfile:
    str_ = json.dumps(j_response,
                      indent=4,
                      sort_keys=True,
                      separators=(',', ':'),
                      ensure_ascii=False)
    outfile.write(str(str_))
Exemple #15
0
from overpass import API
import numpy as np
from collections import defaultdict
from geopy.distance import vincenty
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx

api = API()
api.timeout = 900
response = api.Get(
    'way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps|'
    'crossing|construction"](40.761872, -73.994120 ,40.782353, -73.969678);')
# response = api.Get('way["highway"]["highway"!~"footway|cycleway|path|service|track|pedestrian|steps|'
#                    'crossing|construction|residential|bridleway|motorway_link"](40.761872, -73.994120 ,40.782353, -73.969678);')

node_dic = {}
cor_dic = defaultdict(list)
x = 0
for features in response['features']:
    print(features['geometry']['coordinates'])
    for coordinate in features['geometry']['coordinates']:
        node_dic[x] = (coordinate[1], coordinate[0])
        x += 1

print("node_dic: ", node_dic)

for node_num in node_dic:
    cor_dic[node_dic[node_num]].append(node_num)

distance_dic = {}