Advertisement
Guest User

rute_traffic

a guest
Feb 27th, 2025
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 8.57 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Interactive Route with Traffic Info</title>
  7.  
  8.     <!-- Include Leaflet.js -->
  9.     <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
  10.     <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
  11.  
  12.     <style>
  13.         #map {
  14.             width: 100%;
  15.             height: 500px;
  16.         }
  17.         body {
  18.             font-family: Arial, sans-serif;
  19.             margin: 0;
  20.             padding: 0;
  21.         }
  22.         #route-info {
  23.             margin: 10px;
  24.             padding: 10px;
  25.             background: #f9f9f9;
  26.             border: 1px solid #ccc;
  27.         }
  28.     </style>
  29. </head>
  30. <body>
  31.     <h1 style="text-align: center;">Interactive Route with Traffic Info</h1>
  32.     <div id="map"></div>
  33.     <div id="route-info">Click on the map to set start and end points.</div>
  34.  
  35.     <script>
  36.         const apiKey = 'Gixt05RAvLI57chTAGgMFzNaxcYAyigl'; // Your TomTom API Key
  37.  
  38.         // Initialize the map with OpenStreetMap as the base layer
  39.         const map = L.map('map').setView([-7.25, 112.75], 12); // Centered on Surabaya
  40.  
  41.         // Add OpenStreetMap tiles
  42.         L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  43.             attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  44.         }).addTo(map);
  45.  
  46.         let startPointMarker = null; // To store the start point marker
  47.         let endPointMarker = null;   // To store the end point marker
  48.         let routeLine = null;        // To store the route polyline
  49.  
  50.         // Define custom icons for start and end points
  51.         const startIcon = L.icon({
  52.             iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png',
  53.             iconSize: [25, 41],
  54.             iconAnchor: [12, 41],
  55.             popupAnchor: [1, -34]
  56.         });
  57.  
  58.         const endIcon = L.icon({
  59.             iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png',
  60.             iconSize: [25, 41],
  61.             iconAnchor: [12, 41],
  62.             popupAnchor: [1, -34]
  63.         });
  64.  
  65.         // Function to handle map clicks (for setting start and end points)
  66.         map.on('click', function (e) {
  67.             const latLng = e.latlng; // Get the latitude and longitude of the click
  68.  
  69.             if (!startPointMarker) {
  70.                 // First click: Set the start point
  71.                 startPointMarker = L.marker(latLng, { draggable: true, icon: startIcon }).addTo(map);
  72.                 startPointMarker.bindPopup('Start Point').openPopup();
  73.                 startPointMarker.on('dragend', updateRoute); // Update route when marker is dragged
  74.                 document.getElementById('route-info').innerHTML = `Start Point: ${latLng.lat.toFixed(5)}, ${latLng.lng.toFixed(5)}`;
  75.             } else if (!endPointMarker) {
  76.                 // Second click: Set the end point
  77.                 endPointMarker = L.marker(latLng, { draggable: true, icon: endIcon }).addTo(map);
  78.                 endPointMarker.bindPopup('End Point').openPopup();
  79.                 endPointMarker.on('dragend', updateRoute); // Update route when marker is dragged
  80.                 document.getElementById('route-info').innerHTML = `End Point: ${latLng.lat.toFixed(5)}, ${latLng.lng.toFixed(5)}`;
  81.  
  82.                 // Fetch and display the route
  83.                 fetchRoute(startPointMarker.getLatLng(), endPointMarker.getLatLng());
  84.             } else {
  85.                 // Reset if both points are already set
  86.                 resetMarkers();
  87.                 startPointMarker = L.marker(latLng, { draggable: true, icon: startIcon }).addTo(map);
  88.                 startPointMarker.bindPopup('Start Point').openPopup();
  89.                 startPointMarker.on('dragend', updateRoute);
  90.                 document.getElementById('route-info').innerHTML = `Start Point: ${latLng.lat.toFixed(5)}, ${latLng.lng.toFixed(5)}`;
  91.             }
  92.         });
  93.  
  94.         // Function to reset markers and route
  95.         function resetMarkers() {
  96.             if (startPointMarker) {
  97.                 map.removeLayer(startPointMarker);
  98.                 startPointMarker = null;
  99.             }
  100.             if (endPointMarker) {
  101.                 map.removeLayer(endPointMarker);
  102.                 endPointMarker = null;
  103.             }
  104.             if (routeLine) {
  105.                 map.removeLayer(routeLine);
  106.                 routeLine = null;
  107.             }
  108.             document.getElementById('route-info').innerHTML = 'Click on the map to set start and end points.';
  109.         }
  110.  
  111.         // Function to update the route when markers are moved
  112.         async function updateRoute() {
  113.             if (startPointMarker && endPointMarker) {
  114.                const startLatLng = startPointMarker.getLatLng();
  115.                 const endLatLng = endPointMarker.getLatLng();
  116.                 await fetchRoute(startLatLng, endLatLng);
  117.             }
  118.         }
  119.  
  120.         // Function to fetch the route using TomTom Routing API
  121.         async function fetchRoute(start, end) {
  122.             const url = `https://api.tomtom.com/routing/1/calculateRoute/${start.lat},${start.lng}:${end.lat},${end.lng}/json?key=${apiKey}&traffic=true`;
  123.            
  124.             //const url = `https://api.tomtom.com/routing/1/calculateRoute/${start.lat},${start.lng}:${end.lat},${end.lng}/json?key=${apiKey}&traffic=true`;
  125.  
  126.             try {
  127.                 const response = await fetch(url);
  128.                 if (!response.ok) {
  129.                     throw new Error(`Error fetching route: HTTP ${response.status}`);
  130.                 }
  131.  
  132.                 const data = await response.json();
  133.                 console.log('Full API Response:', data); // Log the full response
  134.  
  135.                 // Check if the response contains valid route data
  136.                 if (!data.routes || !data.routes[0] || !data.routes[0].legs || !data.routes[0].legs[0]) {
  137.                     throw new Error('Invalid route data received from the API.');
  138.                 }
  139.  
  140.                 // Extract route information
  141.                 const route = data.routes[0];
  142.                 const summary = route.summary;
  143.                 const distance = (summary.lengthInMeters / 1000).toFixed(2); // Convert meters to kilometers
  144.                 const travelTime = Math.ceil(summary.travelTimeInSeconds / 60); // Convert seconds to minutes
  145.                 const trafficDelay = Math.ceil(summary.trafficDelayInSeconds / 60); // Convert seconds to minutes
  146.  
  147.                 // Display route information
  148.                 document.getElementById('route-info').innerHTML = `
  149.                     <strong>Route Summary:</strong><br>
  150.                     Distance: ${distance} km<br>
  151.                     Estimated Travel Time: ${travelTime} minutes<br>
  152.                     Traffic Delay: ${trafficDelay} minutes
  153.                 `;
  154.  
  155.                 // Extract route geometry
  156.                 const coordinates = route.legs[0].points.map(point => [point.latitude, point.longitude]);
  157.  
  158.                 // Determine overall route color based on traffic delay
  159.                 const routeColor = getRouteColor(trafficDelay);
  160.  
  161.                 // Draw the route on the map
  162.                 if (routeLine) {
  163.                     map.removeLayer(routeLine); // Remove the previous route
  164.                 }
  165.                 routeLine = L.polyline(coordinates, {
  166.                     color: routeColor,
  167.                     weight: 5
  168.                 }).addTo(map);
  169.  
  170.                 // Add a popup to the route with traffic info
  171.                 routeLine.bindPopup(`
  172.                     <strong>Traffic Info:</strong><br>
  173.                     Distance: ${distance} km<br>
  174.                     Estimated Travel Time: ${travelTime} minutes<br>
  175.                     Traffic Delay: ${trafficDelay} minutes
  176.                 `);
  177.  
  178.                 // Adjust the map view to fit the route
  179.                 map.fitBounds(L.latLngBounds(coordinates));
  180.             } catch (error) {
  181.                 console.error('Error fetching route:', error);
  182.                 document.getElementById('route-info').innerHTML = 'Failed to load route information.';
  183.             }
  184.         }
  185.  
  186.         // Function to determine the route color based on traffic delay
  187.         function getRouteColor(trafficDelay) {
  188.             if (trafficDelay === 0) return '#28a745'; // Green: No traffic delay
  189.             if (trafficDelay <= 5) return '#ffc107'; // Yellow: Moderate delay
  190.            return '#dc3545'; // Red: Heavy delay
  191.        }
  192.    </script>
  193. </body>
  194. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement