summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxsdk/testapp/activity/annotation/AnimatedMarkerActivity.java
blob: 1874cf728bbac93ac7690fad2c38b1cc3cafd23d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package com.mapbox.mapboxsdk.testapp.activity.annotation;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;

import com.google.gson.JsonObject;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.turf.TurfMeasurement;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.mapbox.mapboxsdk.style.expressions.Expression.get;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconRotate;

/**
 * Test activity showcasing animating MarkerViews.
 */
public class AnimatedMarkerActivity extends AppCompatActivity {

  private static final String PASSENGER = "passenger";
  private static final String PASSENGER_LAYER = "passenger-layer";
  private static final String PASSENGER_SOURCE = "passenger-source";
  private static final String TAXI = "taxi";
  private static final String TAXI_LAYER = "taxi-layer";
  private static final String TAXI_SOURCE = "taxi-source";
  private static final String RANDOM_CAR_LAYER = "random-car-layer";
  private static final String RANDOM_CAR_SOURCE = "random-car-source";
  private static final String RANDOM_CAR_IMAGE_ID = "random-car";
  private static final String PROPERTY_BEARING = "bearing";
  private static final String WATERWAY_LAYER_ID = "waterway-label";
  private static final int DURATION_RANDOM_MAX = 1500;
  private static final int DURATION_BASE = 3000;

  private final Random random = new Random();

  private MapView mapView;
  private MapboxMap mapboxMap;

  private List<Car> randomCars = new ArrayList<>();
  private GeoJsonSource randomCarSource;
  private Car taxi;
  private GeoJsonSource taxiSource;
  private LatLng passenger;

  private List<Animator> animators = new ArrayList<>();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animated_marker);

    mapView = (MapView) findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(mapboxMap -> {
      AnimatedMarkerActivity.this.mapboxMap = mapboxMap;
      setupCars();
      animateRandomRoutes();
      animateTaxi();
    });
  }

  private void setupCars() {
    addRandomCars();
    addPassenger();
    addMainCar();
  }

  private void animateRandomRoutes() {
    final Car longestDrive = getLongestDrive();
    final Random random = new Random();
    for (final Car car : randomCars) {
      final boolean isLongestDrive = longestDrive.equals(car);
      ValueAnimator valueAnimator = ValueAnimator.ofObject(new LatLngEvaluator(), car.current, car.next);
      valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        private LatLng latLng;

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
          latLng = (LatLng) animation.getAnimatedValue();
          car.current = latLng;
          if (isLongestDrive) {
            updateRandomCarSource();
          }
        }
      });

      if (isLongestDrive) {
        valueAnimator.addListener(new AnimatorListenerAdapter() {
          @Override
          public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            updateRandomDestinations();
            animateRandomRoutes();
          }
        });
      }

      valueAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStart(Animator animation) {
          super.onAnimationStart(animation);
          car.feature.properties().addProperty("bearing", Car.getBearing(car.current, car.next));
        }
      });

      int offset = random.nextInt(2) == 0 ? 0 : random.nextInt(1000) + 250;
      valueAnimator.setStartDelay(offset);
      valueAnimator.setDuration(car.duration - offset);
      valueAnimator.setInterpolator(new LinearInterpolator());
      valueAnimator.start();

      animators.add(valueAnimator);
    }
  }

  private void animateTaxi() {
    ValueAnimator valueAnimator = ValueAnimator.ofObject(new LatLngEvaluator(), taxi.current, taxi.next);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

      private LatLng latLng;

      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        latLng = (LatLng) animation.getAnimatedValue();
        taxi.current = latLng;
        updateTaxiSource();
      }
    });

    valueAnimator.addListener(new AnimatorListenerAdapter() {
      @Override
      public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd(animation);
        updatePassenger();
        animateTaxi();
      }
    });

    valueAnimator.addListener(new AnimatorListenerAdapter() {
      @Override
      public void onAnimationStart(Animator animation) {
        super.onAnimationStart(animation);
        taxi.feature.properties().addProperty("bearing", Car.getBearing(taxi.current, taxi.next));
      }
    });

    valueAnimator.setDuration((long) (7 * taxi.current.distanceTo(taxi.next)));
    valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    valueAnimator.start();

    animators.add(valueAnimator);
  }

  private void updatePassenger() {
    passenger = getLatLngInBounds();
    updatePassengerSource();
    taxi.setNext(passenger);
  }

  private void updatePassengerSource() {
    GeoJsonSource source = mapboxMap.getSourceAs(PASSENGER_SOURCE);
    FeatureCollection featureCollection = FeatureCollection.fromFeatures(new Feature[] {
      Feature.fromGeometry(
        Point.fromLngLat(
          passenger.getLongitude(),
          passenger.getLatitude()
        )
      )
    });
    source.setGeoJson(featureCollection);
  }

  private void updateTaxiSource() {
    taxi.updateFeature();
    taxiSource.setGeoJson(taxi.feature);
  }

  private void updateRandomDestinations() {
    for (Car randomCar : randomCars) {
      randomCar.setNext(getLatLngInBounds());
    }
  }

  private Car getLongestDrive() {
    Car longestDrive = null;
    for (Car randomCar : randomCars) {
      if (longestDrive == null) {
        longestDrive = randomCar;
      } else if (longestDrive.duration < randomCar.duration) {
        longestDrive = randomCar;
      }
    }
    return longestDrive;
  }

  private void updateRandomCarSource() {
    for (Car randomCarsRoute : randomCars) {
      randomCarsRoute.updateFeature();
    }
    randomCarSource.setGeoJson(featuresFromRoutes());
  }

  private FeatureCollection featuresFromRoutes() {
    List<Feature> features = new ArrayList<>();
    for (Car randomCarsRoute : randomCars) {
      features.add(randomCarsRoute.feature);
    }
    return FeatureCollection.fromFeatures(features);
  }

  private long getDuration() {
    return random.nextInt(DURATION_RANDOM_MAX) + DURATION_BASE;
  }

  private void addRandomCars() {
    LatLng latLng;
    LatLng next;
    for (int i = 0; i < 3000; i++) {
      latLng = getLatLngInBounds();
      next = getLatLngInBounds();

      JsonObject properties = new JsonObject();
      properties.addProperty(PROPERTY_BEARING, Car.getBearing(latLng, next));

      Feature feature = Feature.fromGeometry(
        Point.fromLngLat(
          latLng.getLongitude(),
          latLng.getLatitude()
        ), properties);

      randomCars.add(
        new Car(feature, next, getDuration())
      );
    }

    randomCarSource = new GeoJsonSource(RANDOM_CAR_SOURCE, featuresFromRoutes());
    mapboxMap.addSource(randomCarSource);
    mapboxMap.addImage(RANDOM_CAR_IMAGE_ID,
      ((BitmapDrawable) getResources().getDrawable(R.drawable.ic_car_top)).getBitmap());

    SymbolLayer symbolLayer = new SymbolLayer(RANDOM_CAR_LAYER, RANDOM_CAR_SOURCE);
    symbolLayer.withProperties(
      iconImage(RANDOM_CAR_IMAGE_ID),
      iconAllowOverlap(true),
      iconRotate(get("bearing")),
      iconIgnorePlacement(true)
    );

    mapboxMap.addLayerBelow(symbolLayer, WATERWAY_LAYER_ID);
  }

  private void addPassenger() {
    passenger = getLatLngInBounds();
    FeatureCollection featureCollection = FeatureCollection.fromFeatures(new Feature[] {
      Feature.fromGeometry(
        Point.fromLngLat(
          passenger.getLongitude(),
          passenger.getLatitude()
        )
      )
    });

    mapboxMap.addImage(PASSENGER,
      ((BitmapDrawable) getResources().getDrawable(R.drawable.icon_burned)).getBitmap());

    GeoJsonSource geoJsonSource = new GeoJsonSource(PASSENGER_SOURCE, featureCollection);
    mapboxMap.addSource(geoJsonSource);

    SymbolLayer symbolLayer = new SymbolLayer(PASSENGER_LAYER, PASSENGER_SOURCE);
    symbolLayer.withProperties(
      iconImage(PASSENGER),
      iconIgnorePlacement(true),
      iconAllowOverlap(true)
    );
    mapboxMap.addLayerBelow(symbolLayer, RANDOM_CAR_LAYER);
  }

  private void addMainCar() {
    LatLng latLng = getLatLngInBounds();
    JsonObject properties = new JsonObject();
    properties.addProperty(PROPERTY_BEARING, Car.getBearing(latLng, passenger));
    Feature feature = Feature.fromGeometry(
      Point.fromLngLat(
        latLng.getLongitude(),
        latLng.getLatitude()), properties);
    FeatureCollection featureCollection = FeatureCollection.fromFeatures(new Feature[] {feature});

    taxi = new Car(feature, passenger, getDuration());
    mapboxMap.addImage(TAXI,
      ((BitmapDrawable) getResources().getDrawable(R.drawable.ic_taxi_top)).getBitmap());
    taxiSource = new GeoJsonSource(TAXI_SOURCE, featureCollection);
    mapboxMap.addSource(taxiSource);

    SymbolLayer symbolLayer = new SymbolLayer(TAXI_LAYER, TAXI_SOURCE);
    symbolLayer.withProperties(
      iconImage(TAXI),
      iconRotate(get(PROPERTY_BEARING)),
      iconAllowOverlap(true),
      iconIgnorePlacement(true)

    );
    mapboxMap.addLayer(symbolLayer);
  }

  private LatLng getLatLngInBounds() {
    LatLngBounds bounds = mapboxMap.getProjection().getVisibleRegion().latLngBounds;
    Random generator = new Random();
    double randomLat = bounds.getLatSouth() + generator.nextDouble()
      * (bounds.getLatNorth() - bounds.getLatSouth());
    double randomLon = bounds.getLonWest() + generator.nextDouble()
      * (bounds.getLonEast() - bounds.getLonWest());
    return new LatLng(randomLat, randomLon);
  }

  @Override
  protected void onStart() {
    super.onStart();
    mapView.onStart();
  }

  @Override
  protected void onResume() {
    super.onResume();
    mapView.onResume();
  }

  @Override
  protected void onPause() {
    super.onPause();
    mapView.onPause();
  }

  @Override
  protected void onStop() {
    super.onStop();
    mapView.onStop();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();

    for (Animator animator : animators) {
      if (animator != null) {
        animator.removeAllListeners();
        animator.cancel();
      }
    }

    mapView.onDestroy();
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
  }

  /**
   * Evaluator for LatLng pairs
   */
  private static class LatLngEvaluator implements TypeEvaluator<LatLng> {

    private LatLng latLng = new LatLng();

    @Override
    public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
      latLng.setLatitude(startValue.getLatitude()
        + ((endValue.getLatitude() - startValue.getLatitude()) * fraction));
      latLng.setLongitude(startValue.getLongitude()
        + ((endValue.getLongitude() - startValue.getLongitude()) * fraction));
      return latLng;
    }
  }


  private static class Car {
    private Feature feature;
    private LatLng next;
    private LatLng current;
    private long duration;

    Car(Feature feature, LatLng next, long duration) {
      this.feature = feature;
      Point point = ((Point) feature.geometry());
      this.current = new LatLng(point.latitude(), point.longitude());
      this.duration = duration;
      this.next = next;
    }

    void setNext(LatLng next) {
      this.next = next;
    }

    void updateFeature() {
      feature = Feature.fromGeometry(Point.fromLngLat(
        current.getLongitude(),
        current.getLatitude())
      );
      feature.properties().addProperty("bearing", getBearing(current, next));
    }

    private static float getBearing(LatLng from, LatLng to) {
      return (float) TurfMeasurement.bearing(
        Point.fromLngLat(from.getLongitude(), from.getLatitude()),
        Point.fromLngLat(to.getLongitude(), to.getLatitude())
      );
    }
  }
}