Select to view content in your preferred language

Esri Routing service request not optimising

152
0
01-19-2025 04:36 AM
Labels (1)
TrisKent
Emerging Contributor
Hi im trying to optimise a route in a test scenario.
I have a drive location and some stops.
my script gets the multiple driver locations and stops into the request with the driver location being first.
then i get the result for each driver.
the result is then passed into a url in the order it is recieved from the request in a csv

using this url below and authenticating using a web connection (cliend id and secret )https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve

These are the parameters I'm sending, i'm finding that no matter 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"
 
here are the parameters 

Stops Parameter: 152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996
Request Parameters for stops: {
  "f": "json",
  "token": "xyzxyzx", (removed)
  "stops": "152.88844866600004,-27.55606990399997;152.9154993647696,-27.55711911755536;152.94965997832725,-27.557727861245567;152.8859595770001,-27.56771165699996",
  "useTraffic": "true",
  "startTime": "now",
  "returnDirections": "false",
  "returnStops": "true",
  "findBestSequence": "true",
  "returnToStart": "false",
  "impedanceAttribute": "time",
  "preserveFirstStop": "false",
  "preserveLastStop": "false"
}


here is the result in google 
2-36 Lather Rd, Bellbowrie QLD 4070 to Weekes Rd, Bellbowrie QLD 4070 - Google Maps you can see its not in a good order

here is my code

 

 

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}'")

 



 

0 Kudos
0 Replies