Reputation: 1966
I am trying to implement Google Maps Directions Waypoints using @react-google-maps/api
library to show the directions between starting and ending points.
With mock data coordinates it seems to work, but not with the data coming from the api/json
file.
Here is the Codesandbox link
And the code below
import React, { useState } from "react";
import {
DirectionsRenderer,
DirectionsService,
GoogleMap,
LoadScript,
Marker
} from "@react-google-maps/api";
const containerStyle = {
width: "100%",
height: "900px"
};
const center = {
lat: 51.4332,
lng: 7.6616
};
const options = {
disableDefaultUI: true,
zoomControl: true,
fullscreenControl: true,
maxZoom: 17
};
export default function App({ parks }) {
const [directions, setDirections] = useState();
const directionsCallback = React.useCallback((response) => {
console.log(response);
if (response !== null) {
if (response.status === "OK") {
console.log("response", response);
setDirections(response);
} else {
console.log("response: ", response);
}
}
}, []);
//destination
const destinationPark = parks.features.find(
(park) => park.properties.id === 28007
);
//origin
const originPark = parks.features.find(
(park) => park.properties.id === 35299
);
const google = window.google;
// data to add as waypoints
const waypointsParks = parks.features.filter(
(park) => park.properties.id !== 28007 && park.properties.id !== 35299
);
return (
<div style={{ width: "100%", height: "100%" }}>
<LoadScript googleMapsApiKey={google_api_key}>
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={6}
options={options}
>
<Marker
position={{
lat: parseFloat("52.50920109083271"),
lng: parseFloat("13.416411897460808")
}}
/>
)
<DirectionsService
callback={directionsCallback}
options={{
destination: `${destinationPark.properties.coordinates[1]}, ${destinationPark.properties.coordinates[0]}`,
origin: `${originPark.properties.coordinates[1]}, ${originPark.properties.coordinates[0]}`,
travelMode: "DRIVING"
// waypoints: [
// {
// location: new google.maps.LatLng(
// 52.596714626379296,
// 14.70278827986568
// )
// },
// {
// location: new google.maps.LatLng(
// 52.56193313494678,
// 11.52648542963747
// )
// }
// ]
}}
/>
<DirectionsRenderer
options={{
directions: directions
}}
/>
</GoogleMap>
</LoadScript>
</div>
);
}
Any help will be appreciated.
Upvotes: 0
Views: 372
Reputation: 3454
Assuming the failure is the following based upon codesandbox log.
Directions request returned no results.
Your application must handle the case where no results are found.
If you feel like this is a mistake, please provide a simplified example with just the origin, destination, waypoints, etc that you believe should return a result.
Upvotes: 1