Home Backend Development Python Tutorial How to Create a Multi-Stop Route Optimization Application with TomTom Maps API

How to Create a Multi-Stop Route Optimization Application with TomTom Maps API

Aug 14, 2024 pm 06:50 PM

This post will walk you through creating a ride-a-request application using TomTom Maps API. This application will allow users to input multiple pick-up and drop-off locations, calculate the optimal route, and display it on a map. We’ll cover everything from obtaining the API key to rendering the optimized route on a map.

Step 1: Setting Up TomTom API
Before diving into the code, you’ll need to sign up on the TomTom Developer Portal and obtain an API key. This key will allow you to access TomTom’s services such as routing, geocoding, and maps.

Step 2: Implementing the Ride Request Functionality
The core of the application involves collecting addresses, converting them to coordinates, and calculating the optimal route. Here’s how you can do it:

def ride_request(request):
    if request.method == 'POST':
        form = RideForm(request.POST)
        if form.is_valid():
            ride = form.save(commit=False)
            # Get coordinates for the pickup and drop locations
            pickup_coords = get_coordinates(ride.pickup_address)
            pickup_coords_1 = get_coordinates(ride.pickup_address_1)
            pickup_coords_2 = get_coordinates(ride.pickup_address_2)
            drop_coords = get_coordinates(ride.drop_address)

            # Ensure all coordinates are available
            if all([pickup_coords, pickup_coords_1, pickup_coords_2, drop_coords]):
                # Set the coordinates
                ride.pickup_latitude, ride.pickup_longitude = pickup_coords
                ride.pickup_latitude_1, ride.pickup_longitude_1 = pickup_coords_1
                ride.pickup_latitude_2, ride.pickup_longitude_2 = pickup_coords_2
                ride.drop_latitude, ride.drop_longitude = drop_coords

                # Save the ride and redirect to the success page
                try:
                    ride.save()
                    return redirect('success_page', pickup_lon=ride.pickup_longitude, pickup_lat=ride.pickup_latitude,
                                    pickup_lon_1=ride.pickup_longitude_1, pickup_lat_1=ride.pickup_latitude_1,
                                    pickup_lon_2=ride.pickup_longitude_2, pickup_lat_2=ride.pickup_lat_2,
                                    drop_lon=ride.drop_longitude, drop_lat=ride.drop_latitude)
                except IntegrityError as e:
                    messages.error(request, f'IntegrityError: {str(e)}')
            else:
                messages.error(request, 'Error getting coordinates. Please try again.')
    else:
        form = RideForm()

    return render(request, 'maps/ride_request.html', {'form': form})
Copy after login

In this snippet, the application accepts user input for multiple addresses, converts these addresses into coordinates using the get_coordinates function, and saves the data for later use.

def get_coordinates(address):
    """
    Get coordinates (latitude, longitude) for a given address using TomTom Geocoding API.
    """
    api_key = 'YOUR_TOMTOM_API_KEY'
    base_url = 'https://api.tomtom.com/search/2/geocode/{address}.json'

    # Prepare the URL with the address and API key
    url = base_url.format(address=address)
    params = {'key': api_key}

    # Make the request to TomTom Geocoding API
    response = requests.get(url, params=params)
    data = response.json()

    # Check if the request was successful
    if response.status_code == 200 and data.get('results'):
        # Extract coordinates from the response
        result = data['results'][0]
        if 'position' in result:
            coordinates = result['position']
            return coordinates.get('lat'), coordinates.get('lon')
        else:
            print(
                f"Error getting coordinates for {address}: 'position' key not found in the response.")
            return None
    else:
        # Handle errors or return a default value
        print(
            f"Error getting coordinates for {address}: {data.get('message')}")
        return None
Copy after login

Step 3: Calculating the Optimized Route
Once you have the coordinates, the next step is to calculate the optimized route. TomTom’s Waypoint Optimization API helps in determining the most efficient path between multiple points.

def get_optimized_route(*pickup_coords, drop_coords):
    api_key = 'YOUR_TOMTOM_API_KEY'

    # Prepare the payload for the API
    payload = {
        'waypoints': [{'point': {'latitude': lat, 'longitude': lon}} for lon, lat in pickup_coords],
        'options': {'travelMode': 'car'},
    }

    # Add the drop location to the waypoints
    payload['waypoints'].append({'point': {'latitude': drop_coords[1], 'longitude': drop_coords[0]}})

    # API request
    response = requests.post(f'https://api.tomtom.com/routing/waypointoptimization/1',
                             params={'key': api_key},
                             json=payload)

    if response.status_code == 200:
        data = response.json()
        if 'optimizedOrder' in data:
            # Extract the optimized route
            return [get_route_geometry(pickup_coords[i], pickup_coords[j]) 
                    for i, j in zip(data['optimizedOrder'], data['optimizedOrder'][1:])]
    return None
Copy after login

This function sends a request to the TomTom API, receives the optimized order of waypoints, and then calculates the route geometry.

Step 4: Rendering the Map and Route
Finally, after obtaining the optimized route data, it’s time to render the map on your success_page.html.

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ride Request - Success</title>
    <link rel="stylesheet" href="{% static 'maps/css/styles.css' %}">
    <!-- Include TomTom Map SDK -->
    <link rel="stylesheet" type="text/css"
        href="https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.25.0/maps/maps.css" />
    <script type="text/javascript"
        src="https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.25.0/maps/maps-web.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="map-container" id="dynamic-map"></div>
    </div>
    <!-- Map Initialization Script -->
    <script type="text/javascript">
        var map;
        var pickup_lon = {{ pickup_lon }};
        var pickup_lat = {{ pickup_lat }};
        var pickup_lon_1 = {{ pickup_lon_1 }};
        var pickup_lat_1 = {{ pickup_lat_1 }};
        var pickup_lon_2 = {{ pickup_lon_2 }};
        var pickup_lat_2 = {{ pickup_lat_2 }};
        var drop_lon = {{ drop_lon }};
        var drop_lat = {{ drop_lat }};
        var routeGeometry = {{ route_data.route_geometry| safe }};
        var geomatryCoordinates = routeGeometry.geometry.coordinates;
        const API_KEY = 'YOUR_TOMTOM_API_KEY';

        function initMap() {
            //let center = [(pickup_lat + drop_lat) / 2, (pickup_lon + drop_lon) / 2];
            let center = [pickup_lon, pickup_lat];
            console.log('center:', center)
            map = tt.map({
                key: API_KEY,
                container: 'dynamic-map',
                //stylesVisibility: {
                //  trafficIncidents: true
                //},
                center: center,
                bearing: 0,
                maxZoom: 21,
                minZoom: 1,
                pitch: 60,
                zoom: 12,
                //style: `https://api.tomtom.com/style/1/style/*?map=2/basic_street-satellite&poi=2/poi_dynamic-satellite&key=${API_KEY}`
            });
            map.addControl(new tt.FullscreenControl());
            map.addControl(new tt.NavigationControl());
            map.on('load', () => {
                console.log('Map loaded successfully!');

                // Add markers for all pickup locations and drop location
                var pickupMarker = new tt.Marker({ color: 'green' }).setLngLat([pickup_lon, pickup_lat]).addTo(map);
                var pickupMarker1 = new tt.Marker({ color: 'blue' }).setLngLat([pickup_lon_1, pickup_lat_1]).addTo(map);
                var pickupMarker2 = new tt.Marker({ color: 'orange' }).setLngLat([pickup_lon_2, pickup_lat_2]).addTo(map);
                var dropMarker = new tt.Marker({ color: 'red' }).setLngLat([drop_lon, drop_lat]).addTo(map);

                try {
                    // Iterate through each set of coordinates and add route layer
                    geomatryCoordinates.forEach((coordinates, index) => {
                        var routeGeometry = {
                            type: 'Feature',
                            geometry: {
                                type: 'LineString',
                                coordinates: coordinates,
                            },
                        };

                        // Check if the routeGeometry is a valid GeoJSON object
                        if (isValidGeoJSON(routeGeometry)) {
                            map.addLayer({
                                'id': `route-${index}`,
                                'type': 'line',
                                'source': {
                                    'type': 'geojson',
                                    'data': routeGeometry,
                                },
                                'layout': {
                                    'line-join': 'round',
                                    'line-cap': 'round',
                                },
                                'paint': {
                                    'line-color': '#3887be',
                                    'line-width': 8,
                                    'line-opacity': 0.8,
                                },
                            });
                            console.log(`Route layer ${index} added successfully!`);
                        } else {
                            console.error(`Invalid GeoJSON format for route ${index}. Creating a simple LineString.`);

                            // Attempt to create a LineString GeoJSON
                            var simpleRouteGeometry = {
                                type: 'Feature',
                                geometry: {
                                    type: 'LineString',
                                    coordinates: coordinates,
                                },
                            };

                            map.addLayer({
                                'id': `route-${index}`,
                                'type': 'line',
                                'source': {
                                    'type': 'geojson',
                                    'data': simpleRouteGeometry,
                                },
                                'layout': {
                                    'line-join': 'round',
                                    'line-cap': 'round',
                                },
                                'paint': {
                                    'line-color': '#3887be',
                                    'line-width': 8,
                                    'line-opacity': 0.8,
                                },
                            });
                            console.log(`Route layer ${index} added successfully with new GeoJSON.`);
                        }
                    });
                } catch (error) {
                    console.error('Error handling GeoJSON:', error);
                }

        function isValidGeoJSON(data) {
            return typeof data === 'object' && data !== null && data.type === 'Feature';
        }
        initMap();  // Call the initMap function
    </script>
</body>
</html>
Copy after login

This HTML code initializes the TomTom map, places markers on the pickup and drop-off points, and draws the route between them.

Result: Ride Request Form & Success Map

How to Create a Multi-Stop Route Optimization Application with TomTom Maps API

How to Create a Multi-Stop Route Optimization Application with TomTom Maps API

Note: The code provided above is a simplified example to demonstrate the basic functionality of requesting a ride and calculating routes using TomTom’s API. The actual implementation may differ and include additional features or variations based on specific requirements. For more detailed information and advanced usage, please refer to the official TomTom Developer Documentation.

The above is the detailed content of How to Create a Multi-Stop Route Optimization Application with TomTom Maps API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

See all articles