Skip to main content

NetworkDataset

Краткая информация

Предоставляет доступ к свойствам набора сетевых данных. Этот класс можно использовать для получения свойств и значений атрибутов ребер, соединений и поворотов набора сетевых данных, а также других свойств набора сетевых данных.

Синтаксис

NetworkDataset(in_network)

Имя Объяснение Тип данных

in_network

Набор сетевых данных, свойства которого вы хотите получить. Аргумент можно задать с помощью пути к каталогу ч набором сетевых данных, объекту слоя набора сетевых данных или строки с именем слоя набора сетевых данных.

String

Свойства

Имя Объяснение Тип данных

buildTimestamp

(Только для чтения)

Дата и время последнего построения набора сетевых данных.

DateTime

customEvaluators

(Чтение / Запись)

Список классов Python, которые настраивают значения сетевых атрибутов для ребер, соединений и поворотов во время операции решения. Свойство должно быть указано как список экземпляров пользовательских классов, наследуемых от класса arcpy.nax.AttributeEvaluator.

Классы пользовательского анализатора не могут быть постоянно связаны с набором сетевых данных с помощью этого свойства. Связь является временной и применяется только для выполнения операций в том же скрипте, где установлено это свойство. Чтобы навсегда сохранить связь с классом пользовательского анализатора, используйте метод updateNetworkDatasetSchema.

Более подробно о пользовательских анализаторах

Object

directionsCustomizer

(Чтение / Запись)

Класс Python, который настраивает текст маневра по направлениям, возвращаемый при использовании набора сетевых данных в операции решения. Свойство должно быть указано как экземпляр определяемого пользователем класса, наследуемого от класса arcpy.nax.DirectionsCustomizer.

Классы пользовательских маршрутов не могут быть постоянно связаны с набором сетевых данных с помощью этого свойства. Связь является временной и применяется только для выполнения операций в том же скрипте, где установлено это свойство. Чтобы навсегда сохранить связь с классом пользовательских маршрутов, используйте метод updateNetworkDatasetSchema.

Более подробно о пользовательских маршрутах

Object

edgeCount

(Только для чтения)

Число ребер сети.

Integer

isBuilt

(Только для чтения)

Указывает, построен ли набор сетевых данных. Значение False означает, что набор сетевых данных необходимо перестроить для сохранения изменений.

Boolean

junctionCount

(Только для чтения)

Число соединений сети.

Integer

travelModes

(Только для чтения)

Возвращает словарь объектов режимов передвижения, которые доступны в наборе сетевых данных. Ключи словаря – это имена режимов передвижения, а значения словаря – это объекты режимов передвижения. Это свойство возвращает такие же выходные данные, как и функция GetTravelModes.

Dictionary

turnCount

(Только для чтения)

Число поворотов в сети.

Integer

Методы

checkIntersectingFeatures(feature_layer, cutoff)

Возвращает значение Boolean, определяющее, является ли количество исходных объектов-ребер из заданного набора сетевых данных, которые пересекаются объектами в заданном векторном слое, меньшим или равным заданной предельной величине. Эта функция применяется для ограничения количества объектов, которые могут быть загружены, как линейные или полигональные барьеры в слой сетевого анализа.

Этот метод схож с функцией CheckIntersectingFeatures.

Имя Объяснение Тип данных

feature_layer

Объект Layer с объектами, пересекающими источники ребер сети. Любой набор выделения или запрос на определения в объекте слоя учитывается и может использоваться для указания поднабора объектов.

Layer

cutoff

Максимальное число пересекающих объектов.

Integer

Возвращаемое значение

Тип данных Объяснение

Boolean

Возвращает True, если число пересекающих объектов меньше или равно значению cutoff. Возвращает False, если число пересекающих объектов превышает значение cutoff.

describe()

Возвращает объект Describe, содержащий дополнительные свойства набора сетевых данных. Это равнозначно использованию команды arcpy.Describe для набора сетевых данных.

Возвращаемое значение

Тип данных Объяснение

Object

Объект Describe набора сетевых данных.

edges({edge_properties[edge_properties,...]}, {attribute_names[attribute_names,...]}, {time_of_day}, {eids[eids,...]}, {travel_mode}, {area_of_interest})

Возвращает итератор ребер набора сетевых данных, который можно использовать для доступа к значениям определенных свойств ребер и сетевых атрибутов в указанное время дня.

Имя Объяснение Тип данных

edge_properties[edge_properties,...]

(Дополнительный)

A list of strings representing the network edge properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:

  • EID—The ID of the edge.

  • SOURCEID— The ID of the source feature class of the edge.

  • SOURCEOID— The ObjectID of the feature within the source feature class from which this network edge is derived.

  • FROMPOSITION— The distance along the source feature where this network edge starts. A network edge can represent a partial feature in the source feature class.

  • TOPOSITION— The distance along the source feature where this network edge ends.

  • DIRECTION— A Boolean value indicating whether the edge's direction is along the direction of digitization of the source feature. A value of True means that the edge's direction is along the direction of digitization, and a value of False means that the edge's direction is against the direction of digitization.

  • FROMJUNCTION— The EID of the junction feature at the beginning of the edge.

  • TOJUNCTION— The EID of the junction feature at the end of the edge.

  • ISRESTRICTED—A Boolean value indicating whether the edge is restricted for the specified travel mode.

  • COST—The cost to traverse the edge for the specified travel mode.

  • TIME—The time cost to traverse the edge for the specified travel mode.

  • DISTANCE—The distance cost incurred by traversing the edge for the specified travel mode.

To request the ISRESTRICTED, COST, TIME, and DISTANCE properties, you must specify a value for the travel_mode parameter.

String

attribute_names[attribute_names,...]

(Дополнительный)

The list of network dataset attribute names, such as costs or restrictions, for which to retrieve the value for each network element. If the value is time dependent, you can specify the time of day using the time_of_day parameter. For a single attribute, you can use a string instead of a list of strings.

String

time_of_day

(Дополнительный)

The time of day for which to retrieve time-dependent attribute values for this network element. When no time of day value is passed, the time-neutral value will be returned.

DateTime

eids[eids,...]

(Дополнительный)

A list of EID values to include in the cursor. This allows you to return only a subset of all network elements. If no value is passed for this parameter, all network elements are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Integer

travel_mode

(Дополнительный)

The travel mode to apply when requesting edge properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters.

When no travel mode is specified, all values requested from attribute_names use their default attribute parameter values, and the ISRESTRICTED, COST, TIME, and DISTANCE properties are not available.

The travel mode should be specified as a TravelMode object. You can use one of the network's travel modes obtained using the NetworkDataset object's travelModes property or use a custom TravelMode object.

Object

area_of_interest

(Дополнительный)

The spatial filter to apply when requesting edge properties and attribute values. This allows you to return only the subset of edges that intersect the specified area of interest.

The parameter should be specified as an Extent object or a Polygon object. If an Extent object is used, all edges intersecting the rectangular extent are returned. If a Polygon object is used, all edges intersecting the polygon's shape are returned. The Polygon option can be used to filter edges by country or state boundaries, for example. If a 3D polygon is used, all edges intersecting the 2D projection of the polygon are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Object

Возвращаемое значение

Тип данных Объяснение

Object

Для итерирования по возвращенным ребрам может использоваться объект NetworkDatasetEdgeCursor. Каждая строка - это кортеж со значениями элементов, заданными в параметрах ребра edge_properties и attribute_names.

getDataSourceFromSourceID(source_id)

Возвращает путь к каталогу класса объектов исходного набора сетевых данных, идентифицированного по указанному идентификатору источника.

Подсказка:

Этот метод работает фактически мгновенно, поскольку считывает кэшированное значение. Ваш код может многократно вызывать этот метод с минимальным влиянием на производительность.

Имя Объяснение Тип данных

source_id

The network source ID for which the corresponding source feature class's catalog path will be retrieved.

Integer

Возвращаемое значение

Тип данных Объяснение

String

Путь к каталогу класса объектов исходного набора сетевых данных.

getLiveTrafficStatus(wait_for_update)

В наборе сетевых данных с настроенным текущим трафиком OpenLR, getLiveTrafficStatus считывает локальный кеш трафика и возвращает словарь с ключевыми индикаторами состояния.

Имя Объяснение Тип данных

wait_for_update

Specifies whether the function will wait for any ongoing cache update to complete before retuning the status.

  • True—The function will wait for any ongoing cache update to complete before returning the status.

  • False—The function will return the status immediately.

(Значение по умолчанию — False)

Boolean

Возвращаемое значение

Тип данных Объяснение

Dictionary

Словарь, содержащий ключевые индикаторы состояния о потоке текущего трафика и его кеше.

Поддерживаются следующие ключи словаря:

  • cachePath — Полный путь к папке кеша. Эта папка может существовать или нет.

  • isLastUpdateSuccessful — Указывает, успешно ли завершилось последнее обновление.

  • isUpdateInProgress — Указывает, выполняется ли в данный момент обновление кеша.

  • roadClosuresDataAvailable — Указывает, содержит ли кеш данные о закрытых дорогах.

  • roadClosuresDataSize — Размер (в кБ) данных о закрытых дорогах в кеше.

  • speedDataAvailable — Указывает, содержит ли кэш данные о скорости.

  • speedsDataSize — Размер (в кБ) данных о скорости в кеше.

  • tempDataSize — Размер (в кБ) временных данных в кеше.

  • trafficCacheStatus — Словарь с информацией о статусе кэша или None, если кэш не был создан.

Поддерживаются следующие ключи словаря trafficCacheStatus:

  • endTimeWindow — Конечное время временного окна в виде метки времени UNIX Epoch (POSIX).

  • lastCreatedFileNames — Список файлов, созданных во время последнего обновления.

  • lastDecodingElapsedTime — Время (в миллисекундах), затраченное на декодирование строк OpenLR.

  • lastRemovedFileNames — Список устаревших файлов, удаленных из кэша во время последнего обновления.

  • lastUpdatedElapsedTime — Продолжительность последнего обновления (в миллисекундах).

  • lastUpdatedMessages — Список сообщений, полученных в процессе обновления кеша. Каждое сообщение представляет собой словарь, где ключ type указывает тип сообщения (информация, предупреждение или ошибка), а ключ description содержит текст сообщения.

  • lastUpdatedTime — Время последнего обновления кеша в формате метки времени UNIX Epoch (POSIX).

  • remainingSpeedLocationsToMatch — Количество местоположений со скоростью, которые все еще необходимо сопоставить.

  • roadClosureLocationsCount — Общее количество закрытых дорог, которые в настоящее время сопоставлены в наборе сетевых данных.

  • selectedTrafficDataRegions — Источники данных о движении, используемые для набора сетевых данных.

  • speedLocationsCount — Общее количество местоположений скорости OpenLR, которые в настоящее время сопоставлены в наборе сетевых данных.

  • startTimeWindow — Начальное время временного окна в виде метки времени UNIX Epoch (POSIX).

Пример выходного словаря

{
    'cachePath': 'C:\\Users\\user1234\\AppData\\Local\\ESRI\\Local Caches\\TrafficCache\\openlr.3d8242d7b77a47b6b7d42acb5ce87f97',
    'isLastUpdateSuccessful': True,
    'isUpdateInProgress': False,
    'roadClosuresDataAvailable': True,
    'roadClosuresDataSize': 5384,
    'speedDataAvailable': True,
    'speedsDataSize': 1847255,
    'tempDataSize': 1862992,
    'trafficCacheStatus': {
        'endTimeWindow': 1741141680000,
        'lastCreatedFileNames': ['speeds.20250305012800.1.ff.dat', 'speeds.20250305012800.1.nff.dat', 'road_closures.20250305012800.1.dat', 'speeds.20250305012800.info.dat'],
        'lastDecodingElapsedTime': 0,
        'lastRemovedFileNames': [],
        'lastUpdatedElapsedTime': 6285,
        'lastUpdatedMessages': [
            {
                'description': 'FF update is required because of feed: USA_SW',
                'type': 'info'
            }
        ],
        'lastUpdatedTime': 1741138226073,
        'remainingSpeedLocationsToMatch': 0,
        'roadClosureLocationsCount': 44,
        'selectedTrafficDataRegions': ['USA_SW'],
        'speedLocationsCount': 4047,
        'startTimeWindow': 1741137091000
    }
}

junctions({junction_properties[junction_properties,...]}, {attribute_names[attribute_names,...]}, {time_of_day}, {eids[eids,...]}, {travel_mode}, {area_of_interest})

Возвращает итератор соединений набора сетевых данных, который можно использовать для доступа к значениям определенных свойств соединений и сетевых атрибутов в указанное время дня.

Имя Объяснение Тип данных

junction_properties[junction_properties,...]

(Дополнительный)

A list of strings representing the network junction properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:

  • EID—The ID of the junction.

  • SOURCEID— The ID of the source feature class of the junction.

  • SOURCEOID— The ObjectID of the feature within the source feature class from which this network junction is derived.

  • ISRESTRICTED—A Boolean value indicating whether the junction is restricted for the specified travel mode.

  • COST—The cost to traverse the junction for the specified travel mode.

  • TIME—The time cost to traverse the junction for the specified travel mode.

  • DISTANCE—The distance cost incurred by traversing the junction for the specified travel mode.

To request the ISRESTRICTED, COST, TIME, and DISTANCE properties, you must specify a value for the travel_mode parameter.

String

attribute_names[attribute_names,...]

(Дополнительный)

The list of network dataset attribute names, such as costs or restrictions, for which the value of each network element will be retrieved. If the value is time dependent, you can specify the time of day using the time_of_day parameter. For a single attribute, you can use a string instead of a list of strings.

String

time_of_day

(Дополнительный)

The time of day that time-dependent attribute values for this network element will be retrieved. When no time of day value is passed, the time-neutral value will be returned.

DateTime

eids[eids,...]

(Дополнительный)

A list of EID values to include in the cursor. This allows you to return only a subset of all network elements. If no value is passed for this parameter, all network elements are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Integer

travel_mode

(Дополнительный)

The travel mode to apply when requesting junction properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters.

When no travel mode is specified, all values requested from attribute_names use their default attribute parameter values, and the ISRESTRICTED, COST, TIME, and DISTANCE properties are not available.

The travel mode should be specified as a TravelMode object. You can use one of the network's travel modes obtained using the NetworkDataset object's travelModes property or use a custom TravelMode object.

Object

area_of_interest

(Дополнительный)

The spatial filter to apply when requesting junction properties and attribute values. This allows you to return only the subset of junctions that intersect the specified area of interest.

The parameter should be specified as an Extent object or a Polygon object. If an Extent object is used, all junctions intersecting the rectangular extent are returned. If a Polygon object is used, all junctions intersecting the polygon's shape are returned. The Polygon option can be used to filter junctions by country or state boundaries, for example. If a 3D polygon is used, all junctions intersecting the 2D projection of the polygon are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Object

Возвращаемое значение

Тип данных Объяснение

Object

Объект NetworkDatasetJunctionCursor, который можно использовать для итерирования возвращенных соединений. Каждая строка - это кортеж со значениями элементов, заданных в параметрах junction_properties и attribute_names для этого соединения.

turns({turn_properties[turn_properties,...]}, {attribute_names[attribute_names,...]}, {eids[eids,...]}, {travel_mode}, {area_of_interest})

Возвращает итератор элементов поворотов набора сетевых данных, которые используются для доступа к значению определенных свойств поворота и атрибутов сети.

Имя Объяснение Тип данных

turn_properties[turn_properties,...]

(Дополнительный)

A list of strings representing the network turn properties to retrieve. For a single property, you can use a string instead of a list of strings. The available properties include the following:

  • EID—The ID of the turn.

  • SOURCEID— The ID of the source feature class of the turn.

  • SOURCEOID— The ObjectID of the feature within the source feature class from which this network turn is derived.

  • EDGEEIDS— An ordered list of EID values of network edges that participate in this turn.

  • ISRESTRICTED—A Boolean value indicating whether the turn is restricted for the specified travel mode.

  • COST—The cost to traverse the turn for the specified travel mode.

  • TIME—The time cost to traverse the turn for the specified travel mode.

  • DISTANCE—The distance cost incurred by traversing the turn for the specified travel mode.

To request the ISRESTRICTED, COST, TIME, and DISTANCE properties, you must specify a value for the travel_mode parameter.

String

attribute_names[attribute_names,...]

(Дополнительный)

The list of network dataset attribute names, such as costs or restrictions, for which to retrieve the value for each network element. For a single attribute, you can use a string instead of a list of strings.

String

eids[eids,...]

(Дополнительный)

A list of EID values to include in the cursor. This allows you to return only a subset of all network elements. If no value is passed for this parameter, all network elements are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Integer

travel_mode

(Дополнительный)

The travel mode to apply when requesting turn properties and attribute values. The travel mode settings may impact the returned property and attribute values, particularly if the travel mode uses nondefault values for any attribute parameters.

When no travel mode is specified, all values requested from attribute_names use their default attribute parameter values, and the ISRESTRICTED, COST, TIME, and DISTANCE properties are not available.

The travel mode should be specified as a TravelMode object. You can use one of the network's travel modes obtained using the NetworkDataset object's travelModes property or use a custom TravelMode object.

Object

area_of_interest

(Дополнительный)

The spatial filter to apply when requesting turn properties and attribute values. This allows you to return only the subset of turns that intersect the specified area of interest.

The parameter should be specified as an Extent object or a Polygon object. If an Extent object is used, all turns intersecting the rectangular extent are returned. If a Polygon object is used, all turns intersecting the polygon's shape are returned. The Polygon option can be used to filter turns by country or state boundaries, for example. If a 3D polygon is used, all turns intersecting the 2D projection of the polygon are returned.

The eids and area_of_interest parameters cannot be used simultaneously.

Object

Возвращаемое значение

Тип данных Объяснение

Object

Объект NetworkDatasetTurnCursor, который можно использовать для итерирования возвращенных поворотов. Каждая строка - это кортеж со значениями элементов, заданных в параметрах turn_properties и attribute_names для этого поворота.

updateNetworkDatasetSchema({custom_evaluators}, {custom_directions}, {openlr_traffic_service_id}, {openlr_traffic_feed_ids})

Обновляет набор сетевых данных, чтобы связать с сетью пользовательский анализатор или класс Python путевых листов или задает идентификатор сервиса Текущего трафика OpenLR или идентификаторы каналов.

Имя Объяснение Тип данных

custom_evaluators

(Дополнительный)

A dictionary that describes the custom evaluators that will be associated with the network dataset.

The dictionary keys are the network attribute names that the custom evaluator will be applied to. The values are a dictionary with a class key and an optional sourceNames key. The class key value describes how to import the custom evaluator class from the active ArcGIS Pro Python environment's site-packages directory using a dot notation to specify the package, module, and class. The sourceNames key value is a list of network source names specifying the sources the custom evaluator applies to. If this key is not included in the dictionary, the custom evaluator will apply to all sources.

This code snippet shows a dictionary with the correct structure to update the network dataset's Minutes attribute with a custom evaluator whose code is defined in a class named CostCustomizer in a Python file named custom_eval.py in a folder Python na_customization in the Python environment's site-packages directory.

ce_description = {
    "Minutes": {
        "class": "na_customization.custom_eval.CostCustomizer",
        "sourceNames": ["Streets"]
    }
}
nd.updateNetworkDatasetSchema(custom_evaluators=ce_description)

Only include a given network attribute in the dictionary once. You can only associate one custom evaluator with a given attribute.

To remove a reference to existing custom evaluators from the network dataset schema, use a value of None when calling this method.

nd.updateNetworkDatasetSchema(custom_evaluators=None)

Внимание:

Positional arguments are not supported with this method. To associate a custom evaluator with the network, you must use the named argument custom_evaluators when calling this method.

Learn more about custom evaluators

Dictionary

custom_directions

(Дополнительный)

A dictionary that describes the directions customization classes that will be associated with the network dataset.

The dictionary must have a class key. The value describes how to import the custom evaluator class from the active ArcGIS Pro Python environment's site-packages directory using a dot notation to specify the package, module, and class.

This code snippet shows a dictionary with the correct structure to update the network dataset schema with a custom directions class named DirectionsCustomizer in a Python file named custom_directions.py in a folder named na_customization in the Python environment's site-packages directory.

cd_description = {"class": "na_customization.custom_directions.DirectionsCustomizer"}
nd.updateNetworkDatasetSchema(custom_directions=cd_description)

To remove a reference to existing custom directions classes from the network dataset schema, use a value of None when calling this method.

nd.updateNetworkDatasetSchema(custom_directions=None)

Внимание:

Positional arguments are not supported with this method. To associate a custom directions class with the network, you must use the named argument custom_directions when calling this method.

Learn more about custom directions

Dictionary

openlr_traffic_service_id

(Дополнительный)

Specifies an ID that represents the OpenLR live traffic service that the network will use.

Valid values are as follows:

  • ActivePortal—The active portal will be used.

  • The ID property value defined in the .traffic configuration file of the network's geodatabase—The service defined in the configuration file will be used.

  • An empty string—The existing configuration will be cleared, and the traffic service will be removed from the network.

String

openlr_traffic_feed_ids

(Дополнительный)

Specifies one or more IDs that represents the OpenLR live traffic feed IDs that the network will use.

The schema can only have the traffic service ID or the traffic feed IDs set. Setting one will clear the other from the schema. Setting both in a single call with raise an exception.

Valid values are as follows:

  • A list of one or more feed ID strings as defined in the traffic configuration file of the network's geodatabase

  • An empty list or None will clear the feed IDs from the schema

network_dataset.updateNetworkDatasetSchema(openlr_traffic_feed_ids=['TomTom_USA_M', 'TomTom_USA_SW'])

String

updateTrafficCache({timeout_seconds})

В наборе сетевых данных с настроенным текущим трафиком OpenLR, updateTrafficCache обновляет локальный кэш трафика, добавляя актуальные данные о скорости, перекрытиях дорог и сопутствующими метаданными.

Имя Объяснение Тип данных

timeout_seconds

(Дополнительный)

The maximum duration in seconds the function can run. If this time limit is exceeded, the function will automatically terminate.

If no value is specified, the timeout duration will be the number of seconds specified by the cronScheduleSeconds value defined in the .traffic configuration file of the network's geodatabase. If no configuration file exists, a timeout duration of 240 seconds will be used.

Long

Пример кода

NetworkDataset, пример 1

Выдает время в пути для каждого ребра сети, по которому не ограничено движение автомобилей.

# Print the travel time for each edge in the network that is not restricted to automobiles
import datetime
import arcpy

nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"

# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)

# Print network dataset build information
print(f"Network dataset is built: {nds.isBuilt}")
print(f"Most recent build time: {nds.buildTimestamp}")

# Iterate through all the edges in the network and get the TravelTime cost attribute
# value for a specific time of day. Only print the value if the edge is not restricted
# to automobiles
edges = nds.edges("EID", ["TravelTime", "Driving an Automobile"], datetime.datetime(2019, 4, 19, 8, 0, 0))
for edge in edges:
    if not edge[2]:
        print(f"TravelTime for EID {edge[0]}: {edge[1]}")
NetworkDataset, пример 2

Получает значения ObjectID всех соединений для всех ребер, которые участвуют в поворотах.

# Retrieve the ObjectIDs of all junctions for all edges that participate in turns
import arcpy

nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"

# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)

# Iterate through all turns in the network and get the edges that participate
turns = nds.turns(["SOURCEOID", "EDGEEIDS"])
for turn in turns:
    # For the edges in the turn, get the from and to junctions
    edges = nds.edges(["SOURCEOID", "FROMJUNCTION", "TOJUNCTION"], eids=turn[1])
    for edge in edges:
        # For the from and to junction, get the SOURCEOID
        junctions = nds.junctions("SOURCEOID", eids=[edge[1], edge[2]])
        junctionOIDs = [j[0] for j in junctions]
NetworkDataset, пример 3

Получает стоимость и статус запрета для всех ребер сети для режима передвижения Walking Time.

# Retrieve the cost and restricted status for all network edges for the Walking Time travel mode
import arcpy

nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"

# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)

# Iterate through all the edges in the network and print the cost to traverse it with the Walking Time travel mode and
# whether or not the edge is restricted.
for edge in nds.edges(["EID", "COST", "ISRESTRICTED"], travel_mode=nds.travelModes["Walking Time"]):
    print(f"EID {edge[0]} -- COST: {edge[1]}; RESTRICTED: {edge[2]}")
NetworkDataset, пример 4

Получает значения ObjectID всех соединений в пределах указанного экстента.

# Retrieve the ObjectID values for junctions within a specified extent
import arcpy

nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
extent_fc = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Analysis\AnalysisExtent"

# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)

# Get the extent from the feature class
extent = arcpy.Describe(extent_fc).extent

# Retrieve the junctions that fall within the designated extent
for junction in nds.junctions(["SOURCEOID"], area_of_interest=extent):
    print(junction)
NetworkDataset, пример 5

Получает значения ObjectID всех соединений в пределах указанных областей.

# Retrieve the ObjectID values for junctions within specified territories
import arcpy

nds_path = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Transportation\Streets_ND"
territories = r"E:\TutorialData\Network Analyst\Tutorial\SanDiego.gdb\Analysis\Territories"

# Initialize the NetworkDataset object
nds = arcpy.nax.NetworkDataset(nds_path)

# Iterate through the polygons in the Territories feature class and retrieve
# the junctions that fall within each territory's boundary.
for row in arcpy.da.SearchCursor(territories, ["Name", "SHAPE@"]):
    print(f"Junctions in territory {row[0]}:")
    for junction in nds.junctions(["SOURCEOID"], area_of_interest=row[1]):
        print(junction[0])