summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationManager.java
blob: d15d5eddf879a856379522da84f0b6807c4465f0 (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
package com.mapbox.mapboxsdk.maps;

import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import android.view.View;

import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.R;
import com.mapbox.mapboxsdk.annotations.Annotation;
import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions;
import com.mapbox.mapboxsdk.annotations.BaseMarkerViewOptions;
import com.mapbox.mapboxsdk.annotations.Icon;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerView;
import com.mapbox.mapboxsdk.annotations.MarkerViewManager;
import com.mapbox.mapboxsdk.annotations.Polygon;
import com.mapbox.mapboxsdk.annotations.PolygonOptions;
import com.mapbox.mapboxsdk.annotations.Polyline;
import com.mapbox.mapboxsdk.annotations.PolylineOptions;
import com.mapbox.services.commons.geojson.Feature;

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

import timber.log.Timber;

/**
 * Responsible for managing and tracking state of Annotations linked to Map. All events related to
 * annotations that occur on {@link MapboxMap} are forwarded to this class.
 * <p>
 * Responsible for referencing {@link InfoWindowManager} and {@link MarkerViewManager}.
 * </p>
 * <p>
 * Exposes convenience methods to add/remove/update all subtypes of annotations found in
 * com.mapbox.mapboxsdk.annotations.
 * </p>
 */
class AnnotationManager {

  private static final String LAYER_ID_SHAPE_ANNOTATIONS = "com.mapbox.annotations.shape.";
  private static final long NO_ANNOTATION_ID = -1;

  private final NativeMapView nativeMapView;
  private final MapView mapView;
  private final IconManager iconManager;
  private final InfoWindowManager infoWindowManager = new InfoWindowManager();
  private final MarkerViewManager markerViewManager;
  private final LongSparseArray<Annotation> annotations = new LongSparseArray<>();
  private final List<Marker> selectedMarkers = new ArrayList<>();
  private final List<String> shapeAnnotationIds = new ArrayList<>();

  private MapboxMap mapboxMap;
  private MapboxMap.OnMarkerClickListener onMarkerClickListener;
  private MapboxMap.OnPolygonClickListener onPolygonClickListener;
  private MapboxMap.OnPolylineClickListener onPolylineClickListener;

  AnnotationManager(NativeMapView view, MapView mapView, MarkerViewManager markerViewManager) {
    this.nativeMapView = view;
    this.mapView = mapView;
    this.iconManager = new IconManager(nativeMapView);
    this.markerViewManager = markerViewManager;
    if (view != null) {
      // null checking needed for unit tests
      view.addOnMapChangedListener(markerViewManager);
    }
  }

  // TODO refactor MapboxMap out for Projection and Transform
  // Requires removing MapboxMap from Annotations by using Peer model from #6912
  AnnotationManager bind(MapboxMap mapboxMap) {
    this.mapboxMap = mapboxMap;
    this.markerViewManager.bind(mapboxMap);
    return this;
  }

  void update() {
    markerViewManager.update();
    infoWindowManager.update();
  }

  //
  // Annotations
  //

  Annotation getAnnotation(long id) {
    return annotations.get(id);
  }

  List<Annotation> getAnnotations() {
    List<Annotation> annotations = new ArrayList<>();
    for (int i = 0; i < this.annotations.size(); i++) {
      annotations.add(this.annotations.get(this.annotations.keyAt(i)));
    }
    return annotations;
  }

  void removeAnnotation(@NonNull Annotation annotation) {
    if (annotation instanceof Marker) {
      Marker marker = (Marker) annotation;
      marker.hideInfoWindow();
      if (selectedMarkers.contains(marker)) {
        selectedMarkers.remove(marker);
      }

      if (marker instanceof MarkerView) {
        markerViewManager.removeMarkerView((MarkerView) marker);
      }
    } else {
      // instanceOf Polygon/Polyline
      shapeAnnotationIds.remove(annotation.getId());
    }
    long id = annotation.getId();
    if (nativeMapView != null) {
      nativeMapView.removeAnnotation(id);
    }
    annotations.remove(id);
  }

  void removeAnnotation(long id) {
    if (nativeMapView != null) {
      nativeMapView.removeAnnotation(id);
    }
    annotations.remove(id);
  }

  void removeAnnotations(@NonNull List<? extends Annotation> annotationList) {
    int count = annotationList.size();
    long[] ids = new long[count];
    for (int i = 0; i < count; i++) {
      Annotation annotation = annotationList.get(i);
      if (annotation instanceof Marker) {
        Marker marker = (Marker) annotation;
        marker.hideInfoWindow();
        if (selectedMarkers.contains(marker)) {
          selectedMarkers.remove(marker);
        }

        if (marker instanceof MarkerView) {
          markerViewManager.removeMarkerView((MarkerView) marker);
        }
      } else {
        // instanceOf Polygon/Polyline
        shapeAnnotationIds.remove(annotation.getId());
      }
      ids[i] = annotationList.get(i).getId();
    }

    if (nativeMapView != null) {
      nativeMapView.removeAnnotations(ids);
    }

    for (long id : ids) {
      annotations.remove(id);
    }
  }

  void removeAnnotations() {
    Annotation annotation;
    int count = annotations.size();
    long[] ids = new long[count];
    selectedMarkers.clear();
    for (int i = 0; i < count; i++) {
      ids[i] = annotations.keyAt(i);
      annotation = annotations.get(ids[i]);
      if (annotation instanceof Marker) {
        Marker marker = (Marker) annotation;
        marker.hideInfoWindow();
        if (marker instanceof MarkerView) {
          markerViewManager.removeMarkerView((MarkerView) marker);
        }
      } else {
        // instanceOf Polygon/Polyline
        shapeAnnotationIds.remove(annotation.getId());
      }
    }

    if (nativeMapView != null) {
      nativeMapView.removeAnnotations(ids);
    }

    annotations.clear();
  }

  //
  // Markers
  //

  Marker addMarker(@NonNull BaseMarkerOptions markerOptions, @NonNull MapboxMap mapboxMap) {
    Marker marker = prepareMarker(markerOptions);
    long id = nativeMapView != null ? nativeMapView.addMarker(marker) : 0;
    marker.setMapboxMap(mapboxMap);
    marker.setId(id);
    annotations.put(id, marker);
    return marker;
  }

  List<Marker> addMarkers(@NonNull List<? extends BaseMarkerOptions> markerOptionsList, @NonNull MapboxMap mapboxMap) {
    int count = markerOptionsList.size();
    List<Marker> markers = new ArrayList<>(count);
    if (count > 0) {
      BaseMarkerOptions markerOptions;
      Marker marker;
      for (int i = 0; i < count; i++) {
        markerOptions = markerOptionsList.get(i);
        marker = prepareMarker(markerOptions);
        markers.add(marker);
      }

      if (markers.size() > 0) {
        long[] ids;
        if (nativeMapView != null) {
          ids = nativeMapView.addMarkers(markers);
        } else {
          ids = new long[markers.size()];
        }

        long id;
        Marker m;
        for (int i = 0; i < ids.length; i++) {
          m = markers.get(i);
          m.setMapboxMap(mapboxMap);
          id = ids[i];
          m.setId(id);
          annotations.put(id, m);
        }

      }
    }
    return markers;
  }

  private Marker prepareMarker(BaseMarkerOptions markerOptions) {
    Marker marker = markerOptions.getMarker();
    Icon icon = iconManager.loadIconForMarker(marker);
    marker.setTopOffsetPixels(iconManager.getTopOffsetPixelsForIcon(icon));
    return marker;
  }

  MarkerView addMarker(@NonNull BaseMarkerViewOptions markerOptions, @NonNull MapboxMap mapboxMap,
                       @Nullable MarkerViewManager.OnMarkerViewAddedListener onMarkerViewAddedListener) {
    final MarkerView marker = prepareViewMarker(markerOptions);

    // add marker to map
    marker.setMapboxMap(mapboxMap);
    long id = nativeMapView.addMarker(marker);
    marker.setId(id);
    annotations.put(id, marker);

    if (onMarkerViewAddedListener != null) {
      markerViewManager.addOnMarkerViewAddedListener(marker, onMarkerViewAddedListener);
    }
    markerViewManager.setEnabled(true);
    markerViewManager.setWaitingForRenderInvoke(true);
    return marker;
  }

  List<MarkerView> addMarkerViews(@NonNull List<? extends BaseMarkerViewOptions> markerViewOptions,
                                  @NonNull MapboxMap mapboxMap) {
    List<MarkerView> markers = new ArrayList<>();
    for (BaseMarkerViewOptions markerViewOption : markerViewOptions) {
      // if last marker
      if (markerViewOptions.indexOf(markerViewOption) == markerViewOptions.size() - 1) {
        // get notified when render occurs to invalidate and draw MarkerViews
        markerViewManager.setWaitingForRenderInvoke(true);
      }
      // add marker to map
      MarkerView marker = prepareViewMarker(markerViewOption);
      marker.setMapboxMap(mapboxMap);
      long id = nativeMapView.addMarker(marker);
      marker.setId(id);
      annotations.put(id, marker);
      markers.add(marker);
    }
    markerViewManager.setEnabled(true);
    markerViewManager.update();
    return markers;
  }

  private MarkerView prepareViewMarker(BaseMarkerViewOptions markerViewOptions) {
    MarkerView marker = markerViewOptions.getMarker();
    iconManager.loadIconForMarkerView(marker);
    return marker;
  }

  void updateMarker(@NonNull Marker updatedMarker) {
    if (!isAddedToMap(updatedMarker)) {
      Timber.w("Attempting to update non-added Marker with value %s", updatedMarker);
      return;
    }
    ensureIconLoaded(updatedMarker);
    nativeMapView.updateMarker(updatedMarker);
    annotations.setValueAt(annotations.indexOfKey(updatedMarker.getId()), updatedMarker);
  }

  private boolean isAddedToMap(Annotation annotation) {
    return annotation != null && annotation.getId() != -1 && annotations.indexOfKey(annotation.getId()) > -1;
  }

  private void ensureIconLoaded(Marker marker) {
    if (!(marker instanceof MarkerView)) {
      iconManager.ensureIconLoaded(marker, mapboxMap);
    }
  }

  List<Marker> getMarkers() {
    List<Marker> markers = new ArrayList<>();
    Annotation annotation;
    for (int i = 0; i < annotations.size(); i++) {
      annotation = annotations.get(annotations.keyAt(i));
      if (annotation instanceof Marker) {
        markers.add((Marker) annotation);
      }
    }
    return markers;
  }

  void setOnMarkerClickListener(@Nullable MapboxMap.OnMarkerClickListener listener) {
    onMarkerClickListener = listener;
  }

  void setOnPolygonClickListener(@Nullable MapboxMap.OnPolygonClickListener listener) {
    onPolygonClickListener = listener;
  }

  void setOnPolylineClickListener(@Nullable MapboxMap.OnPolylineClickListener listener) {
    onPolylineClickListener = listener;
  }

  void selectMarker(@NonNull Marker marker) {
    if (selectedMarkers.contains(marker)) {
      return;
    }

    // Need to deselect any currently selected annotation first
    if (!infoWindowManager.isAllowConcurrentMultipleOpenInfoWindows()) {
      deselectMarkers();
    }

    if (marker instanceof MarkerView) {
      markerViewManager.select((MarkerView) marker, false);
      markerViewManager.ensureInfoWindowOffset((MarkerView) marker);
    }

    if (infoWindowManager.isInfoWindowValidForMarker(marker) || infoWindowManager.getInfoWindowAdapter() != null) {
      infoWindowManager.add(marker.showInfoWindow(mapboxMap, mapView));
    }

    // only add to selected markers if user didn't handle the click event themselves #3176
    selectedMarkers.add(marker);
  }

  void deselectMarkers() {
    if (selectedMarkers.isEmpty()) {
      return;
    }

    for (Marker marker : selectedMarkers) {
      if (marker.isInfoWindowShown()) {
        marker.hideInfoWindow();
      }

      if (marker instanceof MarkerView) {
        markerViewManager.deselect((MarkerView) marker, false);
      }
    }

    // Removes all selected markers from the list
    selectedMarkers.clear();
  }

  void deselectMarker(@NonNull Marker marker) {
    if (!selectedMarkers.contains(marker)) {
      return;
    }

    if (marker.isInfoWindowShown()) {
      marker.hideInfoWindow();
    }

    if (marker instanceof MarkerView) {
      markerViewManager.deselect((MarkerView) marker, false);
    }

    selectedMarkers.remove(marker);
  }

  List<Marker> getSelectedMarkers() {
    return selectedMarkers;
  }

  @NonNull
  List<Marker> getMarkersInRect(@NonNull RectF rectangle) {
    // convert Rectangle to be density dependent
    float pixelRatio = nativeMapView.getPixelRatio();
    RectF rect = new RectF(rectangle.left / pixelRatio,
      rectangle.top / pixelRatio,
      rectangle.right / pixelRatio,
      rectangle.bottom / pixelRatio);

    long[] ids = nativeMapView.queryPointAnnotations(rect);

    List<Long> idsList = new ArrayList<>(ids.length);
    for (long id : ids) {
      idsList.add(id);
    }

    List<Marker> annotations = new ArrayList<>(ids.length);
    List<Annotation> annotationList = getAnnotations();
    int count = annotationList.size();
    for (int i = 0; i < count; i++) {
      Annotation annotation = annotationList.get(i);
      if (annotation instanceof com.mapbox.mapboxsdk.annotations.Marker && idsList.contains(annotation.getId())) {
        annotations.add((com.mapbox.mapboxsdk.annotations.Marker) annotation);
      }
    }

    return new ArrayList<>(annotations);
  }

  List<MarkerView> getMarkerViewsInRect(@NonNull RectF rectangle) {
    float pixelRatio = nativeMapView.getPixelRatio();
    RectF rect = new RectF(rectangle.left / pixelRatio,
      rectangle.top / pixelRatio,
      rectangle.right / pixelRatio,
      rectangle.bottom / pixelRatio);

    long[] ids = nativeMapView.queryPointAnnotations(rect);

    List<Long> idsList = new ArrayList<>(ids.length);
    for (long id : ids) {
      idsList.add(id);
    }

    List<MarkerView> annotations = new ArrayList<>(ids.length);
    List<Annotation> annotationList = getAnnotations();
    int count = annotationList.size();
    for (int i = 0; i < count; i++) {
      Annotation annotation = annotationList.get(i);
      if (annotation instanceof MarkerView && idsList.contains(annotation.getId())) {
        annotations.add((MarkerView) annotation);
      }
    }

    return new ArrayList<>(annotations);
  }

  //
  // Polygons
  //

  Polygon addPolygon(@NonNull PolygonOptions polygonOptions, @NonNull MapboxMap mapboxMap) {
    Polygon polygon = polygonOptions.getPolygon();
    if (!polygon.getPoints().isEmpty()) {
      long id = nativeMapView != null ? nativeMapView.addPolygon(polygon) : 0;
      polygon.setId(id);
      polygon.setMapboxMap(mapboxMap);
      shapeAnnotationIds.add(LAYER_ID_SHAPE_ANNOTATIONS + id);
      annotations.put(id, polygon);
    }
    return polygon;
  }

  List<Polygon> addPolygons(@NonNull List<PolygonOptions> polygonOptionsList, @NonNull MapboxMap mapboxMap) {
    int count = polygonOptionsList.size();

    Polygon polygon;
    List<Polygon> polygons = new ArrayList<>(count);
    if (count > 0) {
      for (PolygonOptions polygonOptions : polygonOptionsList) {
        polygon = polygonOptions.getPolygon();
        if (!polygon.getPoints().isEmpty()) {
          polygons.add(polygon);
        }
      }

      long[] ids;
      if (nativeMapView != null) {
        ids = nativeMapView.addPolygons(polygons);
      } else {
        ids = new long[polygons.size()];
      }

      long id;
      for (int i = 0; i < ids.length; i++) {
        polygon = polygons.get(i);
        polygon.setMapboxMap(mapboxMap);
        id = ids[i];
        polygon.setId(id);
        shapeAnnotationIds.add(LAYER_ID_SHAPE_ANNOTATIONS + id);
        annotations.put(id, polygon);
      }
    }
    return polygons;
  }

  void updatePolygon(@NonNull Polygon polygon) {
    if (!isAddedToMap(polygon)) {
      Timber.w("Attempting to update non-added Polygon with value %s", polygon);
      return;
    }

    nativeMapView.updatePolygon(polygon);
    annotations.setValueAt(annotations.indexOfKey(polygon.getId()), polygon);
  }

  List<Polygon> getPolygons() {
    List<Polygon> polygons = new ArrayList<>();
    Annotation annotation;
    for (int i = 0; i < annotations.size(); i++) {
      annotation = annotations.get(annotations.keyAt(i));
      if (annotation instanceof Polygon) {
        polygons.add((Polygon) annotation);
      }
    }
    return polygons;
  }

  //
  // Polylines
  //

  Polyline addPolyline(@NonNull PolylineOptions polylineOptions, @NonNull MapboxMap mapboxMap) {
    Polyline polyline = polylineOptions.getPolyline();
    if (!polyline.getPoints().isEmpty()) {
      long id = nativeMapView != null ? nativeMapView.addPolyline(polyline) : 0;
      polyline.setMapboxMap(mapboxMap);
      polyline.setId(id);
      shapeAnnotationIds.add(LAYER_ID_SHAPE_ANNOTATIONS + id);
      annotations.put(id, polyline);
    }
    return polyline;
  }

  List<Polyline> addPolylines(@NonNull List<PolylineOptions> polylineOptionsList, @NonNull MapboxMap mapboxMap) {
    int count = polylineOptionsList.size();
    Polyline polyline;
    List<Polyline> polylines = new ArrayList<>(count);

    if (count > 0) {
      for (PolylineOptions options : polylineOptionsList) {
        polyline = options.getPolyline();
        if (!polyline.getPoints().isEmpty()) {
          polylines.add(polyline);
        }
      }

      long[] ids;
      if (nativeMapView != null) {
        ids = nativeMapView.addPolylines(polylines);
      } else {
        ids = new long[polylines.size()];
      }

      long id;
      Polyline p;
      for (int i = 0; i < ids.length; i++) {
        p = polylines.get(i);
        p.setMapboxMap(mapboxMap);
        id = ids[i];
        p.setId(id);
        shapeAnnotationIds.add(LAYER_ID_SHAPE_ANNOTATIONS + id);
        annotations.put(id, p);
      }
    }
    return polylines;
  }

  void updatePolyline(@NonNull Polyline polyline) {
    if (!isAddedToMap(polyline)) {
      Timber.w("Attempting to update non-added Polyline with value %s", polyline);
      return;
    }

    nativeMapView.updatePolyline(polyline);
    annotations.setValueAt(annotations.indexOfKey(polyline.getId()), polyline);
  }

  List<Polyline> getPolylines() {
    List<Polyline> polylines = new ArrayList<>();
    Annotation annotation;
    for (int i = 0; i < annotations.size(); i++) {
      annotation = annotations.get(annotations.keyAt(i));
      if (annotation instanceof Polyline) {
        polylines.add((Polyline) annotation);
      }
    }
    return polylines;
  }

  InfoWindowManager getInfoWindowManager() {
    return infoWindowManager;
  }

  MarkerViewManager getMarkerViewManager() {
    return markerViewManager;
  }

  void adjustTopOffsetPixels(MapboxMap mapboxMap) {
    int count = annotations.size();
    for (int i = 0; i < count; i++) {
      Annotation annotation = annotations.get(i);
      if (annotation instanceof Marker) {
        Marker marker = (Marker) annotation;
        marker.setTopOffsetPixels(
          iconManager.getTopOffsetPixelsForIcon(marker.getIcon()));
      }
    }

    for (Marker marker : selectedMarkers) {
      if (marker.isInfoWindowShown()) {
        marker.hideInfoWindow();
        marker.showInfoWindow(mapboxMap, mapView);
      }
    }
  }

  void reloadMarkers() {
    iconManager.reloadIcons();
    int count = annotations.size();
    for (int i = 0; i < count; i++) {
      Annotation annotation = annotations.get(i);
      if (annotation instanceof Marker) {
        Marker marker = (Marker) annotation;
        nativeMapView.removeAnnotation(annotation.getId());
        long newId = nativeMapView.addMarker(marker);
        marker.setId(newId);
      }
    }
  }

  //
  // Click event
  //

  boolean onTap(PointF tapPoint) {
    if (!shapeAnnotationIds.isEmpty()) {
      ShapeAnnotationHit shapeAnnotationHit = getShapeAnnotationHitFromTap(tapPoint);
      long shapeAnnotationId = new ShapeAnnotationHitResolver(mapboxMap).execute(shapeAnnotationHit);
      if (shapeAnnotationId != NO_ANNOTATION_ID) {
        handleClickForShapeAnnotation(shapeAnnotationId);
      }
    }

    MarkerHit markerHit = getMarkerHitFromTouchArea(tapPoint);
    long markerId = new MarkerHitResolver(mapboxMap).execute(markerHit);
    return markerId != NO_ANNOTATION_ID && isClickHandledForMarker(markerId);
  }

  private ShapeAnnotationHit getShapeAnnotationHitFromTap(PointF tapPoint) {
    float touchTargetSide = Mapbox.getApplicationContext().getResources().getDimension(R.dimen.mapbox_eight_dp);
    RectF tapRect = new RectF(
      tapPoint.x - touchTargetSide,
      tapPoint.y - touchTargetSide,
      tapPoint.x + touchTargetSide,
      tapPoint.y + touchTargetSide
    );
    return new ShapeAnnotationHit(tapRect, shapeAnnotationIds.toArray(new String[shapeAnnotationIds.size()]));
  }

  private void handleClickForShapeAnnotation(long shapeAnnotationId) {
    Annotation annotation = getAnnotation(shapeAnnotationId);
    if (annotation instanceof Polygon && onPolygonClickListener != null) {
      onPolygonClickListener.onPolygonClick((Polygon) annotation);
    } else if (annotation instanceof Polyline && onPolylineClickListener != null) {
      onPolylineClickListener.onPolylineClick((Polyline) annotation);
    }
  }

  private MarkerHit getMarkerHitFromTouchArea(PointF tapPoint) {
    int touchSurfaceWidth = (int) (iconManager.getHighestIconHeight() * 1.5);
    int touchSurfaceHeight = (int) (iconManager.getHighestIconWidth() * 1.5);
    final RectF tapRect = new RectF(tapPoint.x - touchSurfaceWidth,
      tapPoint.y - touchSurfaceHeight,
      tapPoint.x + touchSurfaceWidth,
      tapPoint.y + touchSurfaceHeight
    );
    return new MarkerHit(tapRect, getMarkersInRect(tapRect));
  }

  private boolean isClickHandledForMarker(long markerId) {
    boolean handledDefaultClick;
    Marker marker = (Marker) getAnnotation(markerId);
    if (marker instanceof MarkerView) {
      handledDefaultClick = markerViewManager.onClickMarkerView((MarkerView) marker);
    } else {
      handledDefaultClick = onClickMarker(marker);
    }

    if (!handledDefaultClick) {
      toggleMarkerSelectionState(marker);
    }
    return true;
  }

  private boolean onClickMarker(Marker marker) {
    return onMarkerClickListener != null && onMarkerClickListener.onMarkerClick(marker);
  }

  private void toggleMarkerSelectionState(Marker marker) {
    if (!selectedMarkers.contains(marker)) {
      selectMarker(marker);
    } else {
      deselectMarker(marker);
    }
  }

  private static class ShapeAnnotationHitResolver {

    private MapboxMap mapboxMap;

    ShapeAnnotationHitResolver(MapboxMap mapboxMap) {
      this.mapboxMap = mapboxMap;
    }

    public long execute(ShapeAnnotationHit shapeHit) {
      long foundAnnotationId = NO_ANNOTATION_ID;
      List<Feature> features = mapboxMap.queryRenderedFeatures(shapeHit.tapPoint, shapeHit.layerIds);
      if (!features.isEmpty()) {
        foundAnnotationId = getIdFromFeature(features.get(0));
      }
      return foundAnnotationId;
    }

    private long getIdFromFeature(Feature feature) {
      try {
        return Long.valueOf(feature.getId());
      } catch (NumberFormatException exception) {
        Timber.e(exception, "Couldn't parse feature id to a long, with id: %s", feature.getId());
        return NO_ANNOTATION_ID;
      }
    }
  }

  private static class MarkerHitResolver {

    private final MarkerViewManager markerViewManager;
    private final Projection projection;

    private View view;
    private Bitmap bitmap;
    private PointF markerLocation;

    private Rect hitRectView = new Rect();
    private RectF hitRectMarker = new RectF();
    private RectF highestSurfaceIntersection = new RectF();

    private long closestMarkerId = NO_ANNOTATION_ID;

    MarkerHitResolver(@NonNull MapboxMap mapboxMap) {
      this.markerViewManager = mapboxMap.getMarkerViewManager();
      this.projection = mapboxMap.getProjection();
    }

    public long execute(MarkerHit markerHit) {
      resolveForMarkers(markerHit);
      return closestMarkerId;
    }

    private void resolveForMarkers(MarkerHit markerHit) {
      for (Marker marker : markerHit.markers) {
        if (marker instanceof MarkerView) {
          resolveForMarkerView(markerHit, (MarkerView) marker);
        } else {
          resolveForMarker(markerHit, marker);
        }
      }
    }

    private void resolveForMarkerView(MarkerHit markerHit, MarkerView markerView) {
      view = markerViewManager.getView(markerView);
      if (view != null) {
        view.getHitRect(hitRectView);
        hitRectMarker = new RectF(hitRectView);
        hitTestMarker(markerHit, markerView, hitRectMarker);
      }
    }

    private void resolveForMarker(MarkerHit markerHit, Marker marker) {
      markerLocation = projection.toScreenLocation(marker.getPosition());
      bitmap = marker.getIcon().getBitmap();
      hitRectMarker.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
      hitRectMarker.offsetTo(
        markerLocation.x - bitmap.getWidth() / 2,
        markerLocation.y - bitmap.getHeight() / 2
      );
      hitTestMarker(markerHit, marker, hitRectMarker);
    }

    private void hitTestMarker(MarkerHit markerHit, Marker marker, RectF hitRectMarker) {
      if (hitRectMarker.contains(markerHit.getTapPointX(), markerHit.getTapPointY())) {
        hitRectMarker.intersect(markerHit.tapRect);
        if (isRectangleHighestSurfaceIntersection(hitRectMarker)) {
          highestSurfaceIntersection = new RectF(hitRectMarker);
          closestMarkerId = marker.getId();
        }
      }
    }

    private boolean isRectangleHighestSurfaceIntersection(RectF rectF) {
      return rectF.width() * rectF.height() > highestSurfaceIntersection.width() * highestSurfaceIntersection.height();
    }
  }

  private static class ShapeAnnotationHit {
    private final RectF tapPoint;
    private final String[] layerIds;

    ShapeAnnotationHit(RectF tapRect, String[] layerIds) {
      this.tapPoint = tapRect;
      this.layerIds = layerIds;
    }
  }

  private static class MarkerHit {
    private final RectF tapRect;
    private final List<Marker> markers;

    MarkerHit(RectF tapRect, List<Marker> markers) {
      this.tapRect = tapRect;
      this.markers = markers;
    }

    float getTapPointX() {
      return tapRect.centerX();
    }

    float getTapPointY() {
      return tapRect.centerY();
    }
  }
}