summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java
blob: 6424de342e36f3965640be0e6888d38c4f6caff1 (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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
package com.mapbox.mapboxsdk.maps;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.PointF;
import android.location.Location;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ScaleGestureDetectorCompat;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.InputDevice;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;

import com.almeros.android.multitouch.gesturedetectors.RotateGestureDetector;
import com.almeros.android.multitouch.gesturedetectors.ShoveGestureDetector;
import com.almeros.android.multitouch.gesturedetectors.TwoFingerGestureDetector;
import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.services.android.telemetry.MapboxEvent;
import com.mapbox.services.android.telemetry.MapboxTelemetry;
import com.mapbox.services.android.telemetry.utils.MathUtils;
import com.mapbox.services.android.telemetry.utils.TelemetryUtils;

import java.util.concurrent.CopyOnWriteArrayList;

import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_API_GESTURE;

/**
 * Manages gestures events on a MapView.
 * <p>
 * Relies on gesture detection code in almeros.android.multitouch.gesturedetectors.
 * </p>
 */
final class MapGestureDetector {

  private final Transform transform;
  private final Projection projection;
  private final UiSettings uiSettings;
  private final TrackingSettings trackingSettings;
  private final AnnotationManager annotationManager;
  private final CameraChangeDispatcher cameraChangeDispatcher;

  private GestureDetectorCompat gestureDetector;
  private ScaleGestureDetector scaleGestureDetector;
  private RotateGestureDetector rotateGestureDetector;
  private ShoveGestureDetector shoveGestureDetector;

  // deprecated map touch API
  private MapboxMap.OnMapClickListener onMapClickListener;
  private MapboxMap.OnMapLongClickListener onMapLongClickListener;
  private MapboxMap.OnFlingListener onFlingListener;
  private MapboxMap.OnScrollListener onScrollListener;

  // new map touch API
  private final CopyOnWriteArrayList<MapboxMap.OnMapClickListener> onMapClickListenerList
    = new CopyOnWriteArrayList<>();

  private final CopyOnWriteArrayList<MapboxMap.OnMapLongClickListener> onMapLongClickListenerList
    = new CopyOnWriteArrayList<>();

  private final CopyOnWriteArrayList<MapboxMap.OnFlingListener> onFlingListenerList
    = new CopyOnWriteArrayList<>();

  private final CopyOnWriteArrayList<MapboxMap.OnScrollListener> onScrollListenerList
    = new CopyOnWriteArrayList<>();

  private PointF focalPoint;

  private boolean twoTap;
  private boolean quickZoom;
  private boolean tiltGestureOccurred;
  private boolean scrollGestureOccurred;

  private boolean scaleGestureOccurred;
  private boolean recentScaleGestureOccurred;
  private boolean scaleAnimating;
  private long scaleBeginTime;

  private VelocityTracker velocityTracker;
  private boolean wasZoomingIn;
  private boolean wasClockwiseRotating;
  private boolean rotateGestureOccurred;

  MapGestureDetector(Context context, Transform transform, Projection projection, UiSettings uiSettings,
                     TrackingSettings trackingSettings, AnnotationManager annotationManager,
                     CameraChangeDispatcher cameraChangeDispatcher) {
    this.annotationManager = annotationManager;
    this.transform = transform;
    this.projection = projection;
    this.uiSettings = uiSettings;
    this.trackingSettings = trackingSettings;
    this.cameraChangeDispatcher = cameraChangeDispatcher;

    // Touch gesture detectors
    if (context != null) {
      gestureDetector = new GestureDetectorCompat(context, new GestureListener());
      gestureDetector.setIsLongpressEnabled(true);
      scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener());
      ScaleGestureDetectorCompat.setQuickScaleEnabled(scaleGestureDetector, true);
      rotateGestureDetector = new RotateGestureDetector(context, new RotateGestureListener());
      shoveGestureDetector = new ShoveGestureDetector(context, new ShoveGestureListener());
    }
  }

  /**
   * Set the gesture focal point.
   * <p>
   * this is the center point used for calculate transformations from gestures, value is
   * overridden if end user provides his own through {@link UiSettings#setFocalPoint(PointF)}.
   * </p>
   *
   * @param focalPoint the center point for gestures
   */
  void setFocalPoint(PointF focalPoint) {
    if (focalPoint == null) {
      // resetting focal point,
      if (uiSettings.getFocalPoint() != null) {
        // using user provided one to reset
        focalPoint = uiSettings.getFocalPoint();
      }
    }
    this.focalPoint = focalPoint;
  }

  /**
   * Get the current active gesture focal point.
   * <p>
   * This could be either the user provided focal point in {@link UiSettings#setFocalPoint(PointF)} or the focal point
   * defined as a result of {@link TrackingSettings#setMyLocationEnabled(boolean)}.
   * </p>
   *
   * @return the current active gesture focal point.
   */
  @Nullable
  PointF getFocalPoint() {
    return focalPoint;
  }

  /**
   * Given coordinates from a gesture, use the current projection to translate it into
   * a Location object.
   *
   * @param x coordinate
   * @param y coordinate
   * @return location
   */
  private Location getLocationFromGesture(float x, float y) {
    LatLng latLng = projection.fromScreenLocation(new PointF(x, y));
    return TelemetryUtils.buildLocation(latLng.getLongitude(), latLng.getLatitude());
  }

  /**
   * Called when user touches the screen, all positions are absolute.
   * <p>
   * Forwards event to the related gesture detectors.
   * </p>
   *
   * @param event the MotionEvent
   * @return True if touch event is handled
   */
  boolean onTouchEvent(MotionEvent event) {
    // framework can return null motion events in edge cases #9432
    if (event == null) {
      return false;
    }

    // Check and ignore non touch or left clicks
    if ((event.getButtonState() != 0) && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) {
      return false;
    }

    // Check two finger gestures first
    scaleGestureDetector.onTouchEvent(event);
    rotateGestureDetector.onTouchEvent(event);
    shoveGestureDetector.onTouchEvent(event);

    // Handle two finger tap
    switch (event.getActionMasked()) {
      case MotionEvent.ACTION_DOWN:
        if (velocityTracker == null) {
          velocityTracker = VelocityTracker.obtain();
        } else {
          velocityTracker.clear();
        }
        velocityTracker.addMovement(event);
        // First pointer down, reset scaleGestureOccurred, used to avoid triggering a fling after a scale gesture #7666
        recentScaleGestureOccurred = false;
        transform.setGestureInProgress(true);
        break;

      case MotionEvent.ACTION_POINTER_DOWN:
        // Second pointer down
        twoTap = event.getPointerCount() == 2
          && uiSettings.isZoomGesturesEnabled();
        if (twoTap) {
          // Confirmed 2nd Finger Down
          MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
            getLocationFromGesture(event.getX(), event.getY()),
            MapboxEvent.GESTURE_TWO_FINGER_SINGLETAP, transform));
        }
        break;

      case MotionEvent.ACTION_POINTER_UP:
        // Second pointer up
        break;

      case MotionEvent.ACTION_UP:
        // First pointer up
        long tapInterval = event.getEventTime() - event.getDownTime();
        boolean isTap = tapInterval <= ViewConfiguration.getTapTimeout();
        boolean inProgress = rotateGestureDetector.isInProgress()
          || scaleGestureDetector.isInProgress()
          || shoveGestureDetector.isInProgress();

        if (twoTap && isTap && !inProgress) {
          if (focalPoint != null) {
            transform.zoom(false, focalPoint);
          } else {
            PointF focalPoint = TwoFingerGestureDetector.determineFocalPoint(event);
            transform.zoom(false, focalPoint);
          }
          twoTap = false;
          return true;
        }

        // Scroll / Pan Has Stopped
        if (scrollGestureOccurred) {
          MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapDragEndEvent(
            getLocationFromGesture(event.getX(), event.getY()), transform));
          scrollGestureOccurred = false;
          cameraChangeDispatcher.onCameraIdle();
        }

        twoTap = false;
        transform.setGestureInProgress(false);
        if (velocityTracker != null) {
          velocityTracker.recycle();
        }
        velocityTracker = null;
        break;

      case MotionEvent.ACTION_CANCEL:
        twoTap = false;
        transform.setGestureInProgress(false);
        if (velocityTracker != null) {
          velocityTracker.recycle();
        }
        velocityTracker = null;
        break;
      case MotionEvent.ACTION_MOVE:
        if (velocityTracker != null) {
          velocityTracker.addMovement(event);
          velocityTracker.computeCurrentVelocity(1000);
        }
        break;
    }

    return gestureDetector.onTouchEvent(event);
  }

  /**
   * Called for events that don't fit the other handlers.
   * <p>
   * Examples of such events are mouse scroll events, mouse moves, joystick & trackpad.
   * </p>
   *
   * @param event The MotionEvent occured
   * @return True is the event is handled
   */
  boolean onGenericMotionEvent(MotionEvent event) {
    // Mouse events
    // if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { // this is not available before API 18
    if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == InputDevice.SOURCE_CLASS_POINTER) {
      // Choose the action
      switch (event.getActionMasked()) {
        // Mouse scrolls
        case MotionEvent.ACTION_SCROLL:
          if (!uiSettings.isZoomGesturesEnabled()) {
            return false;
          }

          // Cancel any animation
          transform.cancelTransitions();

          // Get the vertical scroll amount, one click = 1
          float scrollDist = event.getAxisValue(MotionEvent.AXIS_VSCROLL);

          // Scale the map by the appropriate power of two factor
          transform.zoomBy(scrollDist, event.getX(), event.getY());

          return true;

        default:
          // We are not interested in this event
          return false;
      }
    }

    // We are not interested in this event
    return false;
  }

  /**
   * Responsible for handling one finger gestures.
   */
  private class GestureListener extends android.view.GestureDetector.SimpleOnGestureListener {

    @Override
    public boolean onDown(MotionEvent event) {
      return true;
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
      if (!uiSettings.isZoomGesturesEnabled() || !uiSettings.isDoubleTapGesturesEnabled()) {
        return false;
      }

      switch (e.getAction()) {
        case MotionEvent.ACTION_DOWN:
          break;
        case MotionEvent.ACTION_MOVE:
          break;
        case MotionEvent.ACTION_UP:
          if (quickZoom) {
            cameraChangeDispatcher.onCameraIdle();
            quickZoom = false;
            break;
          }

          // notify camera change listener
          cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);

          // Single finger double tap
          if (focalPoint != null) {
            // User provided focal point
            transform.zoom(true, focalPoint);
          } else {
            // Zoom in on gesture
            transform.zoom(true, new PointF(e.getX(), e.getY()));
          }
          break;
      }

      MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
        getLocationFromGesture(e.getX(), e.getY()),
        MapboxEvent.GESTURE_DOUBLETAP, transform));

      return true;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
      // Cancel any animation
      transform.cancelTransitions();
      return true;
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
      PointF tapPoint = new PointF(motionEvent.getX(), motionEvent.getY());
      boolean tapHandled = annotationManager.onTap(tapPoint);

      if (!tapHandled) {
        if (uiSettings.isDeselectMarkersOnTap()) {
          // deselect any selected marker
          annotationManager.deselectMarkers();
        }

        notifyOnMapClickListeners(tapPoint);
      }

      MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
        getLocationFromGesture(motionEvent.getX(), motionEvent.getY()),
        MapboxEvent.GESTURE_SINGLETAP, transform));

      return true;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {
      PointF longClickPoint = new PointF(motionEvent.getX(), motionEvent.getY());

      if (!quickZoom) {
        notifyOnMapLongClickListeners(longClickPoint);
      }
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
      if ((!trackingSettings.isScrollGestureCurrentlyEnabled()) || recentScaleGestureOccurred) {
        // don't allow a fling is scroll is disabled
        // and ignore when a scale gesture has occurred
        return false;
      }

      float screenDensity = uiSettings.getPixelRatio();

      // calculate velocity vector for xy dimensions, independent from screen size
      double velocityXY = Math.hypot(velocityX / screenDensity, velocityY / screenDensity);
      if (velocityXY < MapboxConstants.VELOCITY_THRESHOLD_IGNORE_FLING) {
        // ignore short flings, these can occur when other gestures just have finished executing
        return false;
      }

      trackingSettings.resetTrackingModesIfRequired(true, false, false);

      // cancel any animation
      transform.cancelTransitions();

      cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);

      // tilt results in a bigger translation, limiting input for #5281
      double tilt = transform.getTilt();
      double tiltFactor = 1.5 + ((tilt != 0) ? (tilt / 10) : 0);
      double offsetX = velocityX / tiltFactor / screenDensity;
      double offsetY = velocityY / tiltFactor / screenDensity;

      // calculate animation time based on displacement
      long animationTime = (long) (velocityXY / 7 / tiltFactor + MapboxConstants.ANIMATION_DURATION_FLING_BASE);

      // update transformation
      transform.moveBy(offsetX, offsetY, animationTime);

      notifyOnFlingListeners();
      return true;
    }

    // Called for drags
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
      if (!trackingSettings.isScrollGestureCurrentlyEnabled()) {
        return false;
      }

      if (tiltGestureOccurred) {
        return false;
      }

      if (!scrollGestureOccurred) {
        scrollGestureOccurred = true;

        // Cancel any animation
        if (!scaleGestureOccurred) {
          transform.cancelTransitions();
          cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);
        }

        MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
          getLocationFromGesture(e1.getX(), e1.getY()),
          MapboxEvent.GESTURE_PAN_START, transform));
      }

      // reset tracking if needed
      trackingSettings.resetTrackingModesIfRequired(true, false, false);

      // Scroll the map
      transform.moveBy(-distanceX, -distanceY, 0 /*no duration*/);

      notifyOnScrollListeners();
      return true;
    }
  }

  void notifyOnMapClickListeners(PointF tapPoint) {
    // deprecated API
    if (onMapClickListener != null) {
      onMapClickListener.onMapClick(projection.fromScreenLocation(tapPoint));
    }

    // new API
    for (MapboxMap.OnMapClickListener listener : onMapClickListenerList) {
      listener.onMapClick(projection.fromScreenLocation(tapPoint));
    }
  }

  void notifyOnMapLongClickListeners(PointF longClickPoint) {
    // deprecated API
    if (onMapLongClickListener != null) {
      onMapLongClickListener.onMapLongClick(projection.fromScreenLocation(longClickPoint));
    }

    // new API
    for (MapboxMap.OnMapLongClickListener listener : onMapLongClickListenerList) {
      listener.onMapLongClick(projection.fromScreenLocation(longClickPoint));
    }
  }

  void notifyOnFlingListeners() {
    // deprecated API
    if (onFlingListener != null) {
      onFlingListener.onFling();
    }

    // new API
    for (MapboxMap.OnFlingListener listener : onFlingListenerList) {
      listener.onFling();
    }
  }

  void notifyOnScrollListeners() {
    //deprecated API
    if (onScrollListener != null) {
      onScrollListener.onScroll();
    }

    // new API
    for (MapboxMap.OnScrollListener listener : onScrollListenerList) {
      listener.onScroll();
    }
  }

  /**
   * Responsible for handling two finger gestures and double-tap drag gestures.
   */
  private class ScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    private static final int ANIMATION_TIME_MULTIPLIER = 77;
    private static final double ZOOM_DISTANCE_DIVIDER = 5;

    private float scaleFactor = 1.0f;
    private PointF scalePointBegin;

    // Called when two fingers first touch the screen
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
      if (!uiSettings.isZoomGesturesEnabled()) {
        return false;
      }

      recentScaleGestureOccurred = true;
      scalePointBegin = new PointF(detector.getFocusX(), detector.getFocusY());
      scaleBeginTime = detector.getEventTime();
      MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
        getLocationFromGesture(detector.getFocusX(), detector.getFocusY()),
        MapboxEvent.GESTURE_PINCH_START, transform));
      return true;
    }

    // Called each time a finger moves
    // Called for pinch zooms and quickzooms/quickscales
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
      if (!uiSettings.isZoomGesturesEnabled()) {
        return super.onScale(detector);
      }

      wasZoomingIn = (Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2)) > 0;
      if (tiltGestureOccurred) {
        return false;
      }

      // Ignore short touches in case it is a tap
      // Also ignore small scales
      long time = detector.getEventTime();
      long interval = time - scaleBeginTime;
      if (!scaleGestureOccurred && (interval <= ViewConfiguration.getTapTimeout())) {
        return false;
      }

      // If scale is large enough ignore a tap
      scaleFactor *= detector.getScaleFactor();
      if ((scaleFactor > 1.1f) || (scaleFactor < 0.9f)) {
        // notify camera change listener
        cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);
        scaleGestureOccurred = true;
      }

      if (!scaleGestureOccurred) {
        return false;
      }

      // Gesture is a quickzoom if there aren't two fingers
      if (!quickZoom && !twoTap) {
        cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);
      }
      quickZoom = !twoTap;

      // make an assumption here; if the zoom center is specified by the gesture, it's NOT going
      // to be in the center of the map. Therefore the zoom will translate the map center, so tracking
      // should be disabled.
      trackingSettings.resetTrackingModesIfRequired(!quickZoom, false, false);
      // Scale the map
      if (focalPoint != null) {
        // arround user provided focal point
        transform.zoomBy(Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2), focalPoint.x, focalPoint.y);
      } else if (quickZoom) {
        cameraChangeDispatcher.onCameraMove();
        // clamp scale factors we feed to core #7514
        float scaleFactor = detector.getScaleFactor();
        // around center map
        double zoomBy = Math.log(scaleFactor) / Math.log(Math.PI / 2);
        boolean negative = zoomBy < 0;
        zoomBy = MathUtils.clamp(Math.abs(zoomBy),
          MapboxConstants.MINIMUM_SCALE_FACTOR_CLAMP,
          MapboxConstants.MAXIMUM_SCALE_FACTOR_CLAMP);
        transform.zoomBy(negative ? -zoomBy : zoomBy, uiSettings.getWidth() / 2, uiSettings.getHeight() / 2);
        recentScaleGestureOccurred = true;
      } else {
        // around gesture
        transform.zoomBy(Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2),
          scalePointBegin.x, scalePointBegin.y);
      }
      return true;
    }

    // Called when fingers leave screen
    @Override
    public void onScaleEnd(final ScaleGestureDetector detector) {
      if (velocityTracker == null) {
        return;
      }


      if (rotateGestureOccurred || quickZoom) {
        reset();
        return;
      }

      double velocityXY = Math.abs(velocityTracker.getYVelocity()) + Math.abs(velocityTracker.getXVelocity());
      if (velocityXY > MapboxConstants.VELOCITY_THRESHOLD_IGNORE_FLING / 2) {
        scaleAnimating = true;
        double zoomAddition = calculateScale(velocityXY);
        double currentZoom = transform.getRawZoom();
        long animationTime = (long) (Math.log(velocityXY) * ANIMATION_TIME_MULTIPLIER);
        createScaleAnimator(currentZoom, zoomAddition, animationTime).start();
      } else if (!scaleAnimating) {
        reset();
      }
    }

    private void reset() {
      scaleAnimating = false;
      scaleGestureOccurred = false;
      scaleBeginTime = 0;
      scaleFactor = 1.0f;
      cameraChangeDispatcher.onCameraIdle();
    }

    private double calculateScale(double velocityXY) {
      double zoomAddition = (float) (Math.log(velocityXY) / ZOOM_DISTANCE_DIVIDER);
      if (!wasZoomingIn) {
        zoomAddition = -zoomAddition;
      }
      return zoomAddition;
    }

    private Animator createScaleAnimator(double currentZoom, double zoomAddition, long animationTime) {
      ValueAnimator animator = ValueAnimator.ofFloat((float) currentZoom, (float) (currentZoom + zoomAddition));
      animator.setDuration(animationTime);
      animator.setInterpolator(new FastOutSlowInInterpolator());
      animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
          transform.setZoom((Float) animation.getAnimatedValue(), scalePointBegin);
        }
      });
      animator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
          super.onAnimationEnd(animation);
          reset();
        }
      });
      return animator;
    }
  }

  /**
   * Responsible for handling rotation gestures.
   */
  private class RotateGestureListener extends RotateGestureDetector.SimpleOnRotateGestureListener {

    private static final float ROTATE_INVOKE_ANGLE = 15.30f;
    private static final float ROTATE_LIMITATION_ANGLE = 3.35f;
    private static final float ROTATE_LIMITATION_DURATION = ROTATE_LIMITATION_ANGLE * 1.85f;

    private long beginTime = 0;
    private boolean started = false;
    private boolean animating = false;

    // Called when two fingers first touch the screen
    @Override
    public boolean onRotateBegin(RotateGestureDetector detector) {
      if (!trackingSettings.isRotateGestureCurrentlyEnabled()) {
        return false;
      }

      // notify camera change listener
      cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);

      beginTime = detector.getEventTime();
      return true;
    }

    // Called each time one of the two fingers moves
    // Called for rotation
    @Override
    public boolean onRotate(RotateGestureDetector detector) {
      if (!trackingSettings.isRotateGestureCurrentlyEnabled() || tiltGestureOccurred) {
        return false;
      }

      // If rotate is large enough ignore a tap
      // Also is zoom already started, don't rotate
      float angle = detector.getRotationDegreesDelta();
      if (Math.abs(angle) >= ROTATE_INVOKE_ANGLE) {
        MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
          getLocationFromGesture(detector.getFocusX(), detector.getFocusY()),
          MapboxEvent.GESTURE_ROTATION_START, transform));
        started = true;
      }

      if (!started) {
        return false;
      }

      wasClockwiseRotating = detector.getRotationDegreesDelta() > 0;
      if (scaleBeginTime != 0) {
        rotateGestureOccurred = true;
      }

      // rotation constitutes translation of anything except the center of
      // rotation, so cancel both location and bearing tracking if required
      trackingSettings.resetTrackingModesIfRequired(true, true, false);

      // Calculate map bearing value
      double bearing = transform.getRawBearing() + angle;

      // Rotate the map
      if (focalPoint != null) {
        // User provided focal point
        transform.setBearing(bearing, focalPoint.x, focalPoint.y);
      } else {
        // around gesture
        transform.setBearing(bearing, detector.getFocusX(), detector.getFocusY());
      }
      return true;
    }

    // Called when the fingers leave the screen
    @Override
    public void onRotateEnd(RotateGestureDetector detector) {
      long interval = detector.getEventTime() - beginTime;
      if ((!started && (interval <= ViewConfiguration.getTapTimeout())) || scaleAnimating || interval > 500) {
        reset();
        return;
      }

      double angularVelocity = calculateVelocityVector(detector);
      if (Math.abs(angularVelocity) > 0.001 && rotateGestureOccurred && !animating) {
        animateRotateVelocity();
      } else if (!animating) {
        reset();
      }
    }

    private void reset() {
      beginTime = 0;
      started = false;
      animating = false;
      rotateGestureOccurred = false;
    }

    private void animateRotateVelocity() {
      animating = true;
      double currentRotation = transform.getRawBearing();
      double rotateAdditionDegrees = calculateVelocityInDegrees();
      createAnimator(currentRotation, rotateAdditionDegrees).start();
    }

    private double calculateVelocityVector(RotateGestureDetector detector) {
      return ((detector.getFocusX() * velocityTracker.getYVelocity())
        + (detector.getFocusY() * velocityTracker.getXVelocity()))
        / (Math.pow(detector.getFocusX(), 2) + Math.pow(detector.getFocusY(), 2));
    }

    private double calculateVelocityInDegrees() {
      double angleRadians = Math.atan2(velocityTracker.getXVelocity(), velocityTracker.getYVelocity());
      double angle = angleRadians / (Math.PI / 180);
      if (angle <= 0) {
        angle += 360;
      }

      // limit the angle
      angle = angle / ROTATE_LIMITATION_ANGLE;

      // correct direction
      if (!wasClockwiseRotating) {
        angle = -angle;
      }

      return angle;
    }

    private Animator createAnimator(double currentRotation, double rotateAdditionDegrees) {
      ValueAnimator animator = ValueAnimator.ofFloat(
        (float) currentRotation,
        (float) (currentRotation + rotateAdditionDegrees)
      );
      animator.setDuration((long) (Math.abs(rotateAdditionDegrees) * ROTATE_LIMITATION_DURATION));
      animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
          transform.setBearing((Float) animation.getAnimatedValue());
        }
      });
      animator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
          super.onAnimationEnd(animation);
          reset();
        }
      });
      return animator;
    }
  }

  /**
   * Responsible for handling 2 finger shove gestures.
   */
  private class ShoveGestureListener implements ShoveGestureDetector.OnShoveGestureListener {

    private long beginTime = 0;
    private float totalDelta = 0.0f;

    @Override
    public boolean onShoveBegin(ShoveGestureDetector detector) {
      if (!uiSettings.isTiltGesturesEnabled()) {
        return false;
      }

      // notify camera change listener
      cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE);
      return true;
    }

    @Override
    public void onShoveEnd(ShoveGestureDetector detector) {
      beginTime = 0;
      totalDelta = 0.0f;
      tiltGestureOccurred = false;
    }

    @Override
    public boolean onShove(ShoveGestureDetector detector) {
      if (!uiSettings.isTiltGesturesEnabled()) {
        return false;
      }

      // Ignore short touches in case it is a tap
      // Also ignore small tilt
      long time = detector.getEventTime();
      long interval = time - beginTime;
      if (!tiltGestureOccurred && (interval <= ViewConfiguration.getTapTimeout())) {
        return false;
      }

      // If tilt is large enough ignore a tap
      // Also if zoom already started, don't tilt
      totalDelta += detector.getShovePixelsDelta();
      if (!tiltGestureOccurred && ((totalDelta > 10.0f) || (totalDelta < -10.0f))) {
        tiltGestureOccurred = true;
        beginTime = detector.getEventTime();
        MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent(
          getLocationFromGesture(detector.getFocusX(), detector.getFocusY()),
          MapboxEvent.GESTURE_PITCH_START, transform));
      }

      if (!tiltGestureOccurred) {
        return false;
      }

      // Get tilt value (scale and clamp)
      double pitch = transform.getTilt();
      pitch -= 0.1 * detector.getShovePixelsDelta();
      pitch = Math.max(MapboxConstants.MINIMUM_TILT, Math.min(MapboxConstants.MAXIMUM_TILT, pitch));

      // Tilt the map
      transform.setTilt(pitch);
      return true;
    }
  }

  void setOnMapClickListener(MapboxMap.OnMapClickListener onMapClickListener) {
    this.onMapClickListener = onMapClickListener;
  }

  void setOnMapLongClickListener(MapboxMap.OnMapLongClickListener onMapLongClickListener) {
    this.onMapLongClickListener = onMapLongClickListener;
  }

  void setOnFlingListener(MapboxMap.OnFlingListener onFlingListener) {
    this.onFlingListener = onFlingListener;
  }

  void setOnScrollListener(MapboxMap.OnScrollListener onScrollListener) {
    this.onScrollListener = onScrollListener;
  }

  void addOnMapClickListener(MapboxMap.OnMapClickListener onMapClickListener) {
    onMapClickListenerList.add(onMapClickListener);
  }

  void removeOnMapClickListener(MapboxMap.OnMapClickListener onMapClickListener) {
    onMapClickListenerList.remove(onMapClickListener);
  }

  void addOnMapLongClickListener(MapboxMap.OnMapLongClickListener onMapLongClickListener) {
    onMapLongClickListenerList.add(onMapLongClickListener);
  }

  void removeOnMapLongClickListener(MapboxMap.OnMapLongClickListener onMapLongClickListener) {
    onMapLongClickListenerList.remove(onMapLongClickListener);
  }

  void addOnFlingListener(MapboxMap.OnFlingListener onFlingListener) {
    onFlingListenerList.add(onFlingListener);
  }

  void removeOnFlingListener(MapboxMap.OnFlingListener onFlingListener) {
    onFlingListenerList.remove(onFlingListener);
  }

  void addOnScrollListener(MapboxMap.OnScrollListener onScrollListener) {
    onScrollListenerList.add(onScrollListener);
  }

  void removeOnScrollListener(MapboxMap.OnScrollListener onScrollListener) {
    onScrollListenerList.remove(onScrollListener);
  }
}