Как найти расстояние до ближайшего края на MultiDiGraph с помощью OSMNx - PullRequest
0 голосов
/ 15 апреля 2020

Я пытаюсь найти расстояние в MultiDiGraph от заданного местоположения до ближайшего края и ближайшего узла. Например, указанное местоположение с latitude = 51.217220 и longitude = 4.418535. Сначала мы создаем MultiDiGraph в этом месте с радиусом 350м. Вот код:

import osmnx as ox
lat = 51.217220
lon = 4.418535
G = ox.graph_from_point((lat, lon), network_type='drive', distance=350, simplify=True)

Пакет OSMNx имеет 2 ценные функции для моего проекта: get_nearest_edge() и get_nearest_node(). get_nearest_node() находит ближайший узел и возвращает его идентификатор. Он также имеет встроенную опцию для возврата расстояния до этого ближайшего узла:

ox.get_nearest_node(G, (lat,lon), method='haversine', return_dist=True) 

get_nearest_edge находит ближайший край и возвращает идентификаторы 2 узлов, которые определяют край (каждый край состоит из 2 узла подключены). Однако встроенной опции для определения расстояния до этого края нет.

Как рассчитать расстояние от заданного местоположения до ближайшего края?

Ответы [ 2 ]

0 голосов
/ 16 апреля 2020

Да, моя функция - get_d_to_nearest_edge (). Этот код приведен ниже:

def get_d_to_nearest_edge(latitude, longitude, file_name):
    # get nearest node incident to nearest edge to reference point
    G = ox.load_graphml(filename=file_name, folder='BAPenvironment')
    distance = get_nearest_edge(G, (latitude, longitude))
    print(type(distance))
    print(distance)

В этой функции я вызываю метод get_nearest_edge (), однако он переписывается так, как @ Sparky05 говорил мне ранее. Код ниже:

def get_nearest_edge(G, point):
    """
    Return the nearest edge to a pair of coordinates. Pass in a graph and a tuple
    with the coordinates. We first get all the edges in the graph. Secondly we compute
    the euclidean distance from the coordinates to the segments determined by each edge.
    The last step is to sort the edge segments in ascending order based on the distance
    from the coordinates to the edge. In the end, the first element in the list of edges
    will be the closest edge that we will return as a tuple containing the shapely
    geometry and the u, v nodes.
    Parameters
    ----------
    G : networkx multidigraph
    point : tuple
        The (lat, lng) or (y, x) point for which we will find the nearest edge
        in the graph
    Returns
    -------
    closest_edge_to_point : tuple (shapely.geometry, u, v)
        A geometry object representing the segment and the coordinates of the two
        nodes that determine the edge section, u and v, the OSM ids of the nodes.
    """
    start_time = time.time()

    gdf = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
    graph_edges = gdf[["geometry", "u", "v"]].values.tolist()

    edges_with_distances = [
        (
            graph_edge,
            ox.Point(tuple(reversed(point))).distance(graph_edge[0])
        )
        for graph_edge in graph_edges
    ]

    edges_with_distances = sorted(edges_with_distances, key=lambda x: x[1])
    closest_edge_to_point, distance = edges_with_distances[0]

    geometry, u, v = closest_edge_to_point

    ox.log('Found nearest edge ({}) to point {} in {:,.2f} seconds'.format((u, v), point, time.time() - start_time))
    print(type(distance))
    print(distance)
    return geometry, u, v, distance

Дело в том, что когда я проверяю тип в функции get_nearest_edge (), тип float, как сказал @ Sparky05, и расстояние найдено. Но, однако, когда я возвращаю это значение в свою головную функцию get_d_to_nearest_edge (), значение является кортежем и не может быть напечатано как число с плавающей точкой.

Однако, что еще более важно, это то, что расстояние, которое я нахожу, полностью неверен. Выход: 0.00025593968794827235, а реальное расстояние должно быть 26,13 метра, любая помощь?

0 голосов
/ 15 апреля 2020

Вы можете создать копию оригинального метода get_nearest_edge, и в своей локальной копии метода вам нужно только заменить строку 247 на:

closet_edge_to_point, distance = edges_with_distances[0]

и оператор return с

return geometry, u, v, distance

Вы также можете создать проблему для этого на странице GitHub osmnx и предложить ее как новую функцию.

...