How can I implement Marker moving animation in React app. I have used react-google-maps for Google Maps.
I am going through the documentation for the library and Google Maps API. There is an option of offset in Google Maps API. But I am not looking for that.
The app will be receiving updated coordinates via a socket.io server. And as soon as the coordinates arrive the marker needs to be moved, like the Uber app.
There is an open issue on GitHub here which is not closed yet.
Currently, I am able to move the markers on the coordinates updates, but without animation.
Sample code
import React, { Component } from 'react';
import Socket from 'socket.io-client';
import { withRouter } from 'react-router-dom';
import {
GoogleMap,
withScriptjs,
withGoogleMap,
Marker
} from 'react-google-maps';
import { googleMapsUrl, socketUrl } from '../../../config/constants';
const io = Socket(socketUrl('dev'));
class GoogleMaps extends Component {
constructor(props) {
super(props);
this.state = {
defaultCenter: {
clientId: "FAKE_CLIENT_ID",
imei: "FAKE_IMEI_NUMBER",
lat: 28.554907,
lng: 77.554385,
name: "FAKE_NAME"
},
defaultZoom: 10,
movingMarker: [],
AllMarkers: []
};
this.pullDataFromSocket = this.pullDataFromSocket.bind(this);
this.createMovingMarker = this.createMovingMarker.bind(this);
}
componentDidMount() {
this.pullDataFromSocket();
}
pullDataFromSocket() {
const pathname = this.props.location.pathname.replace(/\//, '');
io.on('data', data => {
const markerCoordinates = data.devicedatalist.map(ds => {
// Some valude modification
return {
...ds
}
});
const movingMarker = this.state.movingMarker;
movingMarker.push(markerCoordinates[0]);
this.setState({
AllMarkers: markerCoordinates,
defaultCenter: markerCoordinates[0],
movingMarker
});
});
}
createMovingMarker() {
let MarkerLocation = this.state.defaultCenter;
if (this.state.movingMarker.length > 1) {
/**
* Setting the marker to the updated new location
*/
MarkerLocation = this.state.movingMarker[this.state.movingMarker.length - 1];
}
return (
<Marker
position={MarkerLocation}
>
</Marker>
);
}
render() {
return(
<GoogleMap
defaultZoom={this.state.defaultZoom}
center={this.state.defaultCenter}
>
{this.createMovingMarker()}
</GoogleMap>
)
};
}
const MapWrapper = withRouter(
withScriptjs(
withGoogleMap(GoogleMaps)
)
);
export default () => {
return (
<MapWrapper
googleMapURL={googleMapsUrl()}
loadingElement={<div />}
mapElement={<div style={{height: '100vh'}} />}
containerElement={<div />}
/>
)
};