标记摇摇欲坠添加动画谷歌地图android

时间:2016-10-05 07:58:25

标签: android google-maps android-animation marker

我正在使用此代码为标记设置动画,以便在google地图上复制车辆的移动,但是当处理程序函数中调用marker.setPosition时,标记会剧烈震动。代码如下:

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);
            }
        }
    });
}

1 个答案:

答案 0 :(得分:0)

尝试使用AccelerateDecelerateInterpolator,一个插值器,其变化率开始和结束缓慢但在中间加速,而不是在此Google video tutorial中使用的LinearInterpolator。标记动画是无缝的。这是片段:

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).