Skip to content

Automated route calculation using the MapQuest Directions API for logistics, network path analysis, and IoT tracking. Easily fetch optimized routes, travel times, and distance metrics.

Notifications You must be signed in to change notification settings

Zhenyaof/Route-Automation-with-MapQuest-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 

Repository files navigation

Route Automation with MapQuest API

Overview

This project demonstrates how to integrate the MapQuest Directions API to automate route calculations between two locations. It is particularly useful for network engineers working on logistics, network path analysis, and IoT tracking applications. By leveraging the API, users can retrieve optimized routes, estimated travel times, and distance metrics, enabling efficient decision-making in various network-related scenarios.

Features

  • Automated Route Calculation: Fetch the shortest or fastest route between two locations.
  • Real-time Data: Retrieve up-to-date traffic and distance metrics.
  • Customizable Parameters: Adjust route preferences such as avoiding tolls, highways, or specific areas.
  • JSON Response Parsing: Extract and utilize key information from the API response.
  • Scalable Integration: Suitable for larger applications in logistics and network optimization.

Use Cases

  • Logistics & Fleet Management: Optimize delivery routes and reduce transportation costs.
  • Network Path Analysis: Model real-world routing scenarios for network engineering.
  • IoT Applications: Track moving assets and devices efficiently.

Technologies Used

  • Python for scripting and API calls
  • Requests Library for handling HTTP requests
  • MapQuest Directions API for route calculations

Prerequisite

To use this project, you need to obtain an API key from the MapQuest Developer Website. Sign up for a free account, generate an API key, and use it in the script.


Code Implementation

import requests

def get_trip_info(api_key, origin, destination):
    """Fetches route details between two locations using the MapQuest API."""
    url = "https://www.mapquestapi.com/directions/v2/route"
    params = {
        "key": api_key,
        "from": origin,
        "to": destination
    }
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()  # Raises an error for unsuccessful requests
        return response.json()
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error: {conn_err}")
    except requests.exceptions.Timeout as timeout_err:
        print(f"Request timed out: {timeout_err}")
    except requests.exceptions.RequestException as err:
        print(f"An error occurred: {err}")
    return None

def display_trip_info(data):
    """Displays trip details like duration, distance, and directions."""
    if data is None:
        print("No data received from API. Check your API key and internet connection.")
        return
    
    if data.get("info", {}).get("statuscode") == 0:
        route = data["route"]
        print(f"Trip Duration: {route.get('formattedTime', 'N/A')}")
        print(f"Distance: {route.get('distance', 0):.2f} miles")
        print(f"Fuel Used: {route.get('fuelUsed', 0):.2f} gallons")
        print("\nDirections:")
        for leg in route.get("legs", []):
            for maneuver in leg.get("maneuvers", []):
                print(maneuver.get("narrative", "No narrative provided."))
    else:
        print("Error: Invalid input or route not found.")
        print(f"Detailed error info: {data}")

def main():
    """Handles user input and initiates API calls."""
    api_key = input("Enter your MapQuest API Key: ").strip()
    while True:
        origin = input("Enter the starting location (or type 'quit' to exit): ").strip()
        if origin.lower() == 'quit':
            break
        destination = input("Enter the destination (or type 'quit' to exit): ").strip()
        if destination.lower() == 'quit':
            break
        data = get_trip_info(api_key, origin, destination)
        display_trip_info(data)

if __name__ == "__main__":
    main()

Detailed Code Breakdown

1. Importing Dependencies

import requests
  • The requests module is used to send HTTP requests to the MapQuest API.

2. Fetching Trip Information (get_trip_info)

def get_trip_info(api_key, origin, destination):
  • Defines a function that takes an API key, origin, and destination as parameters.
  • This function makes a request to MapQuest API to retrieve trip details.
url = "https://www.mapquestapi.com/directions/v2/route"
params = {
    "key": api_key,
    "from": origin,
    "to": destination
}
  • Specifies the API endpoint and prepares query parameters to send in the request.
response = requests.get(url, params=params, timeout=10)
  • Sends a GET request with the API key, origin, and destination.
  • Uses a timeout of 10 seconds to prevent indefinite waiting.
response.raise_for_status()
  • Checks for HTTP errors (like 404 Not Found, 500 Server Error).
return response.json()
  • Returns the JSON response from the API if successful.

3. Handling Errors

except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
  • Catches errors related to HTTP responses, such as 404 or 500.
except requests.exceptions.ConnectionError as conn_err:
    print(f"Connection error: {conn_err}")
  • Handles issues like network disconnections.
except requests.exceptions.Timeout as timeout_err:
    print(f"Request timed out: {timeout_err}")
  • Handles slow API responses.

4. Displaying Trip Information (display_trip_info)

def display_trip_info(data):
  • Extracts trip duration, distance, fuel usage, and directions.
  • Handles cases where API returns an error.
if data.get("info", {}).get("statuscode") == 0:
  • Ensures that the API response is valid.
for leg in route.get("legs", []):
    for maneuver in leg.get("maneuvers", []):
        print(maneuver.get("narrative", "No narrative provided."))
  • Loops through route legs and maneuvers to print step-by-step directions.

5. User Interaction (main)

def main():
  • Collects user input for API key, origin, and destination.
  • Allows the user to enter multiple locations or type quit to exit.

6. Running the Script

if __name__ == "__main__":
    main()
  • Ensures the script runs only when executed directly, not when imported as a module.

How to Use

  1. Install dependencies (if not installed):
    pip install requests
  2. Run the script:
    python script.py
  3. Enter your MapQuest API Key.
  4. Provide Origin and Destination to get trip details.

Future Enhancements

  • Add Google Maps API support.
  • Implement GUI with Tkinter or Flask API.
  • Include real-time traffic conditions

Output

Here’s an example of what the output might look like when running the script:

Enter your MapQuest API Key: your-api-key
Enter the starting location (or type 'quit' to exit): New York, NY
Enter the destination (or type 'quit' to exit): Boston, MA
Trip Duration: 3 hours 45 minutes
Distance: 215.50 miles
Fuel Used: 8.23 gallons

Directions:
Start out going east on I-95 N.
Take exit 46 for Route 1.
...




About

Automated route calculation using the MapQuest Directions API for logistics, network path analysis, and IoT tracking. Easily fetch optimized routes, travel times, and distance metrics.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages