首頁 > 後端開發 > Python教學 > 如何使用 TomTom Maps API 建立多站路線優化應用程式

如何使用 TomTom Maps API 建立多站路線優化應用程式

WBOY
發布: 2024-08-14 18:50:02
原創
318 人瀏覽過

本文將引導您使用 TomTom Maps API 建立乘車請求應用程式。該應用程式將允許用戶輸入多個上車和下車地點,計算最佳路線並將其顯示在地圖上。我們將涵蓋從獲取 API 金鑰到在地圖上渲染優化路線的所有內容。

第 1 步:設定 TomTom API
在深入研究程式碼之前,您需要在 TomTom 開發人員入口網站上註冊並取得 API 金鑰。此密鑰將允許您存取 TomTom 的服務,例如路線、地理編碼和地圖。

第 2 步:實現乘車請求功能
該應用程式的核心包括收集地址、將其轉換為座標併計算最佳路線。具體方法如下:

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})
登入後複製

在此程式碼片段中,應用程式接受多個位址的使用者輸入,使用 get_coordinates 函數將這些位址轉換為座標,並儲存資料以供日後使用。

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
登入後複製

第三步:計算最佳化路線
獲得座標後,下一步就是計算最佳化路線。 TomTom 的路點最佳化 API 有助於確定多個點之間最有效的路徑。

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
登入後複製

此函數向 TomTom API 發送請求,接收路徑點的最佳化順序,然後計算路線幾何形狀。

第 4 步:渲染地圖與路線
最後,在獲得優化的路線資料後,是時候在 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>
登入後複製

此 HTML 程式碼初始化 TomTom 地圖,在上車點和下車點放置標記,並繪製它們之間的路線。

結果:乘車申請表和成功地圖

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

注意:上面提供的程式碼是一個簡化的範例,用於示範使用 TomTom 的 API 叫車和計算路線的基本功能。實際的實作可能有所不同,並包括基於特定要求的附加功能或變更。更多詳細資訊和進階使用方法,請參考 TomTom 官方開發者文件。

以上是如何使用 TomTom Maps API 建立多站路線優化應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板