Skip to content

Commit 1fcb20b

Browse files
adaup1Andrew Dauphinais
andauthored
docs: extend directions example with draggable markers (#683)
--------- Co-authored-by: Andrew Dauphinais <[email protected]>
1 parent 314da53 commit 1fcb20b

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

examples/directions/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ This is an example which shows how to use `useMapsLibrary` to load the `routes`
66

77
It allows the user to choose alternative routes, updating the route being rendered on the map.
88

9+
Users can also drag the markers around the map to change the route. The route is updated in real-time.
10+
911
## Google Maps Platform API Key
1012

1113
This example does not come with an API key. Running the examples locally requires a valid API key for the Google Maps Platform.

examples/directions/src/app.tsx

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,32 @@ function Directions() {
3939
useEffect(() => {
4040
if (!routesLibrary || !map) return;
4141
setDirectionsService(new routesLibrary.DirectionsService());
42-
setDirectionsRenderer(new routesLibrary.DirectionsRenderer({map}));
42+
setDirectionsRenderer(
43+
new routesLibrary.DirectionsRenderer({
44+
draggable: true, // Only necessary for draggable markers
45+
map
46+
})
47+
);
4348
}, [routesLibrary, map]);
4449

50+
// Add the following useEffect to make markers draggable
51+
useEffect(() => {
52+
if (!directionsRenderer) return;
53+
54+
// Add the listener to update routes when directions change
55+
const listener = directionsRenderer.addListener(
56+
'directions_changed',
57+
() => {
58+
const result = directionsRenderer.getDirections();
59+
if (result) {
60+
setRoutes(result.routes);
61+
}
62+
}
63+
);
64+
65+
return () => google.maps.event.removeListener(listener);
66+
}, [directionsRenderer]);
67+
4568
// Use directions service
4669
useEffect(() => {
4770
if (!directionsService || !directionsRenderer) return;

0 commit comments

Comments
 (0)