-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
81 lines (67 loc) · 2.76 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const inputJourney = document.querySelector(".input_journey");
const submit = document.getElementById("submit");
const output = document.querySelector(".output");
submit.addEventListener("click", (e) => {
e.preventDefault();
const fromLocation = document.getElementById("from").value;
const toLocation = document.getElementById("to").value;
localStorage.setItem("from", fromLocation);
localStorage.setItem("to", toLocation);
inputJourney.style.display = "none";
output.style.display = "block";
alert("Finding the best and optimized route...");
geocodeLocation(fromLocation, (fromGeocode) => {
console.log("From Geocode: ", fromGeocode);
geocodeLocation(toLocation, (toGeocode) => {
console.log("To Geocode: ", toGeocode);
fetch('http://127.0.0.1:5000/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: { lat: fromGeocode.lat, lng: fromGeocode.lng },
to: { lat: toGeocode.lat, lng: toGeocode.lng }
})
})
.then(response => response.json())
.then(data => {
if (data.status === "OK") {
initMap(data.route);
} else {
alert("Could not find the route: " + data.message);
}
})
.catch(error => alert("Error: " + error));
});
});
});
function geocodeLocation(location, callback) {
const url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location)}`;
fetch(url)
.then(response => response.json())
.then(data => {
if (data && data.length > 0) {
const geocode = { lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) };
callback(geocode);
} else {
alert("Location not found for: " + location);
}
})
.catch(error => {
alert("Geocoding error: " + error);
});
}
function initMap(route) {
const map = L.map('map').setView([route[0].lat, route[0].lng], 13);
// Add OpenStreetMap tiles
L.tileLayer('https://api.maptiler.com/tiles/satellite-mediumres/?key=KqZnOLSUd6AO3nx6HZLN#2.5774288280357487/0/0', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Map route points
const latlngs = route.map(point => [point.lat, point.lng]);
// Draw the route as a polyline
const polyline = L.polyline(latlngs, { color: 'blue', weight: 4 }).addTo(map);
// Adjust the map view to fit the route
map.fitBounds(polyline.getBounds());
}