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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
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.

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 vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

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 for Scientific Computing: A Detailed Look Python for Scientific Computing: A Detailed Look Apr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

See all articles