Comments (5)
yep, I don't think something like that can be done with the vanilla DirectionsRenderer that comes with the Maps JavaScript API. I think the best choice for this would be the deck.gl TripsLayer (see also the demo here: https://deck.gl/examples/trips-layer).
For that you need to specify the points along the path together with timestamps and then animate the 'currentTime' value of the layer. If you don't have a 'true' timing reference you can use e.g. the relative distance along the path as timestamp.
That TripsLayer can then be added to the map with an interleaved overlay as shown here: https://visgl.github.io/react-google-maps/docs/guides/deckgl-integration#using-googlemapsoverlay
from react-google-maps.
I tried to write the code, now i'm struggling to get it to animate
here's the code -
Directions.tsx:
"use client";
import {Color, Position} from "@deck.gl/core";
import {TripsLayer} from "@deck.gl/geo-layers";
import {GoogleMapsOverlay} from "@deck.gl/google-maps";
import {useMap, useMapsLibrary} from "@vis.gl/react-google-maps";
import {useEffect, useState} from "react";
const LOOP_LENGTH = 100;
type DataType = {
vendor: number;
path: Position[];
timestamps: number[];
};
export default function Directions({
directionServiceResponse,
}: {
directionServiceResponse: google.maps.DirectionsResult;
}) {
const map = useMap();
const routesLibrary = useMapsLibrary("routes");
const [directionsRenderer, setDirectionsRenderer] = useState<google.maps.DirectionsRenderer>();
const [routes, setRoutes] = useState<google.maps.DirectionsRoute[]>([]);
const selected = routes[0];
const leg = selected?.legs[0];
// Initialize directions service and renderer
useEffect(() => {
if (!routesLibrary || !map) return;
setDirectionsRenderer(new routesLibrary.DirectionsRenderer({map}));
}, [routesLibrary, map]);
// Assign direction response to renderer
useEffect(() => {
if (!directionsRenderer) return;
directionsRenderer.setDirections(directionServiceResponse);
setRoutes(directionServiceResponse.routes);
return () => directionsRenderer.setMap(null);
}, [directionsRenderer]);
// Update direction route
useEffect(() => {
if (!directionsRenderer) return;
directionsRenderer.setRouteIndex(0);
}, [directionsRenderer]);
// Initialize and animate TripsLayer
useEffect(() => {
if (!map || !leg) return;
const path = leg.steps.flatMap((step) =>
step.path.map((latlng) => [latlng.lng(), latlng.lat()]),
);
const timestamps = Array(path.length)
.fill(0)
.map((_, i) => i * 10); // Assuming each step takes 10 units of time
const data = [{vendor: 0, path, timestamps}];
console.log("DATA:::", data);
let currentTime = 0;
const props = {
id: "trips",
data,
getPath: (d: DataType) => d.path,
getTimestamps: (d: DataType) => d.timestamps,
getColor: [0, 255, 255] as Color,
opacity: 1,
widthMinPixels: 2,
trailLength: 180,
currentTime,
shadowEnabled: false,
};
const overlay = new GoogleMapsOverlay({interleaved: true});
const animate = () => {
currentTime = (currentTime + 1) % LOOP_LENGTH;
const tripsLayer = new TripsLayer({
...props,
currentTime,
});
overlay.setProps({
layers: [tripsLayer],
});
window.requestAnimationFrame(animate);
};
window.requestAnimationFrame(animate);
overlay.setMap(map);
return () => overlay.setMap(null);
}, [map, leg]);
if (!leg) return null;
return null;
}
RouteMap.tsx:
import {Map} from "@vis.gl/react-google-maps";
import {MAP_STYLE} from "@/constants";
import Directions from "./Directions";
export default function RouteMap({
directionServiceResponse,
}: {
directionServiceResponse: google.maps.DirectionsResult;
}) {
console.log(directionServiceResponse);
return (
<div>
<Map
className="m-0 h-full w-full rounded-md border-0 p-0"
clickableIcons={false}
controlSize={30}
defaultZoom={11}
disableDefaultUI={true}
fullscreenControl={true}
fullscreenControlOptions={{position: google.maps.ControlPosition.LEFT_TOP}}
gestureHandling={"greedy"}
mapId={"4f6dde3310be51d7"}
mapTypeControl={false}
streetViewControl={false}
styles={MAP_STYLE}
zoomControl={false}
>
<Directions directionServiceResponse={directionServiceResponse} />
</Map>
</div>
);
}
and the route is just sitting there
from react-google-maps.
its working now there was some problem with loop length,
now I'm having issues with default center and default zoom, they don't seem to be working
from react-google-maps.
I believe the default behavior of the DirectionsRenderer is to fit the map to the bounds of the route.
Also, what do you need the DirectionsRenderer for if you're rendering the Route using the TripsLayer?
from react-google-maps.
Closing this since it's not a bugreport or feature request. Feel free to ask followup questions in our Discussions section.
from react-google-maps.
Related Issues (20)
- [Feat] Replace useMemo with useState for one time initializations HOT 2
- Use the API libraries without the need of using a map first [Feat] HOT 5
- [Feat] AdvancedMarker: add style prop HOT 1
- Map returned undefined HOT 4
- [Bug]Cannot remove a WebglOverlay
- [Bug] AdvancedMarker className prop should also be applied when using a Pin instead of custom content
- <ApiProvider> failed to load Google Maps API Error HOT 4
- [Feat] Add support for InfoWindow headerContent / headerDisabled options HOT 10
- Add className and style prop to the MapControl component HOT 1
- [Bug] Warning: useLayoutEffect does nothing on the server HOT 4
- [Bug] InfoWindow anchor reference not cleared on unmount HOT 8
- [Bug] Open two infowindow when clicking the marker HOT 1
- [Feat] Add padding option to defaultBounds HOT 5
- [Feat] Change the language HOT 1
- [Bug] On clicking AdvanceMarker to open InfoWindow, goes into an Infinite loop of rendering on setting markerRef(marker) manually HOT 8
- Marker icons are showing along with marker cluster HOT 2
- [Bug] Infinite loop using AdvancedMarkers when the marker items are changed HOT 2
- [Bug] Cannot remove a WebglOverlay that has not been set to a map
- [Bug] AdvancedMarker onDragEnd event triggers Map's onClick event
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-google-maps.