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
|
const MAPBOX_FORWARD_GEOCODE_BASE_URL = 'https://api.mapbox.com/geocoding/v5/mapbox.places/';
const MAPBOX_REVERSE_GEOCODE_BASE_URL = 'https://api.mapbox.com/geocoding/v5/mapbox.places/';
const MAPBOX_DIRECTIONS_BASE_URL = 'https://api.mapbox.com/directions/v5/mapbox';
const MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoiemF1bHRhdmFuZ2FyIiwiYSI6ImNscHgwNDd1MDA3MXIydm92ODdianp6cGYifQ.WFAqbhwxtMHOWSPtu0l2uQ';
export type TransportationType = 'driving' | 'cycling' | 'walking';
export class MapboxApiUtility {
static forwardGeocodeForFeatures = async (searchText: string) => {
try {
const url = MAPBOX_FORWARD_GEOCODE_BASE_URL + encodeURI(searchText) +'.json' +`?access_token=${MAPBOX_ACCESS_TOKEN}`;
const response = await fetch(url);
const data = await response.json();
return data.features;
} catch (error: any){
// TODO: handle error in better way
return null;
}
}
static reverseGeocodeForFeatures = async (longitude: number, latitude: number) => {
try {
const url = MAPBOX_REVERSE_GEOCODE_BASE_URL + encodeURI(longitude.toString() + "," + latitude.toString()) + '.json' +
`?access_token=${MAPBOX_ACCESS_TOKEN}`;
const response = await fetch(url);
const data = await response.json();
return data.features;
} catch (error: any){
return null;
}
}
static getDirections = async (origin: number[], destination: number[]): Promise<Record<TransportationType, any> | undefined> => {
try {
const directionsPromises: Promise<any>[] = [];
const transportationTypes: TransportationType[] = ['driving', 'cycling', 'walking'];
transportationTypes.forEach((type) => {
directionsPromises.push(
fetch(
`${MAPBOX_DIRECTIONS_BASE_URL}/${type}/${origin[0]},${origin[1]};${destination[0]},${destination[1]}?steps=true&geometries=geojson&access_token=${MAPBOX_ACCESS_TOKEN}`
).then((response) => response.json())
);
});
const results = await Promise.all(directionsPromises);
const routeInfoMap: Record<TransportationType, any> = {
'driving': {},
'cycling': {},
'walking': {},
};
transportationTypes.forEach((type, index) => {
const routeData = results[index].routes[0];
if (routeData) {
const geometry = routeData.geometry;
const coordinates = geometry.coordinates;
routeInfoMap[type] = {
duration: this.secondsToMinutesHours(routeData.duration),
distance: this.metersToMiles(routeData.distance),
coordinates: coordinates,
};
}
});
return routeInfoMap;
// return current route info, and the temporary route
} catch (error: any){
return undefined;
console.log("Error: ", error);
}
}
private static secondsToMinutesHours = (seconds: number) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60).toFixed(2);
if (hours === 0){
return `${minutes} min`
} else {
return `${hours} hr ${minutes} min`
}
}
private static metersToMiles = (meters: number) => {
return `${parseFloat((meters/1609.34).toFixed(2))} mi`;
}
}
// const drivingQuery = await fetch(
// `${MAPBOX_DIRECTIONS_BASE_URL}/driving/${origin[0]},${origin[1]};${destination[0]},${destination[1]}?steps=true&geometries=geojson&access_token=${MAPBOX_ACCESS_TOKEN}`);
// const cyclingQuery = await fetch(
// `${MAPBOX_DIRECTIONS_BASE_URL}/cycling/${origin[0]},${origin[1]};${destination[0]},${destination[1]}?steps=true&geometries=geojson&access_token=${MAPBOX_ACCESS_TOKEN}`);
// const walkingQuery = await fetch(
// `${MAPBOX_DIRECTIONS_BASE_URL}/walking/${origin[0]},${origin[1]};${destination[0]},${destination[1]}?steps=true&geometries=geojson&access_token=${MAPBOX_ACCESS_TOKEN}`);
// const drivingJson = await drivingQuery.json();
// const cyclingJson = await cyclingQuery.json();
// const walkingJson = await walkingQuery.json();
// console.log("Driving: ", drivingJson);
// console.log("Cycling: ", cyclingJson);
// console.log("Waling: ", walkingJson);
// const routeMap = {
// 'driving': drivingJson.routes[0],
// 'cycling': cyclingJson.routes[0],
// 'walking': walkingJson.routes[0]
// }
// const routeInfoMap: Record<TransportationType, any> = {
// 'driving': {},
// 'cycling': {},
// 'walking': {},
// };
// Object.entries(routeMap).forEach(([key, routeData]) => {
// const transportationTypeKey = key as TransportationType;
// const geometry = routeData.geometry;
// const coordinates = geometry.coordinates;
// console.log(coordinates);
// routeInfoMap[transportationTypeKey] = {
// duration: this.secondsToMinutesHours(routeData.duration),
// distance: this.metersToMiles(routeData.distance),
// coordinates: coordinates
// }
// })
|