· 6 years ago · Sep 12, 2019, 02:02 PM
1export async function calculateTripCost(from: Coords, to: Coords, numPassengers: number) {
2 try {
3 const res = await getDistanceAndDuration(from, to) // this is a google maps api for returning distance and duration
4 const { distance } = res
5 let { duration } = res
6
7 if (res.duration_in_traffic) {
8 duration = res.duration_in_traffic
9 }
10
11 const dist = distance.value * OneMeterToMile
12 const time = duration.value / 60.0
13 const bookingFee = (dist * HichNowCosts.costPerMile) / (time / Math.abs(dist - time))
14 const fareWithoutStripe = bookingFee + (dist / HichNowCosts.costPerMile)
15 const stripeFee = (fareWithoutStripe * HichNowCosts.stripePercentage) + HichNowCosts.stripeFixedCost
16 const cost = fareWithoutStripe + stripeFee
17
18 return { cost, distance, duration }
19 } catch (err) {
20 throw (err)
21 }
22}
23
24//
25async function getDistanceAndDuration(from: Coords, to: Coords) {
26 const options = {
27 qs: {
28 units: GoogleMaps.units,
29 origins: `${from.lat},${from.long}`,
30 destinations: `${to.lat},${to.long}`,
31 departure_time: "now",
32 key: GoogleMaps.apiKey
33 },
34 json: true
35 }
36
37 const response = await Request(GoogleMaps.url, options)
38 return response.rows[0].elements[0]
39}