I'm attempting to extract routes from the computeRoutes method from the Google Maps API (https://developers.google.com/maps/documentation/routes/reference/rest/v2/TopLevel/computeRoutes). I'm able to get the correct response each time, which I verify here (https://developers.google.com/maps/documentation/routes/polylinedecoder), but when I use json.encode and then json.decode(response.body), the encodedPolyline comes back altered because certain escape character sequences are adjusted (two backslashes in my case \). Why is this the case? Should I be using a different method? The original response.body works just fine when I log it into my console, so I'm not sure what the issues is: //server.js
app.post('/api/computeRoutes', async (req, res) => {
const { origin, destination, travelMode } = req.body;
const apiKey = process.env.GOOGLE_MAPS_API_KEY;
const [originLat, originLng] = origin.split(',').map(Number);
const [destinationLat, destinationLng] = destination.split(',').map(Number);
const url = `https://routes.googleapis.com/directions/v2:computeRoutes?key=${apiKey}`;
const data = {
origin: {
location: {
latLng: {
latitude: originLat,
longitude: originLng
}
}
},
destination: {
location: {
latLng: {
latitude: destinationLat,
longitude: destinationLng
}
}
},
travelMode: "DRIVE"
// travelMode: travelMode.toUpperCase() || 'DRIVING'
};
const headers = {
'Content-Type': 'application/json',
'X-Goog-FieldMask': 'routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline'
};
try {
const response = await axios.post(url, data, { headers });
console.log(`Server.js Response Data: ${JSON.stringify(response.data)}`);
res.json(response.data);
} catch (error) {
console.error('Error in computeRoutes:', error);
res.status(500).send('Error occurred while fetching routes');
}
});
//map_service.dart
Future<dynamic> getDirections(String origin, String destination, {String travelMode = 'DRIVING'}) async {
final url = '$_baseUrl/api/computeRoutes';
final response = await http.post(
Uri.parse(url),
headers: {"Content-Type": "application/json"},
body: json.encode({
'origin': origin,
'destination': destination,
'travelMode': travelMode,
}),
);
if (response.statusCode == 200) {
String responseBody = response.body;
return json.decode(response.body); // Adjust according to your server's response format
} else {
throw Exception('Failed to get directions: ${response.body}');
}
}