简体   繁体   中英

Marker shaky on adding animation google maps android

I am using this code to animate the marker to kinda replicate the movement of a vehicle on the google maps but the marker shakes vigorously when marker.setPosition is called in the handler function. Code is below:

public static void animateMarker(final GoogleMap map, final Marker marker, final LatLng toPosition) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = map.getProjection();
    Point startPoint = proj.toScreenLocation(marker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 5000;
    final Interpolator interpolator = new LinearInterpolator();
    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude;
            double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude;
            marker.setPosition(new LatLng(lat, lng));
            if (t < 1.0) {
                handler.postDelayed(this, 16);
            }
        }
    });
}

Try using the AccelerateDecelerateInterpolator , an interpolator whose rate of change starts and ends slowly but accelerates through the middle, instead of LinearInterpolator as used in this Google video tutorial . The marker animation was seamless. Here's the snippet:

public class MarkerAnimation {
    static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
        final LatLng startPosition = marker.getPosition();
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final Interpolator interpolator = new AccelerateDecelerateInterpolator();
        final float durationInMs = 3000;

    handler.post(new Runnable() {
        long elapsed;
        float t;
        float v;

        @Override
        public void run() {
            // Calculate progress using interpolator
            elapsed = SystemClock.uptimeMillis() - start;
            t = elapsed / durationInMs;
            v = interpolator.getInterpolation(t);

            marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));

            // Repeat till progress is complete.
            if (t < 1) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

Full code [here](https://gist.github.com/broady/6314689).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM