-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
159 lines (140 loc) · 5.56 KB
/
script.js
File metadata and controls
159 lines (140 loc) · 5.56 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
const mapApp = () => {
const accessToken = "pk.eyJ1IjoidHJhdmVucyIsImEiOiJjbDB6YngxZXAwam92M2Jtb3g3bWlzZnUxIn0.BKOufMZPrYPBuVek7uR7pQ";
return {
newDestination: "",
destinations: [],
suggestions: [],
map: null, // Store the map instance
markers: [], // Store markers
routeControl: null, // for storing the routing control
initMap() {
// Set initial view to Jakarta
this.map = L.map("map").setView([-6.2088, 106.8456], 13);
L.tileLayer("https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
attribution: 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: "mapbox/streets-v11",
tileSize: 512,
zoomOffset: -1,
accessToken: accessToken,
}).addTo(this.map);
},
addDestination() {
if (this.newDestination) {
this.destinations.push(this.newDestination);
this.placeMarker(this.newDestination);
this.newDestination = "";
this.suggestions = [];
if (this.destinations.length > 1) {
this.drawRoute();
}
}
},
async drawRoute() {
// Remove the existing route control if it exists
if (this.routeControl && this.routeControl.remove) {
this.routeControl.remove();
this.routeControl = null;
}
const resolvedWaypoints = await this.resolveWaypoints();
if (resolvedWaypoints.length < 2) {
console.error("Insufficient valid waypoints for routing.");
return;
}
let customRouter = (waypoints, callback) => {
let url = "https://api.mapbox.com/directions/v5/mapbox/driving/";
url += waypoints.map((wp) => `${wp.latLng.lng},${wp.latLng.lat}`).join(";");
url += "?access_token=" + accessToken;
url += "&overview=full&geometries=geojson";
axios
.get(url)
.then((response) => {
let coordinates = response.data.routes[0].geometry.coordinates;
let latLngs = coordinates.map((coord) => L.latLng(coord[1], coord[0]));
let polyline = L.polyline(latLngs, { color: "blue" }).addTo(this.map);
this.map.fitBounds(polyline.getBounds());
callback(null, latLngs);
})
.catch((error) => {
console.error("Routing Error:", error);
callback(error, null);
});
};
// Initialize a new route control
this.routeControl = L.Routing.control({
waypoints: resolvedWaypoints,
routeWhileDragging: false,
router: { route: customRouter },
}).addTo(this.map);
},
async resolveWaypoints() {
const geocodedWaypoints = await Promise.all(
this.destinations.map(async (destination) => {
return await this.geocodeDestination(destination);
})
);
// Filter out any null waypoints
const validWaypoints = geocodedWaypoints.filter((wp) => wp !== null);
return validWaypoints;
},
// New method to geocode a destination
async geocodeDestination(destination) {
try {
const response = await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(destination)}.json?access_token=${accessToken}`);
const coords = response.data.features[0].center;
console.log(`Geocoded ${destination}:`, coords); // Log the coordinates
return L.latLng(coords[1], coords[0]); // Latitude, then Longitude
} catch (error) {
console.error("Error geocoding destination:", error);
return null;
}
},
async placeMarker(destination) {
try {
const response = await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(destination)}.json?access_token=${accessToken}`);
const coords = response.data.features[0].center;
const marker = L.marker([coords[1], coords[0]]).addTo(this.map);
marker.bindPopup(destination).openPopup();
this.markers.push(marker);
// Adjust map view to show all markers
if (this.markers.length > 1) {
const group = new L.featureGroup(this.markers);
this.map.fitBounds(group.getBounds());
}
} catch (error) {
console.error("Error placing marker:", error);
}
},
async fetchAutocomplete() {
if (this.newDestination.length >= 3) {
try {
const response = await axios.get(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(this.newDestination)}.json?access_token=pk.eyJ1IjoidHJhdmVucyIsImEiOiJjbDB6YngxZXAwam92M2Jtb3g3bWlzZnUxIn0.BKOufMZPrYPBuVek7uR7pQ&limit=5`
);
this.suggestions = response.data.features.map((item) => item.place_name);
} catch (error) {
console.error("Error fetching autocomplete suggestions:", error);
}
} else {
this.suggestions = [];
}
},
selectSuggestion(suggestion) {
this.newDestination = suggestion;
this.suggestions = [];
},
removeDestination(index) {
if (index >= 0 && index < this.destinations.length) {
this.destinations.splice(index, 1);
this.removeMarker(index); // Remove the corresponding marker from the map
this.drawRoute(); // Redraw the route with the updated destinations
}
},
removeMarker(index) {
if (index >= 0 && index < this.markers.length) {
this.map.removeLayer(this.markers[index]);
this.markers.splice(index, 1);
}
},
};
};