Animate a car(Marker) along a path in google map android

Nikhil picture Nikhil · Nov 24, 2015 · Viewed 20k times · Source

I am going to share a solution of moving a marker along the path if you have List.The Bitmap will move along the path from using LatLng list.

Answer

Nikhil picture Nikhil · Nov 24, 2015
public static void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint, final Bitmap bitmap) {


    Marker marker = myMap.addMarker(new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
            .position(directionPoint.get(0))
            .flat(true));

    myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(directionPoint.get(0), 10));

    animateMarker(myMap, marker, directionPoint, false);
}


private static void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
                                  final boolean hideMarker) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = myMap.getProjection();
    final long duration = 30000;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        int i = 0;

        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed
                    / duration);
            if (i < directionPoint.size())
                marker.setPosition(directionPoint.get(i));
            i++;


            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}