Select to view content in your preferred language

Calculate routes

411
1
06-07-2018 01:28 PM
PhilippS
New Contributor

Hello, I am new to this community, so I hope my Question ist placed in the right postion:

Due to one of my companie's projects, I have to calculate routes between two points. No problem if I have two points and two feature classes. But I have one feature class with just one point and another with multiple points. So now I have to calculate the route from the single point to each of the other points seperately, using a Python script.

Any idea to solve this?

0 Kudos
1 Reply
J_R_Matchett
Occasional Contributor

You can create a FeatureSet from any two Features and pass it to the find_routes function, so you can iterate over the features in your multiple-points feature set and create a new 2-point feature set along with the start feature. Here's an example where I use a single feature set and select one point as the start and find routes to the other points:

from arcgis.gis import GIS
from arcgis.features import FeatureLayer, FeatureSet
from arcgis.network.analysis import find_routes

gis = GIS(username='name', password='pass')

# get 4 cities
cities_layer = FeatureLayer('https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Major_Cities/FeatureServer/0')
cities = cities_layer.query(
    where="NAME IN ('Santa Clara', 'Sunnyvale', 'Milpitas', 'Cupertino')",
    out_fields='FID, NAME',
    out_sr=4326  # feature points must be in lat/lon
)

# set the start city
start_city = cities.features[2]
start_city.set_value('FID', 0)  # routes are calculated in order of IDs,
                                # so set start city to smallest ID
routes = []
for end_city in cities.features:
    # skip if start city
    if end_city.get_value('FID') == 0:
        continue
    start_end = FeatureSet([start_city, end_city])
    routes.append(find_routes(stops=start_end))

for r in routes:
    print('\n' + r.output_directions.df.RouteName[0])
    print(r.output_directions.df[['Text', 'DriveDistance']])
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍