This is my server.js file which i have created and can fetch the directionsResponse without an error
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
const { Client } = require("@googlemaps/google-maps-services-js");
const googleMapsClient = new Client();
app.use(express.json());
app.get("/calculate-route", async (req, res) => {
const { fromLocation, toLocation, travelMode } = req.query;
const apiKey = "mygoogleapikey";
try {
const directionsResponse = await googleMapsClient.directions({
params: {
origin: fromLocation,
destination: toLocation,
mode: travelMode,
key: apiKey,
},
timeout: 1000,
});
res.json(directionsResponse.data);
} catch (error) {
console.error("Error calculating route:", error.response.data);
res.status(500).json({ error: "Failed to calculate route" });
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
but, when i try to fetch data from my port 3001 it stores the data in directionsResponse and error occurs when i try to render the directions to the map.
import React, { useState, useEffect } from "react";
import axios from "axios";
import {
useJsApiLoader,
GoogleMap,
Marker,
DirectionsRenderer,
} from "@react-google-maps/api";
const center = { lat: 6.867367400000001, lng: 81.0469172 };
function MapContainer({ width, fromLocation, toLocation }) {
const { isLoaded } = useJsApiLoader({
googleMapsApiKey: "mygoogleapikey",
libraries: ["places"],
});
const [map, setMap] = useState(/** @type google.maps.Map */ (null));
const [directionsResponse, setDirectionsResponse] = useState(null);
async function calculateRoute() {
try {
const response = await axios.get(
"http://localhost:3001/calculate-route",
{
params: {
fromLocation: fromLocation,
toLocation: toLocation,
travelMode: "walking",
},
}
);
setDirectionsResponse(response.data);
console.log(response.data);
} catch (error) {
console.error("Error fetching directions:", error);
}
}
if (!isLoaded) {
return <div>Loading...</div>;
}
return (
<GoogleMap
center={center}
zoom={10}
mapContainerStyle={{
height: "85vh",
width: `${width}px`,
borderRadius: "1rem",
}}
options={{
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
fullscreenControl: false,
}}
onLoad={(map) => {
setMap(map);
calculateRoute();
}}
>
<Marker position={center} />
{directionsResponse && (
<DirectionsRenderer directions={directionsResponse} />
)}
</GoogleMap>
);
}
export default MapContainer;
i need to like give my fromLocation,toLocation along with the travel mode and render the from and to locations to the map along with the directions along with the available transport if its transit travel mode chosen.