<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Esri Routing service request not optimising in ArcGIS REST APIs and Services Questions</title>
    <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/esri-routing-service-request-not-optimising/m-p/1577068#M4919</link>
    <description>&lt;DIV class=""&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;Hi im trying to optimise a route in a test scenario.&lt;BR /&gt;I have a drive location and some stops.&lt;/DIV&gt;&lt;DIV&gt;my script gets the multiple driver locations and stops into the request with the driver location being first.&lt;BR /&gt;then i get the result for each driver.&lt;BR /&gt;the result is then passed into a url in the order it is recieved from the request in a csv&lt;/DIV&gt;&lt;DIV&gt;&lt;BR /&gt;using this url below and authenticating using a web connection (cliend id and secret )&lt;SPAN&gt;&lt;A href="https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve" target="_blank" rel="noopener"&gt;https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve&lt;/A&gt;&lt;/SPAN&gt;&lt;BR /&gt;&lt;BR /&gt;These are the parameters I'm sending, i'm finding that no matter&amp;nbsp;what parameters i set the route is not optimised at all , it just returns the route in the order i gave it. I have set "findBestSequence": "true"&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;here are the parameters&amp;nbsp;&lt;BR /&gt;&lt;BR /&gt;Stops Parameter: 152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996&lt;/DIV&gt;&lt;DIV&gt;Request Parameters for stops: {&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp; &lt;STRONG&gt;"f": "json",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "token": "xyzxyzx", (removed)&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "stops": "152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "useTraffic": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "startTime": "now",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnDirections": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnStops": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "findBestSequence": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnToStart": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "impedanceAttribute": "time",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "preserveFirstStop": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "preserveLastStop": "false"&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;}&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;here is the result in google&amp;nbsp;&lt;/STRONG&gt;&lt;A href="https://www.google.com/maps/dir/-27.5560699,152.8884487/-27.5571191,152.9154994/-27.5577279,152.94966/-27.5677117,152.8859596/@-27.5375919,152.8809875,14302m/data=!3m2!1e3!4b1?entry=ttu&amp;amp;g_ep=EgoyMDI1MDExNS4wIKXMDSoASAFQAw%3D%3D" target="_blank" rel="noopener"&gt;2-36 Lather Rd, Bellbowrie QLD 4070 to Weekes Rd, Bellbowrie QLD 4070 - Google Maps&lt;/A&gt;&amp;nbsp;you can see its not in a good order&lt;BR /&gt;&lt;BR /&gt;here is my code&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;import requests
import logging
import json
import csv
from arcgis.gis import GIS

# Client ID and Client Secret
CLIENT_ID = 'xyzxy'
CLIENT_SECRET = 'xyzxyzx'

# OAuth2 token endpoint
token_url = "https://www.arcgis.com/sharing/rest/oauth2/token/"
params = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'client_credentials'
}

# Request token
response = requests.post(token_url, data=params)
token_response = response.json()
access_token = token_response.get('access_token')

if not access_token:
    raise Exception("Failed to retrieve access token")

print("Access token acquired successfully!")

# Setup logging for debugging
logging.basicConfig(level=logging.DEBUG)

# Route service URL
route_service_url = (
    "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve"
)

# Authenticate with ArcGIS Online using the token
gis = GIS("https://www.arcgis.com", token=access_token)

# Access the driver feature service
driver_item_id = "xyzxyzxyz"
driver_item = gis.content.get(driver_item_id)

# Access the stops feature service
stops_item_id = "xyzxyzxyzxyz"
stops_item = gis.content.get(stops_item_id)

# Open CSV file for writing
output_filename = "Driver_Routes.csv"
with open(output_filename, mode='w', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    # Write header row
    csvwriter.writerow(["Driver Name", "Google Maps URL"])

    if driver_item and hasattr(driver_item, "layers") and stops_item and hasattr(stops_item, "layers"):
        driver_layer = driver_item.layers[0]
        stops_layer = stops_item.layers[0]

        # Query drivers
        drivers = driver_layer.query(out_fields="Name, SHAPE", return_geometry=True).features

        # Query stops
        stops_features = stops_layer.query(out_fields="Name, SHAPE", return_geometry=True).features

        # Generate route and URL for each driver
        for driver in drivers:
            driver_name = driver.attributes["Name"]
            driver_geometry = driver.geometry
            driver_start_point = f"{driver_geometry['x']},{driver_geometry['y']}"

            # Filter stops for the current driver
            assigned_stops = [
                f"{feature.geometry['x']},{feature.geometry['y']}"
                for feature in stops_features
                if feature.attributes["name"] == driver_name
            ]

            if not assigned_stops:
                print(f"No stops assigned for {driver_name}. Skipping...")
                continue

            # Combine driver start location with assigned stops
            all_stops = [driver_start_point] + assigned_stops
            stops_param = ";".join(all_stops)

            # Log the stops sequence being sent to the API
            print(f"\nDriver: {driver_name}")
            print(f"Stops Parameter: {stops_param}")

            # Query parameters
            params = {
                "f": "json",
                "token": access_token,
                "stops": stops_param,
                "useTraffic": "true", 
                "startTime": "now",
                "returnDirections": "false",
                "returnStops": "true",
                "findBestSequence": "true", 
                "returnToStart": "false",
                "impedanceAttribute": "time",
                "preserveFirstStop": "false",
                "preserveLastStop": "false"
            }

            # Log the full request being sent
            print(f"Request Parameters for {driver_name}: {json.dumps(params, indent=2)}")

            # Make the GET request
            try:
                response = requests.get(route_service_url, params=params)
                response.raise_for_status()

                # Parse the JSON response
                response_json = response.json()
                logging.debug(f"Response JSON for {driver_name}: {response_json}")

                # Check for valid stops
                if "stops" in response_json and "features" in response_json["stops"]:

                    # Generate Google Maps URL
                    coordinates_for_url = [f"{feature['geometry']['y']},{feature['geometry']['x']}" for feature in response_json["stops"]["features"]]
                    google_maps_base_url = "https://www.google.com/maps/dir/"
                    google_maps_url = google_maps_base_url + "/".join(coordinates_for_url)

                    # Print driver-specific URL
                    print(f"Google Maps URL for {driver_name}:")
                    print(google_maps_url)

                    # Write driver name and URL to CSV
                    csvwriter.writerow([driver_name, google_maps_url])

                else:
                    print(f"Failed to retrieve stops for {driver_name}: {response_json.get('error', {}).get('details', 'Unknown error')}")

            except requests.exceptions.RequestException as e:
                print(f"HTTP Request failed for {driver_name}: {e}")
            except Exception as e:
                print(f"An error occurred for {driver_name}: {e}")

    else:
        print("No layers found in the specified items.")

print(f"Driver routes saved to '{output_filename}'")
​&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
    <pubDate>Sun, 19 Jan 2025 12:36:28 GMT</pubDate>
    <dc:creator>TrisKent</dc:creator>
    <dc:date>2025-01-19T12:36:28Z</dc:date>
    <item>
      <title>Esri Routing service request not optimising</title>
      <link>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/esri-routing-service-request-not-optimising/m-p/1577068#M4919</link>
      <description>&lt;DIV class=""&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;DIV&gt;Hi im trying to optimise a route in a test scenario.&lt;BR /&gt;I have a drive location and some stops.&lt;/DIV&gt;&lt;DIV&gt;my script gets the multiple driver locations and stops into the request with the driver location being first.&lt;BR /&gt;then i get the result for each driver.&lt;BR /&gt;the result is then passed into a url in the order it is recieved from the request in a csv&lt;/DIV&gt;&lt;DIV&gt;&lt;BR /&gt;using this url below and authenticating using a web connection (cliend id and secret )&lt;SPAN&gt;&lt;A href="https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve" target="_blank" rel="noopener"&gt;https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve&lt;/A&gt;&lt;/SPAN&gt;&lt;BR /&gt;&lt;BR /&gt;These are the parameters I'm sending, i'm finding that no matter&amp;nbsp;what parameters i set the route is not optimised at all , it just returns the route in the order i gave it. I have set "findBestSequence": "true"&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;here are the parameters&amp;nbsp;&lt;BR /&gt;&lt;BR /&gt;Stops Parameter: 152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996&lt;/DIV&gt;&lt;DIV&gt;Request Parameters for stops: {&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp; &lt;STRONG&gt;"f": "json",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "token": "xyzxyzx", (removed)&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "stops": "152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "useTraffic": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "startTime": "now",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnDirections": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnStops": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "findBestSequence": "true",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "returnToStart": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "impedanceAttribute": "time",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "preserveFirstStop": "false",&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;&amp;nbsp; "preserveLastStop": "false"&lt;/STRONG&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;STRONG&gt;}&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;here is the result in google&amp;nbsp;&lt;/STRONG&gt;&lt;A href="https://www.google.com/maps/dir/-27.5560699,152.8884487/-27.5571191,152.9154994/-27.5577279,152.94966/-27.5677117,152.8859596/@-27.5375919,152.8809875,14302m/data=!3m2!1e3!4b1?entry=ttu&amp;amp;g_ep=EgoyMDI1MDExNS4wIKXMDSoASAFQAw%3D%3D" target="_blank" rel="noopener"&gt;2-36 Lather Rd, Bellbowrie QLD 4070 to Weekes Rd, Bellbowrie QLD 4070 - Google Maps&lt;/A&gt;&amp;nbsp;you can see its not in a good order&lt;BR /&gt;&lt;BR /&gt;here is my code&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;/DIV&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;import requests
import logging
import json
import csv
from arcgis.gis import GIS

# Client ID and Client Secret
CLIENT_ID = 'xyzxy'
CLIENT_SECRET = 'xyzxyzx'

# OAuth2 token endpoint
token_url = "https://www.arcgis.com/sharing/rest/oauth2/token/"
params = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'client_credentials'
}

# Request token
response = requests.post(token_url, data=params)
token_response = response.json()
access_token = token_response.get('access_token')

if not access_token:
    raise Exception("Failed to retrieve access token")

print("Access token acquired successfully!")

# Setup logging for debugging
logging.basicConfig(level=logging.DEBUG)

# Route service URL
route_service_url = (
    "https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve"
)

# Authenticate with ArcGIS Online using the token
gis = GIS("https://www.arcgis.com", token=access_token)

# Access the driver feature service
driver_item_id = "xyzxyzxyz"
driver_item = gis.content.get(driver_item_id)

# Access the stops feature service
stops_item_id = "xyzxyzxyzxyz"
stops_item = gis.content.get(stops_item_id)

# Open CSV file for writing
output_filename = "Driver_Routes.csv"
with open(output_filename, mode='w', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile)
    # Write header row
    csvwriter.writerow(["Driver Name", "Google Maps URL"])

    if driver_item and hasattr(driver_item, "layers") and stops_item and hasattr(stops_item, "layers"):
        driver_layer = driver_item.layers[0]
        stops_layer = stops_item.layers[0]

        # Query drivers
        drivers = driver_layer.query(out_fields="Name, SHAPE", return_geometry=True).features

        # Query stops
        stops_features = stops_layer.query(out_fields="Name, SHAPE", return_geometry=True).features

        # Generate route and URL for each driver
        for driver in drivers:
            driver_name = driver.attributes["Name"]
            driver_geometry = driver.geometry
            driver_start_point = f"{driver_geometry['x']},{driver_geometry['y']}"

            # Filter stops for the current driver
            assigned_stops = [
                f"{feature.geometry['x']},{feature.geometry['y']}"
                for feature in stops_features
                if feature.attributes["name"] == driver_name
            ]

            if not assigned_stops:
                print(f"No stops assigned for {driver_name}. Skipping...")
                continue

            # Combine driver start location with assigned stops
            all_stops = [driver_start_point] + assigned_stops
            stops_param = ";".join(all_stops)

            # Log the stops sequence being sent to the API
            print(f"\nDriver: {driver_name}")
            print(f"Stops Parameter: {stops_param}")

            # Query parameters
            params = {
                "f": "json",
                "token": access_token,
                "stops": stops_param,
                "useTraffic": "true", 
                "startTime": "now",
                "returnDirections": "false",
                "returnStops": "true",
                "findBestSequence": "true", 
                "returnToStart": "false",
                "impedanceAttribute": "time",
                "preserveFirstStop": "false",
                "preserveLastStop": "false"
            }

            # Log the full request being sent
            print(f"Request Parameters for {driver_name}: {json.dumps(params, indent=2)}")

            # Make the GET request
            try:
                response = requests.get(route_service_url, params=params)
                response.raise_for_status()

                # Parse the JSON response
                response_json = response.json()
                logging.debug(f"Response JSON for {driver_name}: {response_json}")

                # Check for valid stops
                if "stops" in response_json and "features" in response_json["stops"]:

                    # Generate Google Maps URL
                    coordinates_for_url = [f"{feature['geometry']['y']},{feature['geometry']['x']}" for feature in response_json["stops"]["features"]]
                    google_maps_base_url = "https://www.google.com/maps/dir/"
                    google_maps_url = google_maps_base_url + "/".join(coordinates_for_url)

                    # Print driver-specific URL
                    print(f"Google Maps URL for {driver_name}:")
                    print(google_maps_url)

                    # Write driver name and URL to CSV
                    csvwriter.writerow([driver_name, google_maps_url])

                else:
                    print(f"Failed to retrieve stops for {driver_name}: {response_json.get('error', {}).get('details', 'Unknown error')}")

            except requests.exceptions.RequestException as e:
                print(f"HTTP Request failed for {driver_name}: {e}")
            except Exception as e:
                print(f"An error occurred for {driver_name}: {e}")

    else:
        print("No layers found in the specified items.")

print(f"Driver routes saved to '{output_filename}'")
​&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 19 Jan 2025 12:36:28 GMT</pubDate>
      <guid>https://community.esri.com/t5/arcgis-rest-apis-and-services-questions/esri-routing-service-request-not-optimising/m-p/1577068#M4919</guid>
      <dc:creator>TrisKent</dc:creator>
      <dc:date>2025-01-19T12:36:28Z</dc:date>
    </item>
  </channel>
</rss>

