generated from lewagon/taxi-fare-interface
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
218 lines (208 loc) · 6.58 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
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
const algoliaPlacesApiAppId = 'plU4N8HG6QWK';
const algoliaPlacesApiKey = '1131438afb49f60a48ed468c5af189b8';
const mapboxApiToken = 'pk.eyJ1Ijoia3Jva3JvYiIsImEiOiJja2YzcmcyNDkwNXVpMnRtZGwxb2MzNWtvIn0.69leM_6Roh26Ju7Lqb2pwQ';
const taxiFareApiUrl = 'https://YOUR_API_URL.herokuapp.com/predict_fare';
const displayMap = (start, stop) => {
mapboxgl.accessToken = mapboxApiToken;
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
center: [-74.00597, 40.71427], // starting position [lng, lat]
zoom: 10 // starting zoom
});
function getRoute(end) {
var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.onload = function() {
var json = JSON.parse(req.response);
var data = json.routes[0];
var route = data.geometry.coordinates;
var geojson = {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: route
}
};
// if the route already exists on the map, reset it using setData
if (map.getSource('route')) {
map.getSource('route').setData(geojson);
} else { // otherwise, make a new request
map.addLayer({
id: 'route',
type: 'line',
source: {
type: 'geojson',
data: {
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: geojson
}
}
},
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#3887be',
'line-width': 5,
'line-opacity': 0.75
}
});
}
// add turn instructions here at the end
};
req.send();
}
if (start && stop) {
map.on('load', function() {
// make an initial directions request that
// starts and ends at the same location
getRoute(start);
// Add starting point to the map
map.addLayer({
id: 'point',
type: 'circle',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: start
}
}
]
}
},
paint: {
'circle-radius': 10,
'circle-color': '#3887be'
}
});
// this is where the code from the next step will go
var coords = stop
var end = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: coords
}
}
]
};
if (map.getLayer('end')) {
map.getSource('end').setData(end);
} else {
map.addLayer({
id: 'end',
type: 'circle',
source: {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {},
geometry: {
type: 'Point',
coordinates: coords
}
}]
}
},
paint: {
'circle-radius': 10,
'circle-color': '#f30'
}
});
}
getRoute(coords);
});
}
};
const handleOnChangePickup = (e) => {
const coordinates = e.suggestion.latlng;
document.querySelector('#pickup_latitude').value = coordinates.lat;
document.querySelector('#pickup_longitude').value = coordinates.lng;
};
const pickupAutocomplete = () => {
const placesAutocompletePickup = places({
appId: algoliaPlacesApiAppId,
apiKey: algoliaPlacesApiKey,
container: document.querySelector('#pickup')
});
placesAutocompletePickup.on('change', handleOnChangePickup);
};
const handleOnChangeDropoff = (e) => {
const coordinates = e.suggestion.latlng;
document.querySelector('#dropoff_latitude').value = coordinates.lat;
document.querySelector('#dropoff_longitude').value = coordinates.lng;
const start = [parseFloat(document.querySelector('#pickup_longitude').value), parseFloat(document.querySelector('#pickup_latitude').value)];
const stop = [coordinates.lng, coordinates.lat];
displayMap(start, stop)
};
const dropoffAutocomplete = () => {
const placesAutocompleteDropoff = places({
appId: algoliaPlacesApiAppId,
apiKey: algoliaPlacesApiKey,
container: document.querySelector('#dropoff')
});
placesAutocompleteDropoff.on('change', handleOnChangeDropoff);
};
const initFlatpickr = () => {
flatpickr("#pickup_datetime", {
enableTime: true,
dateFormat: "Y-m-d H:i:S",
defaultDate: Date.now()
});
};
const predict = () => {
form = document.querySelector('form');
if (form) {
form.addEventListener('submit', (e) => {
e.preventDefault();
const data = {
"pickup_latitude": parseFloat(document.getElementById('pickup_latitude').value) || 40.747,
"pickup_longitude": parseFloat(document.getElementById('pickup_longitude').value) || -73.989,
"dropoff_latitude": parseFloat(document.getElementById('dropoff_latitude').value) || 40.802,
"dropoff_longitude": parseFloat(document.getElementById('dropoff_longitude').value) || -73.956,
"passenger_count": parseInt(document.getElementById('passenger_count').value) || 2,
"pickup_datetime": `${document.getElementById('pickup_datetime').value} UTC`
};
fetch(taxiFareApiUrl, {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
document.getElementById('fare').classList.remove('d-none');
const fareResult = document.getElementById('predicted-fare');
const fare = Math.round(data['predictions'][0] * 100) / 100
fareResult.innerText = `$${fare}`;
})
.catch((error) => {
console.error('Error:', error);
});
});
}
};
displayMap();
pickupAutocomplete();
dropoffAutocomplete();
initFlatpickr();
predict();