Hi, I’m trying to use the route optimization endpoint, but despite setting “geometry”: True, I don’t see it returning the geometry to draw the route on the map or the distance. Here’s the Python code.
(Buenas, estoy intentando utilizar el endpoint de optimizacion de rutas, pero a pesar de pasarle como opcion “geometry”: True, no veo que me devuelva la geometria para pintar la ruta en el mapa ni la distancia. Os paso el codigo en Python.)
import requests
import json
import os
import certifi # Importa certifi para la verificación SSL
# 1. Configuración
# Intenta obtener la API key de una variable de entorno
ORS_API_KEY = os.environ.get('ORS_API_KEY', 'TU_CLAVE_API_DE_OPENROUTESERVICE')
ORS_API_BASE_URL = 'https://api.openrouteservice.org'
OPTIMIZATION_ENDPOINT = '/optimization' # <-- ¡El endpoint correcto!
# Verifica que la API key esté configurada
if ORS_API_KEY == 'TU_CLAVE_API_DE_OPENROUTESERVICE':
print("Error: La clave API de OpenRouteService no está configurada.")
print("Configúrala como variable de entorno 'ORS_API_KEY' o reemplaza el valor por defecto.")
exit()
# 2. Datos de la Solicitud (Ejemplo simple)
# Coordenadas en formato [longitud, latitud]
# Parada 1: Heidelberg Castle
# Parada 2: Market Square Heidelberg
# Parada 3: Old Bridge Heidelberg
payload = {
"jobs": [
{"id": 0, "location": [8.7100, 49.4115]}, # Heidelberg Castle (Job 0)
{"id": 1, "location": [8.7093, 49.4123]}, # Market Square (Job 1)
{"id": 2, "location": [8.7119, 49.4128]} # Old Bridge (Job 2)
],
"vehicles": [
{
"id": 0, # ID del vehículo
"profile": "driving-car", # Perfil de ruta
"start": [8.7100, 49.4115], # Inicio en Job 0 (Heidelberg Castle)
"end": [8.7119, 49.4128] # Fin en Job 2 (Old Bridge)
# "time_window": [inicio_segundos, fin_segundos] # Opcional: ventana de tiempo
}
],
"options": {
"geometry": True # ¡Importante para obtener la geometría de la ruta!
}
}
# 3. Cabeceras de la Solicitud
headers = {
'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
'Authorization': ORS_API_KEY,
'Content-Type': 'application/json; charset=utf-8'
}
# 4. Realizar la Llamada POST
print(f"Llamando a: {ORS_API_BASE_URL}{OPTIMIZATION_ENDPOINT}")
try:
response = requests.post(
f"{ORS_API_BASE_URL}{OPTIMIZATION_ENDPOINT}",
headers=headers,
json=payload,
timeout=30, # Tiempo de espera razonable
# Es MUY recomendable usar la verificación SSL
# verify=True usa los certificados del sistema
# verify=certifi.where() usa el paquete certifi (más portable)
verify=False
# NUNCA uses verify=False en producción, es inseguro.
)
# Verificar si hubo errores HTTP (4xx o 5xx)
response.raise_for_status() # Lanza una excepción si el estado no es 2xx
# 5. Procesar la Respuesta Exitosa
optimization_result = response.json()
print("\n--- Respuesta Exitosa de ORS Optimization ---")
# Imprimir de forma legible el JSON resultante
print(json.dumps(optimization_result, indent=2))
# Ejemplo de cómo acceder a datos específicos:
if optimization_result and 'routes' in optimization_result and optimization_result['routes']:
route = optimization_result['routes'][0]
print(f"\nResumen de la Ruta Optimizada:")
print(f" Vehículo: {route.get('vehicle')}")
print(f" Distancia: {route.get('distance')} metros")
print(f" Duración: {route.get('duration')} segundos")
print(f" Pasos (orden de visita):")
for step in route.get('steps', []):
step_type = step.get('type')
location = step.get('location')
job_id = step.get('id', 'N/A') # Solo para tipo 'job'
arrival = step.get('arrival')
departure = step.get('departure')
if step_type == 'start':
print(f" - Inicio en {location} a las {departure}s")
elif step_type == 'job':
print(f" - Visitar Job ID {job_id} en {location} (Llegada: {arrival}s, Salida: {departure}s)")
elif step_type == 'end':
print(f" - Fin en {location} a las {arrival}s")
# La geometría estará en route['geometry'] si options.geometry fue True
except requests.exceptions.HTTPError as http_err:
print(f"\n--- Error HTTP ---")
print(f"Status Code: {http_err.response.status_code}")
print(f"Razón: {http_err.response.reason}")
# Intentar mostrar el cuerpo del error si es JSON
try:
error_details = http_err.response.json()
print("Detalles del Error (JSON):")
print(json.dumps(error_details, indent=2))
except json.JSONDecodeError:
print("Detalles del Error (Texto):")
print(http_err.response.text)
except requests.exceptions.SSLError as ssl_err:
print(f"\n--- Error SSL ---")
print(f"No se pudo verificar el certificado SSL: {ssl_err}")
print("Asegúrate de que tu sistema confía en los certificados usados por OpenRouteService o que 'certifi' está actualizado.")
except requests.exceptions.RequestException as req_err:
print(f"\n--- Error de Conexión/Red ---")
print(f"No se pudo conectar a OpenRouteService: {req_err}")
except Exception as e:
print(f"\n--- Ocurrió un Error Inesperado ---")
print(e)
respuesta
{
"code": 0,
"summary": {
"cost": 863,
"routes": 1,
"unassigned": 0,
"setup": 0,
"service": 0,
"duration": 863,
"waiting_time": 0,
"priority": 0,
"violations": [],
"computing_times": {
"loading": 69,
"solving": 1,
"routing": 0
}
},
"unassigned": [],
"routes": [
{
"vehicle": 0,
"cost": 863,
"setup": 0,
"service": 0,
"duration": 863,
"waiting_time": 0,
"priority": 0,
"steps": [
{
"type": "start",
"location": [
8.71,
49.4115
],
"setup": 0,
"service": 0,
"waiting_time": 0,
"arrival": 0,
"duration": 0,
"violations": []
},
{
"type": "job",
"location": [
8.71,
49.4115
],
"id": 0,
"setup": 0,
"service": 0,
"waiting_time": 0,
"job": 0,
"arrival": 0,
"duration": 0,
"violations": []
},
{
"type": "job",
"location": [
8.7093,
49.4123
],
"id": 1,
"setup": 0,
"service": 0,
"waiting_time": 0,
"job": 1,
"arrival": 623,
"duration": 623,
"violations": []
},
{
"type": "job",
"location": [
8.7119,
49.4128
],
"id": 2,
"setup": 0,
"service": 0,
"waiting_time": 0,
"job": 2,
"arrival": 863,
"duration": 863,
"violations": []
},
{
"type": "end",
"location": [
8.7119,
49.4128
],
"setup": 0,
"service": 0,
"waiting_time": 0,
"arrival": 863,
"duration": 863,
"violations": []
}
],
"violations": []
}
]
}