summaryrefslogtreecommitdiff
path: root/android/java/lib/src/main/java/com/mapbox/mapboxgl/lib/MapView.java
blob: f664f2cf0b97fc8bed5b88006e2ff0d359aea129 (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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
package com.mapbox.mapboxgl.lib;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ZoomButtonsController;

import com.almeros.android.multitouch.gesturedetectors.RotateGestureDetector;
import com.almeros.android.multitouch.gesturedetectors.TwoFingerGestureDetector;
import com.arieslabs.assetbridge.Assetbridge;

// Custom view that shows a Map
// Based on SurfaceView as we use OpenGL ES to render
public class MapView extends SurfaceView {

    //
    // Static members
    //

    // Tag used for logging
    private static final String TAG = "MapView";

    // Used for saving instance state
    private static final String STATE_CENTER_COORDINATE = "centerCoordinate";
    private static final String STATE_CENTER_DIRECTION = "centerDirection";
    private static final String STATE_ZOOM_LEVEL = "zoomLevel";
    private static final String STATE_ZOOM_ENABLED = "zoomEnabled";
    private static final String STATE_SCROLL_ENABLED = "scrollEnabled";
    private static final String STATE_ROTATE_ENABLED = "rotateEnabled";
    private static final String STATE_DEBUG_ACTIVE = "debugActive";

    //
    // Instance members
    //

    // Used to call JNI NativeMapView
    private NativeMapView mNativeMapView;

    // Used to style the map
    private String mStyleUrl;

    // Used to load map tiles
    private String mAccessToken;

    // Used to handle DPI scaling
    private float mScreenDensity = 1.0f;

    // Touch gesture detectors
    private GestureDetector mGestureDetector;
    private ScaleGestureDetector mScaleGestureDetector;
    private RotateGestureDetector mRotateGestureDetector;
    private boolean mTwoTap = false;

    // Shows zoom buttons
    private ZoomButtonsController mZoomButtonsController;

    // Used to track trackball long presses
    private TrackballLongPressTimeOut mCurrentTrackballLongPressTimeOut;

    // Used to check connection status
    private ConnectivityManager mConnectivityManager;
    private ConnectivityReceiver mConnectivityReceiver;

    // Holds the context
    private Context mContext;

    //
    // Properties
    //

    private boolean mZoomEnabled = true;
    private boolean mScrollEnabled = true;
    private boolean mRotateEnabled = true;

    //
    // Constructors
    //

    // Called when no properties are being set from XML
    public MapView(Context context) {
        super(context);
        initialize(context, null);
    }

    // Called when properties are being set from XML
    public MapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }

    // Called when properties are being set from XML
    public MapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize(context, attrs);
    }

    //
    // Initialization
    //

    // Common initialization code goes here
    private void initialize(Context context, AttributeSet attrs) {
        Log.v(TAG, "initialize");

        // Save the context
        mContext = context;

        // Check if we are in Eclipse UI editor
        if (isInEditMode()) {
            // TODO editor does not load properly because we don't implement this
            return;
        }

        // Get the screen's density
        mScreenDensity = context.getResources().getDisplayMetrics().density;

        // Get the cache path
        String cachePath = context.getCacheDir().getAbsolutePath();
        String dataPath = context.getFilesDir().getAbsolutePath();

        // Extract the asset files
        Assetbridge.unpack(context);

        // Load the map style and API key
        //mStyleUrl = "https://mapbox.github.io/mapbox-gl-styles/styles/bright-v6.json";
        mStyleUrl = "file://" + dataPath + "/styles/styles/bright-v6.json";
        mAccessToken = "pk.eyJ1IjoibGpiYWRlIiwiYSI6IlJSQ0FEZ2MifQ.7mE4aOegldh3595AG9dxpQ";

        // Are we a debug build?
        boolean isDebuggable = (context.getApplicationInfo().flags &
                ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE;

        // Create the NativeMapView
        mNativeMapView = new NativeMapView(this, cachePath, dataPath);
        mNativeMapView.setStyleURL(mStyleUrl);
        mNativeMapView.setAccessToken(mAccessToken);
        mNativeMapView.setDebug(isDebuggable);

        // Load the attributes
        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.MapView, 0, 0);
        try {
            double centerLongitude = typedArray.getFloat(
                    R.styleable.MapView_centerLongitude, 0.0f);
            double centerLatitude = typedArray.getFloat(
                    R.styleable.MapView_centerLatitude, 0.0f);
            LonLat centerCoordinate = new LonLat(centerLongitude,
                    centerLatitude);
            setCenterCoordinate(centerCoordinate);
            setDirection(typedArray.getFloat(R.styleable.MapView_direction,
                    0.0f));
            setZoomLevel(typedArray.getFloat(R.styleable.MapView_zoomLevel,
                    0.0f));
            setZoomEnabled(typedArray.getBoolean(
                    R.styleable.MapView_zoomEnabled, true));
            setScrollEnabled(typedArray.getBoolean(
                    R.styleable.MapView_scrollEnabled, true));
            setRotateEnabled(typedArray.getBoolean(
                    R.styleable.MapView_rotateEnabled, true));
            setDebugActive(typedArray.getBoolean(
                    R.styleable.MapView_debugActive, true));
        } finally {
            typedArray.recycle();
        }

        // Ensure this view is interactable
        setClickable(true);
        setLongClickable(true);
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();

        // Register the SurfaceHolder callbacks
        getHolder().addCallback(new Callbacks());

        // Touch gesture detectors
        mGestureDetector = new GestureDetector(context, new GestureListener());
        mGestureDetector.setIsLongpressEnabled(true);
        mScaleGestureDetector = new ScaleGestureDetector(context,
                new ScaleGestureListener());
        mRotateGestureDetector = new RotateGestureDetector(context,
                new RotateGestureListener());

        // Shows the zoom controls
        // But not when in Eclipse UI editor
        if (!isInEditMode()) {
            if (!context.getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)) {
                mZoomButtonsController = new ZoomButtonsController(this);
                mZoomButtonsController.setZoomSpeed(300);
                mZoomButtonsController.setOnZoomListener(new OnZoomListener());
            }

            // Check current connection status
            mConnectivityManager = (ConnectivityManager)context.getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = mConnectivityManager.getActiveNetworkInfo();
            boolean isConnected = (activeNetwork != null) &&
                    activeNetwork.isConnectedOrConnecting();
            onConnectivityChanged(isConnected);
        }
    }

    //
    // Property methods
    //

    public LonLat getCenterCoordinate() {
        return mNativeMapView.getLonLat();
    }

    public void setCenterCoordinate(LonLat centerCoordinate) {
        setCenterCoordinate(centerCoordinate, false);
    }

    public void setCenterCoordinate(LonLat centerCoordinate, boolean animated) {
        double duration = animated ? 0.3 : 0.0;
        mNativeMapView.setLonLat(centerCoordinate, duration);
    }

    public void setCenterCoordinate(LonLatZoom centerCoordinate) {
        setCenterCoordinate(centerCoordinate, false);
    }

    public void setCenterCoordinate(LonLatZoom centerCoordinate,
            boolean animated) {
        double duration = animated ? 0.3 : 0.0;
        mNativeMapView.setLonLatZoom(centerCoordinate, duration);
    }

    public double getDirection() {
        double direction = -mNativeMapView.getBearing();

        while (direction > 360)
            direction -= 360;
        while (direction < 0)
            direction += 360;

        return direction;
    }

    public void setDirection(double direction) {
        setDirection(direction, false);
    }

    public void setDirection(double direction, boolean animated) {
        double duration = animated ? 0.3 : 0.0;

        mNativeMapView.setBearing(-direction, duration);
    }

    public void resetPosition() {
        mNativeMapView.resetPosition();
    }

    public void resetNorth() {
        mNativeMapView.resetNorth();
    }

    public double getZoomLevel() {
        return mNativeMapView.getZoom();
    }

    public void setZoomLevel(double zoomLevel) {
        setZoomLevel(zoomLevel, false);
    }

    public void setZoomLevel(double zoomLevel, boolean animated) {
        double duration = animated ? 0.3 : 0.0;
        mNativeMapView.setZoom(zoomLevel, duration);
    }

    public boolean isZoomEnabled() {
        return mZoomEnabled;
    }

    public void setZoomEnabled(boolean zoomEnabled) {
        this.mZoomEnabled = zoomEnabled;

        if ((mZoomButtonsController != null)
                && (getVisibility() == View.VISIBLE) && mZoomEnabled) {
            mZoomButtonsController.setVisible(true);
        }
    }

    public boolean isScrollEnabled() {
        return mScrollEnabled;
    }

    public void setScrollEnabled(boolean scrollEnabled) {
        this.mScrollEnabled = scrollEnabled;
    }

    public boolean isRotateEnabled() {
        return mRotateEnabled;
    }

    public void setRotateEnabled(boolean rotateEnabled) {
        this.mRotateEnabled = rotateEnabled;
    }

    public boolean isDebugActive() {
        return mNativeMapView.getDebug();
    }

    public void setDebugActive(boolean debugActive) {
        mNativeMapView.setDebug(debugActive);
    }

    public void toggleDebug() {
        mNativeMapView.toggleDebug();
    }

    //
    // Style methods
    //

    public void toggleStyle() {
        // TODO
    }

    // TODO seems like JSON simple may be better since it implements Map
    // interface
    // Other candidates: fastjson, json-smart, fossnova json,
    public JSONObject getRawStyle() {
        try {
            return new JSONObject(mNativeMapView.getStyleJSON());
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void setRawStyle(JSONObject style) {
        mNativeMapView.setStyleJSON(style.toString());
    }

    public void getStyleOrderedLayerNames() {
        // TODO
    }

    public void setStyleOrderedLayerNames() {
        // TODO
    }

    public void getAllStyleClasses() {
        // TODO
    }

    public void getAppliedStyleClasses() {
        // TODO
    }

    public void setAppliedStyleClasses() {
        // TODO
    }

    public void getStyleDescriptionForLayer() {
        // TODO
    }

    public void setStyleDescription() {
        // TODO
    }

    //
    // Lifecycle events
    //

    // Called when we need to restore instance state
    // Must be called from Activity onCreate
    public void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "onCreate");
        if (savedInstanceState != null) {
            setCenterCoordinate((LonLat) savedInstanceState
                    .getParcelable(STATE_CENTER_COORDINATE));
            setDirection(savedInstanceState.getDouble(STATE_CENTER_DIRECTION));
            setZoomLevel(savedInstanceState.getDouble(STATE_ZOOM_LEVEL));
            setZoomEnabled(savedInstanceState.getBoolean(STATE_ZOOM_ENABLED));
            setScrollEnabled(savedInstanceState
                    .getBoolean(STATE_SCROLL_ENABLED));
            setRotateEnabled(savedInstanceState
                    .getBoolean(STATE_ROTATE_ENABLED));
            setDebugActive(savedInstanceState.getBoolean(STATE_DEBUG_ACTIVE));
        }

        mNativeMapView.initializeDisplay();
        mNativeMapView.initializeContext();
        mNativeMapView.start();
    }

    // Called when we need to save instance state
    // Must be called from Activity onSaveInstanceState
    public void onSaveInstanceState(Bundle outState) {
        Log.v(TAG, "onSaveInstanceState");
        outState.putParcelable(STATE_CENTER_COORDINATE, getCenterCoordinate());
        outState.putDouble(STATE_CENTER_DIRECTION, getDirection());
        outState.putDouble(STATE_ZOOM_LEVEL, getZoomLevel());
        outState.putBoolean(STATE_ZOOM_ENABLED, isZoomEnabled());
        outState.putBoolean(STATE_SCROLL_ENABLED, isScrollEnabled());
        outState.putBoolean(STATE_ROTATE_ENABLED, isRotateEnabled());
        outState.putBoolean(STATE_DEBUG_ACTIVE, isDebugActive());
    }

    // Called when we need to clean up
    // Must be called from Activity onDestroy
    public void onDestroy() {
        Log.v(TAG, "onDestroy");
        mNativeMapView.stop();
        mNativeMapView.terminateContext();
        mNativeMapView.terminateDisplay();
    }

    // Called when we need to create the GL context
    // Must be called from Activity onStart
    public void onStart() {
        Log.v(TAG, "onStart");
        //mNativeMapView.start();
    }

    // Called when we need to terminate the GL context
    // Must be called from Activity onPause
    public void onStop() {
        Log.v(TAG, "onStop");
        //mNativeMapView.stop();
    }

    // Called when we need to stop the render thread
    // Must be called from Activity onPause
    public void onPause() {
        Log.v(TAG, "onPause");

        // Register for connectivity changes
        getContext().unregisterReceiver(mConnectivityReceiver);
        mConnectivityReceiver = null;

        mNativeMapView.pause();
    }

    // Called when we need to start the render thread
    // Must be called from Activity onResume

    public void onResume() {
        Log.v(TAG, "onResume");

        // Register for connectivity changes
        mConnectivityReceiver = new ConnectivityReceiver();
        mContext.registerReceiver(mConnectivityReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        mNativeMapView.resume();
    }

    // This class handles SurfaceHolder callbacks
    private class Callbacks implements SurfaceHolder.Callback2 {

        // Called when we need to redraw the view
        // This is called before our view is first visible to prevent an initial
        // flicker (see Android SDK documentation)
        @Override
        public void surfaceRedrawNeeded(SurfaceHolder holder) {
            Log.v(TAG, "surfaceRedrawNeeded");
            mNativeMapView.update();
        }

        // Called when the native surface buffer has been created
        // Must do all EGL/GL ES initialization here
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            Log.v(TAG, "surfaceCreated");
            mNativeMapView.createSurface(holder.getSurface());
        }

        // Called when the native surface buffer has been destroyed
        // Must do all EGL/GL ES destruction here
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.v(TAG, "surfaceDestroyed");
            mNativeMapView.destroySurface();
        }

        // Called when the format or size of the native surface buffer has been
        // changed
        // Must handle window resizing here.
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            Log.v(TAG, "surfaceChanged");
            Log.i(TAG, "resize " + format + " " + width + " " + height);
            mNativeMapView.resize((int) (width / mScreenDensity), (int) (height / mScreenDensity),
                    mScreenDensity, width, height);
        }
    }

    // TODO examine how GLSurvaceView hadles attach/detach from window

    // Called when view is no longer connected
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // Required by ZoomButtonController (from Android SDK documentation)
        if (mZoomButtonsController != null) {
            mZoomButtonsController.setVisible(false);
        }
    }

    // Called when view is hidden and shown
    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
        // Required by ZoomButtonController (from Android SDK documentation)
        if ((mZoomButtonsController != null) && (visibility != View.VISIBLE)) {
            mZoomButtonsController.setVisible(false);
        }
        if ((mZoomButtonsController != null) && (visibility == View.VISIBLE)
                && mZoomEnabled) {
            mZoomButtonsController.setVisible(true);
        }
    }

    //
    // Draw events
    //

    // TODO: onDraw for UI editor mockup?
    // By default it just shows a gray screen with "MapView"
    // Not too important but perhaps we could put a static demo map image there

    //
    // Input events
    //

    // Zoom in or out
    private void zoom(boolean zoomIn) {
        zoom(zoomIn, -1.0f, -1.0f);
    }

    private void zoom(boolean zoomIn, float x, float y) {
        // Cancel any animation
        mNativeMapView.cancelTransitions();

        if (zoomIn) {
            mNativeMapView.scaleBy(2.0, x / mScreenDensity, y / mScreenDensity, 0.3);
        } else {
            // TODO two finger tap zoom out
            mNativeMapView.scaleBy(0.5, x / mScreenDensity, y / mScreenDensity, 0.3);
        }
    }

    // Called when user touches the screen, all positions are absolute
    @Override
    public boolean onTouchEvent(@NonNull MotionEvent event) {
        // Check and ignore non touch or left clicks
        if ((event.getButtonState() != 0)
                && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) {
            return false;
        }

        // Check two finger gestures first
        boolean rotateRetVal = false;
        mRotateGestureDetector.onTouchEvent(event);
        boolean scaleRetVal = false;
        mScaleGestureDetector.onTouchEvent(event);

        // Handle two finger tap
        switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            // First pointer down
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
            // Second pointer down
            mTwoTap = event.getPointerCount() == 2;
            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 = mRotateGestureDetector.isInProgress()
                    || mScaleGestureDetector.isInProgress();

            if (mTwoTap && isTap && !inProgress) {
                PointF focalPoint = TwoFingerGestureDetector
                        .determineFocalPoint(event);
                zoom(false, focalPoint.x, focalPoint.y);
                mTwoTap = false;
                return true;
            }

            mTwoTap = false;
            break;

        case MotionEvent.ACTION_CANCEL:
            mTwoTap = false;
            break;
        }

        // Do not change this code! It will break very easily.
        // TODO fix up these warnings
        boolean retVal = rotateRetVal || scaleRetVal;
        retVal = mGestureDetector.onTouchEvent(event) || retVal;
        return retVal || super.onTouchEvent(event);
    }

    // This class handles one finger gestures
    private class GestureListener extends
            GestureDetector.SimpleOnGestureListener {

        // Must always return true otherwise all events are ignored
        @Override
        public boolean onDown(MotionEvent e) {
            // Show the zoom controls
            if ((mZoomButtonsController != null) && mZoomEnabled) {
                mZoomButtonsController.setVisible(true);
            }

            return true;
        }

        // Called for double taps
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (!mZoomEnabled) {
                return false;
            }

            // Single finger double tap
            // Zoom in
            zoom(true, e.getX(), e.getY());
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // Cancel any animation
            mNativeMapView.cancelTransitions();

            return true;
        }

        // Called for single taps after a delay
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return false;
        }

        // Called for a long press
        @Override
        public void onLongPress(MotionEvent e) {
            // TODO
        }

        // Called for flings
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            if (!mScrollEnabled) {
                return false;
            }

            // Fling the map
            // TODO Google Maps also has a rotate and zoom fling
            // TODO does not work
            /*
             * float ease = 0.25f;
             * 
             * velocityX = velocityX * ease; velocityY = velocityY * ease;
             * 
             * double speed = Math.sqrt(velocityX * velocityX + velocityY *
             * velocityY); double deceleration = 2500; double duration = speed /
             * (deceleration * ease);
             * 
             * 
             * // Cancel any animation mNativeMapView.cancelTransitions();
             * 
             * mNativeMapView.moveBy(velocityX * duration / 2.0 / mScreenDensity, velocityY *
             * duration / 2.0 / mScreenDensity, duration);
             * 
             * return true;
             */
            return false;
        }

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

            // Cancel any animation
            mNativeMapView.cancelTransitions(); // TODO need to test canceling
                                                // transitions with touch

            // Scroll the map
            mNativeMapView.moveBy(-distanceX / mScreenDensity, -distanceY / mScreenDensity);
            return true;
        }
    }

    // This class handles two finger gestures
    private class ScaleGestureListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener {

        long mBeginTime = 0;
        float mScaleFactor = 1.0f;
        boolean mStarted = false;

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

            mBeginTime = detector.getEventTime();

            return true;
        }

        // Called when fingers leave screen
        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            mBeginTime = 0;
            mScaleFactor = 1.0f;
            mStarted = false;
        }

        // Called each time one of the two fingers moves
        // Called for pinch zooms
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            if (!mZoomEnabled) {
                return false;
            }

            // If scale is large enough ignore a tap
            // TODO: Google Maps seem to use a velocity rather than absolute
            // value?
            mScaleFactor *= detector.getScaleFactor();
            if ((mScaleFactor > 1.05f) || (mScaleFactor < 0.95f)) {
                mStarted = true;
            }

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

            // TODO complex decision between roate or scale or both (see Google
            // Maps app)

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Scale the map
            mNativeMapView.scaleBy(detector.getScaleFactor(),
                    detector.getFocusX() / mScreenDensity, detector.getFocusY() / mScreenDensity);

            return true;
        }
    }

    // This class handles two rotate gestures
    // TODO need way to single finger rotate - need to research how google maps
    // does this - for phones with single touch, or when using mouse etc
    private class RotateGestureListener extends
            RotateGestureDetector.SimpleOnRotateGestureListener {

        long mBeginTime = 0;
        float mTotalAngle = 0.0f;
        boolean mStarted = false;

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

            mBeginTime = detector.getEventTime();
            Log.d("rotate", "rotate begin");
            return true;
        }

        // Called when the fingers leave the screen
        @Override
        public void onRotateEnd(RotateGestureDetector detector) {
            mBeginTime = 0;
            mTotalAngle = 0.0f;
            mStarted = false;
            Log.d("rotate", "rotate end");
        }

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

            Log.d("rotate", "rotate evt");

            // If rotate is large enough ignore a tap
            // TODO: Google Maps seem to use a velocity rather than absolute
            // value, up to a point then they always rotate
            mTotalAngle += detector.getRotationDegreesDelta();
            Log.d("rotate", "ttl angle " + mTotalAngle);
            if ((mTotalAngle > 5.0f) || (mTotalAngle < -5.0f)) {
                mStarted = true;
                Log.d("rotate", "rotate started");
            }

            // Ignore short touches in case it is a tap
            // Also ignore small rotate
            long time = detector.getEventTime();
            long interval = time - mBeginTime;
            if (!mStarted && (interval <= ViewConfiguration.getTapTimeout())) {
                Log.d("rotate", "rotate ignored");
                return false;
            }

            // TODO complex decision between rotate or scale or both (see Google
            // Maps app). It seems if you start one or the other it takes more
            // to start the other too. Haven't figured out what it uses to
            // decide when to transition to both at the same time.

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Rotate the map
            double bearing = mNativeMapView.getBearing();
            bearing += detector.getRotationDegreesDelta() * Math.PI / 180.0;
            Log.d("rotate", "rotate to " + bearing);
            mNativeMapView.setBearing(bearing, detector.getFocusX() / mScreenDensity,
                    detector.getFocusY() / mScreenDensity);

            return true;
        }
    }

    // This class handles input events from the zoom control buttons
    // Zoom controls allow single touch only devices to zoom in and out
    private class OnZoomListener implements
            ZoomButtonsController.OnZoomListener {

        // Not used
        @Override
        public void onVisibilityChanged(boolean visible) {
            // Ignore
        }

        // Called when user pushes a zoom button
        @Override
        public void onZoom(boolean zoomIn) {
            if (!mZoomEnabled) {
                return;
            }

            // Zoom in or out
            zoom(zoomIn);
        }
    }

    // Called when the user presses a key, also called for repeating keys held
    // down
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        // If the user has held the scroll key down for a while then accelerate
        // the scroll speed
        double scrollDist = event.getRepeatCount() >= 5 ? 50.0 : 10.0;

        // Check which key was pressed via hardware/real key code
        switch (keyCode) {
        // Tell the system to track these keys for long presses on
        // onKeyLongPress is fired
        case KeyEvent.KEYCODE_ENTER:
        case KeyEvent.KEYCODE_DPAD_CENTER:
            event.startTracking();
            return true;

        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Move left
            mNativeMapView.moveBy(scrollDist / mScreenDensity, 0.0 / mScreenDensity);
            return true;

        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Move right
            mNativeMapView.moveBy(-scrollDist / mScreenDensity, 0.0 / mScreenDensity);
            return true;

        case KeyEvent.KEYCODE_DPAD_UP:
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Move up
            mNativeMapView.moveBy(0.0 / mScreenDensity, scrollDist / mScreenDensity);
            return true;

        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Move down
            mNativeMapView.moveBy(0.0 / mScreenDensity, -scrollDist / mScreenDensity);
            return true;

        default:
            // We are not interested in this key
            return super.onKeyUp(keyCode, event);
        }
    }

    // Called when the user long presses a key that is being tracked
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        // Check which key was pressed via hardware/real key code
        switch (keyCode) {
        // Tell the system to track these keys for long presses on
        // onKeyLongPress is fired
        case KeyEvent.KEYCODE_ENTER:
        case KeyEvent.KEYCODE_DPAD_CENTER:
            if (!mZoomEnabled) {
                return false;
            }

            // Zoom out
            zoom(false);
            return true;

        default:
            // We are not interested in this key
            return super.onKeyUp(keyCode, event);
        }
    }

    // Called when the user releases a key
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // Check if the key action was canceled (used for virtual keyboards)
        if (event.isCanceled()) {
            return super.onKeyUp(keyCode, event);
        }

        // Check which key was pressed via hardware/real key code
        // Note if keyboard does not have physical key (ie primary non-shifted
        // key) then it will not appear here
        // Must use the key character map as physical to character is not
        // fixed/guaranteed
        switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
        case KeyEvent.KEYCODE_DPAD_CENTER:
            if (!mZoomEnabled) {
                return false;
            }

            // Zoom in
            zoom(true);
            return true;
        }

        // We are not interested in this key
        return super.onKeyUp(keyCode, event);
    }

    // Called for trackball events, all motions are relative in device specific
    // units
    // TODO: test trackball click and long click
    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        // Choose the action
        switch (event.getActionMasked()) {
        // The trackball was rotated
        case MotionEvent.ACTION_MOVE:
            if (!mScrollEnabled) {
                return false;
            }

            // Cancel any animation
            mNativeMapView.cancelTransitions();

            // Scroll the map
            mNativeMapView.moveBy(-10.0 * event.getX() / mScreenDensity, -10.0 * event.getY() / mScreenDensity);
            return true;

            // Trackball was pushed in so start tracking and tell system we are
            // interested
            // We will then get the up action
        case MotionEvent.ACTION_DOWN:
            // Set up a delayed callback to check if trackball is still
            // After waiting the system long press time out
            if (mCurrentTrackballLongPressTimeOut != null) {
                mCurrentTrackballLongPressTimeOut.cancel();
                mCurrentTrackballLongPressTimeOut = null;
            }
            mCurrentTrackballLongPressTimeOut = new TrackballLongPressTimeOut();
            postDelayed(mCurrentTrackballLongPressTimeOut,
                    ViewConfiguration.getLongPressTimeout());
            return true;

            // Trackball was released
        case MotionEvent.ACTION_UP:
            if (!mZoomEnabled) {
                return false;
            }

            // Only handle if we have not already long pressed
            if (mCurrentTrackballLongPressTimeOut != null) {
                // Zoom in
                zoom(true);
            }
            return true;

            // Trackball was cancelled
        case MotionEvent.ACTION_CANCEL:
            if (mCurrentTrackballLongPressTimeOut != null) {
                mCurrentTrackballLongPressTimeOut.cancel();
                mCurrentTrackballLongPressTimeOut = null;
            }
            return true;

        default:
            // We are not interested in this event
            return super.onTrackballEvent(event);
        }
    }

    // This class implements the trackball long press time out callback
    private class TrackballLongPressTimeOut implements Runnable {

        // Track if we have been cancelled
        private boolean cancelled;

        public TrackballLongPressTimeOut() {
            cancelled = false;
        }

        // Cancel the timeoht
        public void cancel() {
            cancelled = true;
        }

        // Called when long press time out expires
        @Override
        public void run() {
            // Check if the trackball is still pressed
            if (!cancelled) {
                // Zoom out
                zoom(false);

                // Ensure the up action is not run
                mCurrentTrackballLongPressTimeOut = null;
            }
        }
    }

    // Called for events that don't fit the other handlers
    // such as mouse scroll events, mouse moves, joystick, trackpad
    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        // Mouse events
        // TODO: SOURCE_TOUCH_NAVIGATION?
        // TODO: source device resolution?
        if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
            // Choose the action
            switch (event.getActionMasked()) {
            // Mouse scrolls
            case MotionEvent.ACTION_SCROLL:
                if (!mZoomEnabled) {
                    return false;
                }

                // Cancel any animation
                mNativeMapView.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
                mNativeMapView.scaleBy(Math.pow(2.0, scrollDist), event.getX() / mScreenDensity,
                        event.getY() / mScreenDensity);

                return true;

            default:
                // We are not interested in this event
                return super.onGenericMotionEvent(event);
            }
        }

        // We are not interested in this event
        return super.onGenericMotionEvent(event);
    }

    // Called when the mouse pointer enters or exits the view
    // or when it fades in or out due to movement
    @Override
    public boolean onHoverEvent(@NonNull MotionEvent event) {
        switch (event.getActionMasked()) {
        case MotionEvent.ACTION_HOVER_ENTER:
        case MotionEvent.ACTION_HOVER_MOVE:
            // Show the zoom controls
            if ((mZoomButtonsController != null) && mZoomEnabled) {
                mZoomButtonsController.setVisible(true);
            }
            return true;

        case MotionEvent.ACTION_HOVER_EXIT:
            // Hide the zoom controls
            if (mZoomButtonsController != null) {
                mZoomButtonsController.setVisible(false);
            }

        default:
            // We are not interested in this event
            return super.onHoverEvent(event);
        }
    }

    //
    // Action events
    //

    // This class handles connectivity changes
    public class ConnectivityReceiver extends BroadcastReceiver {

        // Called when an action we are listening to in the manifest has been sent
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v(TAG, "ConnectivityReceiver.onReceive: action = " + intent.getAction());
            if (intent.getAction() == ConnectivityManager.CONNECTIVITY_ACTION) {
                boolean noConnectivity = intent.getBooleanExtra(
                        ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                onConnectivityChanged(!noConnectivity);
            }
        }
    }


    // Called when our Internet connectivity has changed
    private void onConnectivityChanged(boolean isConnected) {
        Log.v(TAG, "onConnectivityChanged: " + isConnected);
        mNativeMapView.setReachability(isConnected);
    }

    //
    // Accessibility events
    //

    //
    // Map events
    //

    public interface OnMapChangedListener {
        void onMapChanged();
    }

    private OnMapChangedListener mOnMapChangedListener;

    // Adds a listener for onMapChanged
    public void setOnMapChangedListener(OnMapChangedListener listener) {
        mOnMapChangedListener = listener;
    }

    // Called when the map view transformation has changed
    // Called via JNI from NativeMapView
    // Need to update anything that relies on map state
    protected void onMapChanged() {
        //Log.v(TAG, "onMapChanged");
        if (mOnMapChangedListener != null) {
            mOnMapChangedListener.onMapChanged();
        }
    }
}