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

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.annotation.VisibleForTesting;
import android.util.DisplayMetrics;
import android.util.Pair;

import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.TransitionOptions;
import com.mapbox.mapboxsdk.style.light.Light;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.utils.BitmapUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The proxy object for current map style.
 * <p>
 * To create new instances of this object, create a new instance using a {@link Builder} and load the style with
 * {@link MapboxMap#setStyle(Builder)}. This object is returned from {@link MapboxMap#getStyle()} once the style
 * has been loaded by underlying map.
 * </p>
 */
@SuppressWarnings("unchecked")
public class Style {

  private final NativeMap nativeMap;
  private final HashMap<String, Source> sources = new HashMap<>();
  private final HashMap<String, Layer> layers = new HashMap<>();
  private final HashMap<String, Bitmap> images = new HashMap<>();
  private final Builder builder;
  private boolean fullyLoaded;

  /**
   * Private constructor to build a style object.
   *
   * @param builder   the builder used for creating this style
   * @param nativeMap the map object used to load this style
   */
  @VisibleForTesting
  Style(@NonNull Builder builder, @NonNull NativeMap nativeMap) {
    this.builder = builder;
    this.nativeMap = nativeMap;
  }

  /**
   * Returns the current style url.
   *
   * @return the style url
   */
  @NonNull
  public String getUrl() {
    validateState("getUrl");
    return nativeMap.getStyleUrl();
  }

  /**
   * Returns the current style json.
   *
   * @return the style json
   */
  @NonNull
  public String getJson() {
    validateState("getJson");
    return nativeMap.getStyleJson();
  }

  //
  // Source
  //

  /**
   * Retrieve all the sources in the style
   *
   * @return all the sources in the current style
   */
  @NonNull
  public List<Source> getSources() {
    validateState("getSources");
    return nativeMap.getSources();
  }

  /**
   * Adds the source to the map. The source must be newly created and not added to the map before
   *
   * @param source the source to add
   */
  public void addSource(@NonNull Source source) {
    validateState("addSource");
    sources.put(source.getId(), source);
    nativeMap.addSource(source);
  }

  /**
   * Retrieve a source by id
   *
   * @param id the source's id
   * @return the source if present in the current style
   */
  @Nullable
  public Source getSource(String id) {
    validateState("getSource");
    Source source = sources.get(id);
    if (source == null) {
      source = nativeMap.getSource(id);
    }
    return source;
  }

  /**
   * Tries to cast the Source to T, throws ClassCastException if it's another type.
   *
   * @param sourceId the id used to look up a layer
   * @param <T>      the generic type of a Source
   * @return the casted Source, null if another type
   */
  @Nullable
  public <T extends Source> T getSourceAs(@NonNull String sourceId) {
    validateState("getSourceAs");
    // noinspection unchecked
    if (sources.containsKey(sourceId)) {
      return (T) sources.get(sourceId);
    }
    return (T) nativeMap.getSource(sourceId);
  }

  /**
   * Removes the source from the style.
   *
   * @param sourceId the source to remove
   * @return the source handle or null if the source was not present
   */
  public boolean removeSource(@NonNull String sourceId) {
    validateState("removeSource");
    sources.remove(sourceId);
    return nativeMap.removeSource(sourceId);
  }

  /**
   * Removes the source, preserving the reference for re-use
   *
   * @param source the source to remove
   * @return the source
   */
  public boolean removeSource(@NonNull Source source) {
    validateState("removeSource");
    sources.remove(source.getId());
    return nativeMap.removeSource(source);
  }

  //
  // Layer
  //

  /**
   * Adds the layer to the map. The layer must be newly created and not added to the map before
   *
   * @param layer the layer to add
   */
  public void addLayer(@NonNull Layer layer) {
    validateState("addLayer");
    layers.put(layer.getId(), layer);
    nativeMap.addLayer(layer);
  }

  /**
   * Adds the layer to the map. The layer must be newly created and not added to the map before
   *
   * @param layer the layer to add
   * @param below the layer id to add this layer before
   */
  public void addLayerBelow(@NonNull Layer layer, @NonNull String below) {
    validateState("addLayerBelow");
    layers.put(layer.getId(), layer);
    nativeMap.addLayerBelow(layer, below);
  }

  /**
   * Adds the layer to the map. The layer must be newly created and not added to the map before
   *
   * @param layer the layer to add
   * @param above the layer id to add this layer above
   */
  public void addLayerAbove(@NonNull Layer layer, @NonNull String above) {
    validateState("addLayerAbove");
    layers.put(layer.getId(), layer);
    nativeMap.addLayerAbove(layer, above);
  }

  /**
   * Adds the layer to the map at the specified index. The layer must be newly
   * created and not added to the map before
   *
   * @param layer the layer to add
   * @param index the index to insert the layer at
   */
  public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) {
    validateState("addLayerAbove");
    layers.put(layer.getId(), layer);
    nativeMap.addLayerAt(layer, index);
  }

  /**
   * Get the layer by id
   *
   * @param id the layer's id
   * @return the layer, if present in the style
   */
  @Nullable
  public Layer getLayer(@NonNull String id) {
    validateState("getLayer");
    Layer layer = layers.get(id);
    if (layer == null) {
      layer = nativeMap.getLayer(id);
    }
    return layer;
  }

  /**
   * Tries to cast the Layer to T, throws ClassCastException if it's another type.
   *
   * @param layerId the layer id used to look up a layer
   * @param <T>     the generic attribute of a Layer
   * @return the casted Layer, null if another type
   */
  @Nullable
  public <T extends Layer> T getLayerAs(@NonNull String layerId) {
    validateState("getLayerAs");
    // noinspection unchecked
    return (T) nativeMap.getLayer(layerId);
  }

  /**
   * Retrieve all the layers in the style
   *
   * @return all the layers in the current style
   */
  @NonNull
  public List<Layer> getLayers() {
    validateState("getLayers");
    return nativeMap.getLayers();
  }

  /**
   * Removes the layer. Any references to the layer become invalid and should not be used anymore
   *
   * @param layerId the layer to remove
   * @return the removed layer or null if not found
   */
  public boolean removeLayer(@NonNull String layerId) {
    validateState("removeLayer");
    layers.remove(layerId);
    return nativeMap.removeLayer(layerId);
  }

  /**
   * Removes the layer. The reference is re-usable after this and can be re-added
   *
   * @param layer the layer to remove
   * @return the layer
   */
  public boolean removeLayer(@NonNull Layer layer) {
    validateState("removeLayer");
    layers.remove(layer.getId());
    return nativeMap.removeLayer(layer);
  }

  /**
   * Removes the layer. Any other references to the layer become invalid and should not be used anymore
   *
   * @param index the layer index
   * @return the removed layer or null if not found
   */
  public boolean removeLayerAt(@IntRange(from = 0) int index) {
    validateState("removeLayerAt");
    return nativeMap.removeLayerAt(index);
  }

  //
  // Image
  //

  /**
   * Adds an image to be used in the map's style
   *
   * @param name  the name of the image
   * @param image the pre-multiplied Bitmap
   */
  public void addImage(@NonNull String name, @NonNull Bitmap image) {
    addImage(name, image, false);
  }

  /**
   * Adds an drawable to be converted into a bitmap to be used in the map's style
   *
   * @param name     the name of the image
   * @param drawable the drawable instance to convert
   */
  public void addImage(@NonNull String name, @NonNull Drawable drawable) {
    Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
    if (bitmap == null) {
      throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
    }
    addImage(name, bitmap, false);
  }

  /**
   * Adds an image to be used in the map's style
   *
   * @param name   the name of the image
   * @param bitmap the pre-multiplied Bitmap
   * @param sdf    the flag indicating image is an SDF or template image
   */
  public void addImage(@NonNull final String name, @NonNull final Bitmap bitmap, boolean sdf) {
    validateState("addImage");
    new BitmapImageConversionTask(nativeMap, sdf).execute(new Builder.ImageWrapper(name, bitmap, sdf));
  }

  /**
   * Adds an images to be used in the map's style.
   *
   * @param images the map of images to add
   */
  public void addImages(@NonNull HashMap<String, Bitmap> images) {
    addImages(images, false);
  }

  /**
   * Adds an images to be used in the map's style.
   *
   * @param images the map of images to add
   * @param sdf    the flag indicating image is an SDF or template image
   */
  public void addImages(@NonNull HashMap<String, Bitmap> images, boolean sdf) {
    validateState("addImages");
    new BitmapImageConversionTask(nativeMap, sdf).execute(Builder.ImageWrapper.convertToImageArray(images, sdf));
  }

  /**
   * Removes an image from the map's style.
   *
   * @param name the name of the image to remove
   */
  public void removeImage(@NonNull String name) {
    validateState("removeImage");
    nativeMap.removeImage(name);
  }

  /**
   * Get an image from the map's style using an id.
   *
   * @param id the id of the image
   * @return the image bitmap
   */
  @Nullable
  public Bitmap getImage(@NonNull String id) {
    validateState("getImage");
    return nativeMap.getImage(id);
  }

  //
  // Transition
  //

  /**
   * <p>
   * Set the transition options for style changes.
   * </p>
   * If not set, any changes take effect without animation, besides symbols,
   * which will fade in/out with a default duration after symbol collision detection.
   * <p>
   * To disable symbols fade in/out animation,
   * pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false.
   * <p>
   * Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
   * will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
   *
   * @param transitionOptions the transition options
   */
  public void setTransition(@NonNull TransitionOptions transitionOptions) {
    validateState("setTransition");
    nativeMap.setTransitionOptions(transitionOptions);
  }

  /**
   * <p>
   * Get the transition options for style changes.
   * </p>
   * By default, any changes take effect without animation, besides symbols,
   * which will fade in/out with a default duration after symbol collision detection.
   * <p>
   * To disable symbols fade in/out animation,
   * pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false
   * into {@link #setTransition(TransitionOptions)}.
   * <p>
   * Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
   * will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
   *
   * @return TransitionOptions the transition options
   */
  @NonNull
  public TransitionOptions getTransition() {
    validateState("getTransition");
    return nativeMap.getTransitionOptions();
  }

  //
  // Light
  //

  /**
   * Get the light source used to change lighting conditions on extruded fill layers.
   *
   * @return the global light source
   */
  @Nullable
  public Light getLight() {
    validateState("getLight");
    return nativeMap.getLight();
  }

  //
  // State
  //

  /**
   * Called when the underlying map will start loading a new style. This method will clean up this style
   * by setting the java sources and layers in a detached state and removing them from core.
   */
  void onWillStartLoadingMap() {
    fullyLoaded = false;

    for (Source source : nativeMap.getSources()) {
      source.nativeSetDetached();
    }

    for (Layer layer : nativeMap.getLayers()) {
      layer.nativeSetDetached();
    }

    for (Map.Entry<String, Bitmap> bitmapEntry : images.entrySet()) {
      nativeMap.removeImage(bitmapEntry.getKey());
      bitmapEntry.getValue().recycle();
    }

    sources.clear();
    layers.clear();
    images.clear();
  }

  /**
   * Called when the underlying map has finished loading this style.
   * This method will add all components added to the builder that were defined with the 'with' prefix.
   */
  void onDidFinishLoadingStyle() {
    if (!fullyLoaded) {
      fullyLoaded = true;
      for (Source source : builder.sources) {
        addSource(source);
      }

      for (Builder.LayerWrapper layerWrapper : builder.layers) {
        if (layerWrapper instanceof Builder.LayerAtWrapper) {
          addLayerAt(layerWrapper.layer, ((Builder.LayerAtWrapper) layerWrapper).index);
        } else if (layerWrapper instanceof Builder.LayerAboveWrapper) {
          addLayerAbove(layerWrapper.layer, ((Builder.LayerAboveWrapper) layerWrapper).aboveLayer);
        } else if (layerWrapper instanceof Builder.LayerBelowWrapper) {
          addLayerBelow(layerWrapper.layer, ((Builder.LayerBelowWrapper) layerWrapper).belowLayer);
        } else {
          // just add layer to map, but below annotations
          addLayerBelow(layerWrapper.layer, MapboxConstants.LAYER_ID_ANNOTATIONS);
        }
      }

      for (Builder.ImageWrapper image : builder.images) {
        addImage(image.id, image.bitmap, image.sdf);
      }

      if (builder.transitionOptions != null) {
        setTransition(builder.transitionOptions);
      }
    }
  }

  /**
   * Returns true if the style is fully loaded. Returns false if style hasn't been fully loaded or a new style is
   * underway of being loaded.
   *
   * @return True if fully loaded, false otherwise
   */
  public boolean isFullyLoaded() {
    return fullyLoaded;
  }

  /**
   * Validates the style state, throw an IllegalArgumentException on invalid state.
   *
   * @param methodCall the calling method name
   */
  private void validateState(String methodCall) {
    if (!fullyLoaded) {
      throw new IllegalStateException(
        String.format("Calling %s when a newer style is loading/has loaded.", methodCall)
      );
    }
  }

  //
  // Builder
  //

  /**
   * Builder for composing a style object.
   */
  public static class Builder {

    private final List<Source> sources = new ArrayList<>();
    private final List<LayerWrapper> layers = new ArrayList<>();
    private final List<ImageWrapper> images = new ArrayList<>();

    private TransitionOptions transitionOptions;
    private String styleUrl;
    private String styleJson;

    /**
     * <p>
     * Will loads a new map style asynchronous from the specified URL.
     * </p>
     * {@code url} can take the following forms:
     * <ul>
     * <li>{@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.</li>
     * <li>{@code mapbox://styles/<user>/<style>}:
     * loads the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
     * {@code user} is your username. {@code style} is the ID of your custom
     * style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
     * <li>{@code http://...} or {@code https://...}:
     * loads the style over the Internet from any web server.</li>
     * <li>{@code asset://...}:
     * loads the style from the APK {@code assets/} directory.
     * This is used to load a style bundled with your app.</li>
     * <li>{@code file://...}:
     * loads the style from a file path. This is used to load a style from disk.
     * </li>
     * </li>
     * <li>{@code null}: loads the default {@link Style#MAPBOX_STREETS} style.</li>
     * </ul>
     * <p>
     * This method is asynchronous and will return before the style finishes loading.
     * If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener}
     * callback or use {@link MapboxMap#setStyle(String, OnStyleLoaded)} instead.
     * </p>
     * If the style fails to load or an invalid style URL is set, the map view will become blank.
     * An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
     * will be triggered.
     *
     * @param url The URL of the map style
     * @return this
     * @see Style
     */
    @NonNull
    public Builder fromUrl(@NonNull String url) {
      this.styleUrl = url;
      return this;
    }

    /**
     * Will load a new map style from a json string.
     * <p>
     * If the style fails to load or an invalid style URL is set, the map view will become blank.
     * An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
     * will be triggered.
     * </p>
     *
     * @return this
     */
    @NonNull
    public Builder fromJson(@NonNull String styleJson) {
      this.styleJson = styleJson;
      return this;
    }

    /**
     * Will add the source when map style has loaded.
     *
     * @param source the source to add
     * @return this
     */
    @NonNull
    public Builder withSource(@NonNull Source source) {
      sources.add(source);
      return this;
    }

    /**
     * Will add the sources when map style has loaded.
     *
     * @param sources the sources to add
     * @return this
     */
    @NonNull
    public Builder withSources(@NonNull Source... sources) {
      this.sources.addAll(Arrays.asList(sources));
      return this;
    }

    /**
     * Will add the layer when the style has loaded.
     *
     * @param layer the layer to be added
     * @return this
     */
    @NonNull
    public Builder withLayer(@NonNull Layer layer) {
      layers.add(new LayerWrapper(layer));
      return this;
    }

    /**
     * Will add the layers when the style has loaded.
     *
     * @param layers the layers to be added
     * @return this
     */
    @NonNull
    public Builder withLayers(@NonNull Layer... layers) {
      for (Layer layer : layers) {
        this.layers.add(new LayerWrapper(layer));
      }
      return this;
    }

    /**
     * Will add the layer when the style has loaded at a specified index.
     *
     * @param layer the layer to be added
     * @return this
     */
    @NonNull
    public Builder withLayerAt(@NonNull Layer layer, int index) {
      layers.add(new LayerAtWrapper(layer, index));
      return this;
    }

    /**
     * Will add the layer when the style has loaded above a specified layer id.
     *
     * @param layer the layer to be added
     * @return this
     */
    @NonNull
    public Builder withLayerAbove(@NonNull Layer layer, @NonNull String aboveLayerId) {
      layers.add(new LayerAboveWrapper(layer, aboveLayerId));
      return this;
    }

    /**
     * Will add the layer when the style has loaded below a specified layer id.
     *
     * @param layer the layer to be added
     * @return this
     */
    @NonNull
    public Builder withLayerBelow(@NonNull Layer layer, @NonNull String belowLayerId) {
      layers.add(new LayerBelowWrapper(layer, belowLayerId));
      return this;
    }

    /**
     * Will add the transition when the map style has loaded.
     *
     * @param transition the transition to be added
     * @return this
     */
    @NonNull
    public Builder withTransition(@NonNull TransitionOptions transition) {
      this.transitionOptions = transition;
      return this;
    }

    /**
     * Will add the drawable as image when the map style has loaded.
     *
     * @param id       the id for the image
     * @param drawable the drawable to be converted and added
     * @return this
     */
    @NonNull
    public Builder withImage(@NonNull String id, @NonNull Drawable drawable) {
      Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
      if (bitmap == null) {
        throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
      }
      return this.withImage(id, bitmap, false);
    }

    /**
     * Will add the drawables as images when the map style has loaded.
     *
     * @param values pairs, where first is the id for te image and second is the drawable
     * @return this
     */
    @NonNull
    public Builder withDrawableImages(@NonNull Pair<String, Drawable>... values) {
      return this.withDrawableImages(false, values);
    }

    /**
     * Will add the image when the map style has loaded.
     *
     * @param id    the id for the image
     * @param image the image to be added
     * @return this
     */
    @NonNull
    public Builder withImage(@NonNull String id, @NonNull Bitmap image) {
      return this.withImage(id, image, false);
    }

    /**
     * Will add the images when the map style has loaded.
     *
     * @param values pairs, where first is the id for te image and second is the bitmap
     * @return this
     */
    @NonNull
    public Builder withBitmapImages(@NonNull Pair<String, Bitmap>... values) {
      for (Pair<String, Bitmap> value : values) {
        this.withImage(value.first, value.second, false);
      }
      return this;
    }

    /**
     * Will add the drawable as image when the map style has loaded.
     *
     * @param id       the id for the image
     * @param drawable the drawable to be converted and added
     * @param sdf      the flag indicating image is an SDF or template image
     * @return this
     */
    @NonNull
    public Builder withImage(@NonNull String id, @NonNull Drawable drawable, boolean sdf) {
      Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
      if (bitmap == null) {
        throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
      }
      return this.withImage(id, bitmap, sdf);
    }

    /**
     * Will add the drawables as images when the map style has loaded.
     *
     * @param sdf    the flag indicating image is an SDF or template image
     * @param values pairs, where first is the id for te image and second is the drawable
     * @return this
     */
    @NonNull
    public Builder withDrawableImages(boolean sdf, @NonNull Pair<String, Drawable>... values) {
      for (Pair<String, Drawable> value : values) {
        Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(value.second);
        if (bitmap == null) {
          throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
        }
        this.withImage(value.first, bitmap, sdf);
      }
      return this;
    }

    /**
     * Will add the image when the map style has loaded.
     *
     * @param id    the id for the image
     * @param image the image to be added
     * @param sdf   the flag indicating image is an SDF or template image
     * @return this
     */
    @NonNull
    public Builder withImage(@NonNull String id, @NonNull Bitmap image, boolean sdf) {
      images.add(new ImageWrapper(id, image, sdf));
      return this;
    }

    /**
     * Will add the images when the map style has loaded.
     *
     * @param sdf    the flag indicating image is an SDF or template image
     * @param values pairs, where first is the id for te image and second is the bitmap
     * @return this
     */
    @NonNull
    public Builder withBitmapImages(boolean sdf, @NonNull Pair<String, Bitmap>... values) {
      for (Pair<String, Bitmap> value : values) {
        this.withImage(value.first, value.second, sdf);
      }
      return this;
    }

    String getUrl() {
      return styleUrl;
    }

    String getJson() {
      return styleJson;
    }

    List<Source> getSources() {
      return sources;
    }

    List<LayerWrapper> getLayers() {
      return layers;
    }

    List<ImageWrapper> getImages() {
      return images;
    }

    TransitionOptions getTransitionOptions() {
      return transitionOptions;
    }

    /**
     * Build the composed style.
     */
    Style build(@NonNull NativeMap nativeMap) {
      return new Style(this, nativeMap);
    }

    static class ImageWrapper {
      Bitmap bitmap;
      String id;
      boolean sdf;

      ImageWrapper(String id, Bitmap bitmap, boolean sdf) {
        this.id = id;
        this.bitmap = bitmap;
        this.sdf = sdf;
      }

      static ImageWrapper[] convertToImageArray(HashMap<String, Bitmap> bitmapHashMap, boolean sdf) {
        ImageWrapper[] images = new ImageWrapper[bitmapHashMap.size()];
        List<String> keyList = new ArrayList<>(bitmapHashMap.keySet());
        for (int i = 0; i < bitmapHashMap.size(); i++) {
          String id = keyList.get(i);
          images[i] = new ImageWrapper(id, bitmapHashMap.get(id), sdf);
        }
        return images;
      }
    }

    class LayerWrapper {
      Layer layer;

      LayerWrapper(Layer layer) {
        this.layer = layer;
      }
    }

    class LayerAboveWrapper extends LayerWrapper {
      String aboveLayer;

      LayerAboveWrapper(Layer layer, String aboveLayer) {
        super(layer);
        this.aboveLayer = aboveLayer;
      }
    }

    class LayerBelowWrapper extends LayerWrapper {
      String belowLayer;

      LayerBelowWrapper(Layer layer, String belowLayer) {
        super(layer);
        this.belowLayer = belowLayer;
      }
    }

    class LayerAtWrapper extends LayerWrapper {
      int index;

      LayerAtWrapper(Layer layer, int index) {
        super(layer);
        this.index = index;
      }
    }
  }

  private static class BitmapImageConversionTask extends AsyncTask<Builder.ImageWrapper, Void, List<Image>> {

    private WeakReference<NativeMap> nativeMap;
    private boolean sdf;

    BitmapImageConversionTask(NativeMap nativeMap, boolean sdf) {
      this.nativeMap = new WeakReference<>(nativeMap);
      this.sdf = sdf;
    }

    @NonNull
    @Override
    protected List<Image> doInBackground(Builder.ImageWrapper... params) {
      List<Image> images = new ArrayList<>();
      ByteBuffer buffer;
      String name;
      Bitmap bitmap;

      for (Builder.ImageWrapper param : params) {
        name = param.id;
        bitmap = param.bitmap;

        if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
          bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
        }

        buffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(buffer);

        float pixelRatio = (float) bitmap.getDensity() / DisplayMetrics.DENSITY_DEFAULT;

        images.add(new Image(buffer.array(), pixelRatio, name, bitmap.getWidth(), bitmap.getHeight(), sdf));
      }

      return images;
    }

    @Override
    protected void onPostExecute(@NonNull List<Image> images) {
      super.onPostExecute(images);
      NativeMap nativeMap = this.nativeMap.get();
      if (nativeMap != null && !nativeMap.isDestroyed()) {
        nativeMap.addImages(images.toArray(new Image[images.size()]));
      }
    }
  }

  /**
   * Callback to be invoked when a style has finished loading.
   */
  public interface OnStyleLoaded {
    /**
     * Invoked when a style has finished loading.
     *
     * @param style the style that has finished loading
     */
    void onStyleLoaded(@NonNull Style style);
  }

  //
  // Style URL constants
  //

  /**
   * Indicates the parameter accepts one of the values from Style. Using one of these
   * constants means your map style will always use the latest version and may change as we
   * improve the style
   */
  @StringDef( {MAPBOX_STREETS, OUTDOORS, LIGHT, DARK, SATELLITE, SATELLITE_STREETS, TRAFFIC_DAY, TRAFFIC_NIGHT})
  @Retention(RetentionPolicy.SOURCE)
  public @interface StyleUrl {
  }

  // IMPORTANT: If you change any of these you also need to edit them in strings.xml

  /**
   * Mapbox Streets: A complete basemap, perfect for incorporating your own data. Using this
   * constant means your map style will always use the latest version and may change as we
   * improve the style.
   */
  public static final String MAPBOX_STREETS = "mapbox://styles/mapbox/streets-v11";

  /**
   * Outdoors: A general-purpose style tailored to outdoor activities. Using this constant means
   * your map style will always use the latest version and may change as we improve the style.
   */
  public static final String OUTDOORS = "mapbox://styles/mapbox/outdoors-v11";

  /**
   * Light: Subtle light backdrop for data visualizations. Using this constant means your map
   * style will always use the latest version and may change as we improve the style.
   */
  public static final String LIGHT = "mapbox://styles/mapbox/light-v10";

  /**
   * Dark: Subtle dark backdrop for data visualizations. Using this constant means your map style
   * will always use the latest version and may change as we improve the style.
   */
  public static final String DARK = "mapbox://styles/mapbox/dark-v10";

  /**
   * Satellite: A beautiful global satellite and aerial imagery layer. Using this constant means
   * your map style will always use the latest version and may change as we improve the style.
   */
  public static final String SATELLITE = "mapbox://styles/mapbox/satellite-v9";

  /**
   * Satellite Streets: Global satellite and aerial imagery with unobtrusive labels. Using this
   * constant means your map style will always use the latest version and may change as we
   * improve the style.
   */
  public static final String SATELLITE_STREETS = "mapbox://styles/mapbox/satellite-streets-v11";

  /**
   * Traffic Day: Color-coded roads based on live traffic congestion data. Traffic data is currently
   * available in
   * <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
   * countries</a>. Using this constant means your map style will always use the latest version and
   * may change as we improve the style.
   */
  public static final String TRAFFIC_DAY = "mapbox://styles/mapbox/traffic-day-v2";

  /**
   * Traffic Night: Color-coded roads based on live traffic congestion data, designed to maximize
   * legibility in low-light situations. Traffic data is currently available in
   * <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
   * countries</a>. Using this constant means your map style will always use the latest version and
   * may change as we improve the style.
   */
  public static final String TRAFFIC_NIGHT = "mapbox://styles/mapbox/traffic-night-v2";
}