This repository was archived by the owner on Sep 22, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmap.js
More file actions
323 lines (246 loc) · 8.9 KB
/
Copy pathmap.js
File metadata and controls
323 lines (246 loc) · 8.9 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
let suggestionsView = document.querySelector(".suggestions");
let startLocationName = ""
let endLocationName = ""
let startInputBox = document.querySelector(".start-input-location")
let endInputBox = document.querySelector(".end-input-location")
function resetMapView(){
try {
startInputBox.value = "";
endInputBox.value = "";
if(startMarker) startMarker.remove()
if(endMarker) endMarker.remove()
if(routeLayer) map.removeLayer("route");
}
catch(error){
console.log(error)
}
}
let newID = generateUUID();
mapboxgl.accessToken = 'pk.eyJ1IjoiaWJyYWhpbWFtZTEzIiwiYSI6ImNsb2xlaDUxbDJlcXYya3A5bzZoZWc5MzkifQ.YyKfquv1mvX7xrUj5oG1Ow';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/mapbox/streets-v12', // style URL
center: [33.321258,35.212448], // starting position [lng, lat]
pitch: 60,
bearing: -60,
zoom: 10
});
let source;
let destination;
let startMarker;
let endMarker;
async function getRoute(start, end) {
if(startMarker) startMarker.remove()
if(endMarker) endMarker.remove()
// Set marker options.
endMarker = new mapboxgl.Marker({
color: "#FFFFFF",
draggable: true
})
.setLngLat(end)
.setPopup(new mapboxgl.Popup().setHTML("<h1>Destination</h1>"))
.addTo(map);
startMarker = new mapboxgl.Marker({
color: "var(--accent)",
draggable: true
})
.setLngLat(start)
.setPopup(new mapboxgl.Popup().setHTML("<h1>Destination</h1>"))
.addTo(map);
const bbox = [start, end];
map.fitBounds(bbox, {
padding: {top: 200, bottom: 300, left: 150, right: 150},
duration: 2000,
});
const query = await fetch(
`https://api.mapbox.com/directions/v5/mapbox/driving/${start[0]},${start[1]};${end[0]},${end[1]}?steps=true&geometries=geojson&access_token=${mapboxgl.accessToken}`,
{ method: 'GET' }
);
const json = await query.json();
const routes = json.routes;
const data = json.routes[0];
const route = data.geometry.coordinates;
setDistance(data.distance);
const geojson = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: route
}
};
// if the route already exists on the map, we'll reset it using setData
if (map.getSource('route')) {
map.getSource('route').setData(geojson);
}
// otherwise, we'll make a new request
else {
routeLayer = map.addLayer({
id: 'route',
type: 'line',
source: {
type: 'geojson',
data: geojson
},
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#ff0000',
'line-width': 5,
'line-opacity': 0.75
}
});
}
// add turn instructions here at the end
}
async function giveSuggestions(element) {
let value = element.value
showSuggestionsView();
const query = await fetch(
`https://api.mapbox.com/search/searchbox/v1/suggest?q=${value}&limit=3&session_token=${newID}&access_token=${mapboxgl.accessToken}`,
{ method: 'GET' }
);
const json = await query.json();
suggestionsView.innerHTML = "";
if (element.className == "start-input-location"){
if(json.suggestions){
json.suggestions.forEach( result => {
populateList(result.name, setSourceTo);
});
}
// store source lang lat
}
else if(element.className == "end-input-location"){
if(json.suggestions){
json.suggestions.forEach( result => {
populateList(result.name, setEndTo);
});
}
}
function populateList(value, evenListenerCallback) {
let element = document.createElement('div');
element.textContent = value;
element.className = "suggestion-row";
element.addEventListener('click', () => { evenListenerCallback(value); hideSuggestionsView() });
suggestionsView.appendChild(element);
}
async function setSourceTo(value){
startLocationName = value;
startInputBox.value = value;
document.querySelector(".start-route-box").textContent = value;
const query = await fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${value}.json?access_token=${mapboxgl.accessToken}`,
{ method: 'GET' }
);
const json = await query.json();
if(json){
let result = json.features[0].center;
source = result;
// getRoute(source, result);
}
// hideSuggestionsView();
}
async function setEndTo(value){
endLocationName = value;
endInputBox.value = value;
document.querySelector(".end-route-box").textContent = value;
const query = await fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${value}.json?access_token=${mapboxgl.accessToken}`,
{ method: 'GET' }
);
const json = await query.json();
if(json){
let result = json.features[0].center;
destination = result;
// getRoute(source, result);
}
// hideSuggestionsView();
}
function showSuggestionsView(){
suggestionsView.style.display = "grid"
}
function hideSuggestionsView(){
suggestionsView.style.display = "none"
}
}
function setDistance(distance){
let distanceBox = document.querySelector(".distance-box");
let roundedDistance = Math.round(distance / 1000 * 100) / 100 ;
distanceBox.querySelector("b").textContent = roundedDistance;
let {
fuel,
co2
} = APIResults;
let fuelResult = (fuel * roundedDistance) / 100;
fuelResult = Math.round(fuelResult * 100) / 100;
let co2Result = co2 * roundedDistance;
co2Result = Math.round(co2Result * 100) / 100;
let litresBox = document.querySelector(".litres-box");
let gramsBox = document.querySelector(".grams-box");
litresBox.querySelector("b").textContent = fuelResult;
gramsBox.querySelector("b").textContent = co2Result;
let fuelPrice = getFuelPrice(fuelResult);
let electicityCost = setEVDetails(roundedDistance);
let fuelPriceBox = document.querySelector(".fuel-price-box");
fuelPriceBox.querySelector("b").textContent = fuelPrice;
let savingsResult = fuelPrice - electicityCost;
savingsResult = Math.round((fuelPrice - electicityCost) * 100) / 100;
let savingsBox = document.querySelector(".savings-box");
savingsBox.querySelector("b").textContent = savingsResult;
// What if the fuelPrice is less than the electic cost.
// What if it comes back negative
}
function getFuelPrice(fuelInLitres) {
let fuelPriceDifferentiator = document.querySelector(".fuel-price-differentiator");
let carFuelTypeBox = document.querySelector(".car-fuel-type-box");
let fuelType = carFuelTypeBox.querySelector("div").textContent;
let costPrice;
fuelPriceDifferentiator.textContent = `Fuel Price For ${fuelType}`;
switch (fuelType){
case "Diesel":
costPrice = 39.06;
break;
case "Ethanol":
costPrice = 34.91;
break;
case "Regular Gasoline":
costPrice = 34.55;
break;
case "Premium Gasoline":
costPrice = 36.86;
break;
}
return Math.round(fuelInLitres * costPrice * 100) / 100;
}
function getElectricityCost(electicityUse) {
return Math.round(electicityUse * 9.48 * 100) / 100;
}
function calculateElectricityUse(distance){
return Math.round(distance * 0.14 * 100) / 100;
}
function setEVDetails(distance){
let electicityUse = calculateElectricityUse(distance);
let electricityCost = getElectricityCost(electicityUse);
let electicityUseBox = document.querySelector(".electicity-use-box");
let electicityCostBox = document.querySelector(".electricity-cost-box");
electicityUseBox.querySelector("b").textContent = electicityUse;
electicityCostBox.querySelector("b").textContent = electricityCost;
return electricityCost;
}
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();//Timestamp
var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16;//random number between 0 and 16
if(d > 0){//Use timestamp until depleted
r = (d + r)%16 | 0;
d = Math.floor(d/16);
} else {//Use microseconds since page-load if supported
r = (d2 + r)%16 | 0;
d2 = Math.floor(d2/16);
}
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}