-
Notifications
You must be signed in to change notification settings - Fork 497
/
SymbolLayerMapillaryActivity.java
1199 lines (1045 loc) · 42 KB
/
SymbolLayerMapillaryActivity.java
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
package com.mapbox.mapboxandroiddemo.labs;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.GsonBuilder;
import com.mapbox.mapboxandroiddemo.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.style.functions.stops.Stop;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.LineLayer;
import com.mapbox.mapboxsdk.style.layers.Property;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonOptions;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.style.sources.TileSet;
import com.mapbox.mapboxsdk.style.sources.VectorSource;
import com.mapbox.services.commons.geojson.Feature;
import com.mapbox.services.commons.geojson.FeatureCollection;
import com.mapbox.services.commons.geojson.Geometry;
import com.mapbox.services.commons.geojson.Point;
import com.mapbox.services.commons.geojson.custom.GeometryDeserializer;
import com.mapbox.services.commons.geojson.custom.PositionDeserializer;
import com.mapbox.services.commons.models.Position;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import timber.log.Timber;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.mapbox.mapboxsdk.style.functions.Function.property;
import static com.mapbox.mapboxsdk.style.functions.Function.zoom;
import static com.mapbox.mapboxsdk.style.functions.stops.Stop.stop;
import static com.mapbox.mapboxsdk.style.functions.stops.Stops.categorical;
import static com.mapbox.mapboxsdk.style.functions.stops.Stops.exponential;
import static com.mapbox.mapboxsdk.style.layers.Filter.all;
import static com.mapbox.mapboxsdk.style.layers.Filter.eq;
import static com.mapbox.mapboxsdk.style.layers.Filter.gte;
import static com.mapbox.mapboxsdk.style.layers.Filter.lt;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAnchor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconOffset;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconSize;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineCap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textField;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textOffset;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textSize;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
public class SymbolLayerMapillaryActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String SOURCE_ID = "mapbox.poi";
private static final String MAKI_LAYER_ID = "mapbox.poi.maki";
private static final String LOADING_LAYER_ID = "mapbox.poi.loading";
private static final String CALLOUT_LAYER_ID = "mapbox.poi.callout";
private static final String PROPERTY_SELECTED = "selected";
private static final String PROPERTY_LOADING = "loading";
private static final String PROPERTY_LOADING_PROGRESS = "loading_progress";
private static final String PROPERTY_TITLE = "title";
private static final String PROPERTY_FAVOURITE = "favourite";
private static final String PROPERTY_DESCRIPTION = "description";
private static final String PROPERTY_POI = "poi";
private static final String PROPERTY_STYLE = "style";
private static final long CAMERA_ANIMATION_TIME = 1950;
private static final float LOADING_CIRCLE_RADIUS = 60;
private static final int LOADING_PROGRESS_STEPS = 25; //number of steps in a progress animation
private static final int LOADING_STEP_DURATION = 50; //duration between each step
private MapView mapView;
private MapboxMap mapboxMap;
private RecyclerView recyclerView;
private GeoJsonSource source;
private FeatureCollection featureCollection;
private HashMap<String, View> viewMap;
private AnimatorSet animatorSet;
private LoadMapillaryDataTask loadMapillaryDataTask;
@ActivityStep
private int currentStep;
@Retention(RetentionPolicy.SOURCE)
@IntDef( {STEP_INITIAL, STEP_LOADING, STEP_READY})
public @interface ActivityStep {
}
private static final int STEP_INITIAL = 0;
private static final int STEP_LOADING = 1;
private static final int STEP_READY = 2;
private static final Map<Integer, Double> stepZoomMap = new HashMap<>();
static {
stepZoomMap.put(STEP_INITIAL, 11.0);
stepZoomMap.put(STEP_LOADING, 13.5);
stepZoomMap.put(STEP_READY, 18.0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_symbol_layer_mapillary);
recyclerView = (RecyclerView) findViewById(R.id.rv_on_top_of_map);
// Initialize the map view
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.getUiSettings().setCompassEnabled(false);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.getUiSettings().setAttributionEnabled(false);
new LoadPoiDataTask(this).execute();
}
public void setupData(final FeatureCollection collection) {
if (mapboxMap == null) {
return;
}
featureCollection = collection;
setupSource();
setupMakiLayer();
setupLoadingLayer();
setupCalloutLayer();
setupClickListeners();
setupRecyclerView();
hideLabelLayers();
setupMapillaryTiles();
}
private void setupSource() {
source = new GeoJsonSource(SOURCE_ID, featureCollection);
mapboxMap.addSource(source);
}
private void refreshSource() {
if (source != null && featureCollection != null) {
source.setGeoJson(featureCollection);
}
}
/**
* Setup a layer with maki icons, eg. restaurant.
*/
private void setupMakiLayer() {
mapboxMap.addLayer(new SymbolLayer(MAKI_LAYER_ID, SOURCE_ID)
.withProperties(
/* show maki icon based on the value of poi feature property
* https://www.mapbox.com/maki-icons/
*/
iconImage("{poi}-15"),
/* allows show all icons */
iconAllowOverlap(true),
/* when feature is in selected state, grow icon */
iconSize(
property(
PROPERTY_SELECTED,
categorical(
stop(true, iconSize(1.5f)),
stop(false, iconSize(1.0f))
)
)
)
)
);
}
/**
* Setup layer indicating that there is an ongoing progress.
*/
private void setupLoadingLayer() {
mapboxMap.addLayerBelow(new CircleLayer(LOADING_LAYER_ID, SOURCE_ID)
.withProperties(
circleRadius(property(
PROPERTY_LOADING_PROGRESS, exponential(
getLoadingAnimationStops()
)
)),
circleColor(Color.GRAY),
circleOpacity(0.6f)
)
.withFilter(eq(PROPERTY_LOADING, true)),
MAKI_LAYER_ID
);
}
private Stop<Integer, Float>[] getLoadingAnimationStops() {
List<Stop<Integer, Float>> stops = new ArrayList<>();
for (int i = 0; i < LOADING_PROGRESS_STEPS; i++) {
stops.add(stop(i, circleRadius(LOADING_CIRCLE_RADIUS * i / LOADING_PROGRESS_STEPS)));
}
return stops.toArray(new Stop[LOADING_PROGRESS_STEPS]);
}
/**
* Setup a layer with Android SDK call-outs
* <p>
* title of the feature is used as key for the iconImage
* </p>
*/
private void setupCalloutLayer() {
mapboxMap.addLayer(new SymbolLayer(CALLOUT_LAYER_ID, SOURCE_ID)
.withProperties(
/* show image with id title based on the value of the title feature property */
iconImage("{title}"),
/* set anchor of icon to bottom-left */
iconAnchor("bottom-left"),
/* offset icon slightly to match bubble layout */
iconOffset(new Float[] {-20.0f, -10.0f})
)
/* add a filter to show only when selected feature property is true */
.withFilter(eq(PROPERTY_SELECTED, true))
);
}
/**
* Use OnMapClickListener in combination with queryRenderedFeatures
*/
private void setupClickListeners() {
mapboxMap.setOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
PointF screenPoint = mapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = mapboxMap.queryRenderedFeatures(screenPoint, CALLOUT_LAYER_ID);
if (!features.isEmpty()) {
// we received a click event on the callout layer
Feature feature = features.get(0);
PointF symbolScreenPoint = mapboxMap.getProjection().toScreenLocation(convertToLatLng(feature));
handleClickCallout(feature, screenPoint, symbolScreenPoint);
} else {
// we didn't find a click event on callout layer, try clicking maki layer
handleClickIcon(screenPoint);
}
}
});
}
private void setupRecyclerView() {
RecyclerView.Adapter adapter = new LocationRecyclerViewAdapter(this, featureCollection);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == SCROLL_STATE_IDLE) {
int index = layoutManager.findFirstVisibleItemPosition();
setSelected(index, false);
}
}
});
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
}
private void hideLabelLayers() {
String id;
for (Layer layer : mapboxMap.getLayers()) {
id = layer.getId();
if (id.startsWith("place") || id.startsWith("poi") || id.startsWith("marine") || id.startsWith("road-label")) {
layer.setProperties(visibility("none"));
}
}
}
private void setupMapillaryTiles() {
mapboxMap.addSource(MapillaryTiles.createSource());
mapboxMap.addLayerBelow(MapillaryTiles.createLineLayer(), LOADING_LAYER_ID);
}
/**
* This method handles click events for callout symbols.
* <p>
* It creates a hit rectangle based on the the textView, offsets that rectangle to the location
* of the symbol on screen and hit tests that with the screen point.
* </p>
*
* @param feature the feature that was clicked
* @param screenPoint the point on screen clicked
* @param symbolScreenPoint the point of the symbol on screen
*/
private void handleClickCallout(Feature feature, PointF screenPoint, PointF symbolScreenPoint) {
View view = viewMap.get(feature.getStringProperty(PROPERTY_TITLE));
View textContainer = view.findViewById(R.id.text_container);
// create hitbox for textView
Rect hitRectText = new Rect();
textContainer.getHitRect(hitRectText);
// move hitbox to location of symbol
hitRectText.offset((int) symbolScreenPoint.x, (int) symbolScreenPoint.y);
// offset vertically to match anchor behaviour
hitRectText.offset(0, -view.getMeasuredHeight());
// hit test if clicked point is in textview hitbox
if (hitRectText.contains((int) screenPoint.x, (int) screenPoint.y)) {
// user clicked on text
String callout = feature.getStringProperty("call-out");
Toast.makeText(this, callout, Toast.LENGTH_LONG).show();
} else {
// user clicked on icon
List<Feature> featureList = featureCollection.getFeatures();
for (int i = 0; i < featureList.size(); i++) {
if (featureList.get(i).getStringProperty(PROPERTY_TITLE).equals(feature.getStringProperty(PROPERTY_TITLE))) {
toggleFavourite(i);
}
}
}
}
/**
* This method handles click events for maki symbols.
* <p>
* When a maki symbol is clicked, we moved that feature to the selected state.
* </p>
*
* @param screenPoint the point on screen clicked
*/
private void handleClickIcon(PointF screenPoint) {
List<Feature> features = mapboxMap.queryRenderedFeatures(screenPoint, MAKI_LAYER_ID);
if (!features.isEmpty()) {
String title = features.get(0).getStringProperty(PROPERTY_TITLE);
List<Feature> featureList = featureCollection.getFeatures();
for (int i = 0; i < featureList.size(); i++) {
if (featureList.get(i).getStringProperty(PROPERTY_TITLE).equals(title)) {
setSelected(i, true);
}
}
}
}
/**
* Set a feature selected state with the ability to scroll the RecycleViewer to the provided index.
*
* @param index the index of selected feature
* @param withScroll indicates if the recyclerView position should be updated
*/
private void setSelected(int index, boolean withScroll) {
if (recyclerView.getVisibility() == View.GONE) {
recyclerView.setVisibility(View.VISIBLE);
}
deselectAll(false);
Feature feature = featureCollection.getFeatures().get(index);
selectFeature(feature);
animateCameraToSelection(feature);
refreshSource();
loadMapillaryData(feature);
if (withScroll) {
recyclerView.scrollToPosition(index);
}
}
/**
* Deselects the state of all the features
*/
private void deselectAll(boolean hideRecycler) {
for (Feature feature : featureCollection.getFeatures()) {
feature.getProperties().addProperty(PROPERTY_SELECTED, false);
}
if (hideRecycler) {
recyclerView.setVisibility(View.GONE);
}
}
/**
* Selects the state of a feature
*
* @param feature the feature to be selected.
*/
private void selectFeature(Feature feature) {
feature.getProperties().addProperty(PROPERTY_SELECTED, true);
}
private Feature getSelectedFeature() {
if (featureCollection != null) {
for (Feature feature : featureCollection.getFeatures()) {
if (feature.getBooleanProperty(PROPERTY_SELECTED)) {
return feature;
}
}
}
return null;
}
/**
* Animate camera to a feature.
*
* @param feature the feature to animate to
*/
private void animateCameraToSelection(Feature feature, double newZoom) {
CameraPosition cameraPosition = mapboxMap.getCameraPosition();
if (animatorSet != null) {
animatorSet.cancel();
}
animatorSet = new AnimatorSet();
animatorSet.playTogether(
createLatLngAnimator(cameraPosition.target, convertToLatLng(feature)),
createZoomAnimator(cameraPosition.zoom, newZoom),
createBearingAnimator(cameraPosition.bearing, feature.getNumberProperty("bearing").doubleValue()),
createTiltAnimator(cameraPosition.tilt, feature.getNumberProperty("tilt").doubleValue())
);
animatorSet.start();
}
private void animateCameraToSelection(Feature feature) {
double zoom = feature.getNumberProperty("zoom").doubleValue();
animateCameraToSelection(feature, zoom);
}
private void loadMapillaryData(Feature feature) {
if (loadMapillaryDataTask != null) {
loadMapillaryDataTask.cancel(true);
}
loadMapillaryDataTask = new LoadMapillaryDataTask(this,
mapboxMap, Picasso.with(getApplicationContext()), new Handler(), feature);
loadMapillaryDataTask.execute(50);
}
/**
* Set the favourite state of a feature based on the index.
*
* @param index the index of the feature to favourite/de-favourite
*/
private void toggleFavourite(int index) {
Feature feature = featureCollection.getFeatures().get(index);
String title = feature.getStringProperty(PROPERTY_TITLE);
boolean currentState = feature.getBooleanProperty(PROPERTY_FAVOURITE);
feature.getProperties().addProperty(PROPERTY_FAVOURITE, !currentState);
View view = viewMap.get(title);
ImageView imageView = (ImageView) view.findViewById(R.id.logoView);
imageView.setImageResource(currentState ? R.drawable.ic_favorite : R.drawable.ic_favorite_border);
Bitmap bitmap = SymbolGenerator.generate(view);
mapboxMap.addImage(title, bitmap);
refreshSource();
}
/**
* Invoked when the bitmaps have been generated from a view.
*/
public void setImageGenResults(HashMap<String, View> viewMap, HashMap<String, Bitmap> imageMap) {
if (mapboxMap != null) {
// calling addImages is faster as separate addImage calls for each bitmap.
mapboxMap.addImages(imageMap);
}
// need to store reference to views to be able to use them as hitboxes for click events.
this.viewMap = viewMap;
}
private void setActivityStep(@ActivityStep int activityStep) {
Feature selectedFeature = getSelectedFeature();
double zoom = stepZoomMap.get(activityStep);
animateCameraToSelection(selectedFeature, zoom);
currentStep = activityStep;
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onStop() {
super.onStop();
if (loadMapillaryDataTask != null) {
loadMapillaryDataTask.cancel(true);
}
mapView.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onBackPressed() {
if (currentStep == STEP_LOADING || currentStep == STEP_READY) {
if (loadMapillaryDataTask != null) {
loadMapillaryDataTask.cancel(true);
}
setActivityStep(STEP_INITIAL);
deselectAll(true);
refreshSource();
} else {
super.onBackPressed();
}
}
private LatLng convertToLatLng(Feature feature) {
Point symbolPoint = (Point) feature.getGeometry();
Position position = symbolPoint.getCoordinates();
return new LatLng(position.getLatitude(), position.getLongitude());
}
private Animator createLatLngAnimator(LatLng currentPosition, LatLng targetPosition) {
ValueAnimator latLngAnimator = ValueAnimator.ofObject(new LatLngEvaluator(), currentPosition, targetPosition);
latLngAnimator.setDuration(CAMERA_ANIMATION_TIME);
latLngAnimator.setInterpolator(new FastOutSlowInInterpolator());
latLngAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mapboxMap.setLatLng((LatLng) animation.getAnimatedValue());
}
});
return latLngAnimator;
}
private Animator createZoomAnimator(double currentZoom, double targetZoom) {
ValueAnimator zoomAnimator = ValueAnimator.ofFloat((float) currentZoom, (float) targetZoom);
zoomAnimator.setDuration(CAMERA_ANIMATION_TIME);
zoomAnimator.setInterpolator(new FastOutSlowInInterpolator());
zoomAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mapboxMap.setZoom((Float) animation.getAnimatedValue());
}
});
return zoomAnimator;
}
private Animator createBearingAnimator(double currentBearing, double targetBearing) {
ValueAnimator bearingAnimator = ValueAnimator.ofFloat((float) currentBearing, (float) targetBearing);
bearingAnimator.setDuration(CAMERA_ANIMATION_TIME);
bearingAnimator.setInterpolator(new FastOutSlowInInterpolator());
bearingAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mapboxMap.setBearing((Float) animation.getAnimatedValue());
}
});
return bearingAnimator;
}
private Animator createTiltAnimator(double currentTilt, double targetTilt) {
ValueAnimator tiltAnimator = ValueAnimator.ofFloat((float) currentTilt, (float) targetTilt);
tiltAnimator.setDuration(CAMERA_ANIMATION_TIME);
tiltAnimator.setInterpolator(new FastOutSlowInInterpolator());
tiltAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mapboxMap.setTilt((Float) animation.getAnimatedValue());
}
});
return tiltAnimator;
}
/**
* Helper class to evaluate LatLng objects with a ValueAnimator
*/
private static class LatLngEvaluator implements TypeEvaluator<LatLng> {
private final LatLng latLng = new LatLng();
@Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
latLng.setLatitude(startValue.getLatitude()
+ ((endValue.getLatitude() - startValue.getLatitude()) * fraction));
latLng.setLongitude(startValue.getLongitude()
+ ((endValue.getLongitude() - startValue.getLongitude()) * fraction));
return latLng;
}
}
/**
* AsyncTask to load data from the assets folder.
*/
private static class LoadPoiDataTask extends AsyncTask<Void, Void, FeatureCollection> {
private final WeakReference<SymbolLayerMapillaryActivity> activityRef;
LoadPoiDataTask(SymbolLayerMapillaryActivity activity) {
this.activityRef = new WeakReference<>(activity);
}
@Override
protected FeatureCollection doInBackground(Void... params) {
SymbolLayerMapillaryActivity activity = activityRef.get();
if (activity == null) {
return null;
}
String geoJson = loadGeoJsonFromAsset(activity, "sf_poi.geojson");
return new GsonBuilder()
.registerTypeAdapter(Geometry.class, new GeometryDeserializer())
.registerTypeAdapter(Position.class, new PositionDeserializer())
.create().fromJson(geoJson, FeatureCollection.class);
}
@Override
protected void onPostExecute(FeatureCollection featureCollection) {
super.onPostExecute(featureCollection);
SymbolLayerMapillaryActivity activity = activityRef.get();
if (featureCollection == null || activity == null) {
return;
}
activity.setupData(featureCollection);
new GenerateViewIconTask(activity).execute(featureCollection);
}
static String loadGeoJsonFromAsset(Context context, String filename) {
try {
// Load GeoJSON file from local asset folder
InputStream is = context.getAssets().open(filename);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
}
/**
* AsyncTask to generate Bitmap from Views to be used as iconImage in a SymbolLayer.
* <p>
* Call be optionally be called to update the underlying data source after execution.
* </p>
* <p>
* Generating Views on background thread since we are not going to be adding them to the view hierarchy.
* </p>
*/
private static class GenerateViewIconTask extends AsyncTask<FeatureCollection, Void, HashMap<String, Bitmap>> {
private final HashMap<String, View> viewMap = new HashMap<>();
private final WeakReference<SymbolLayerMapillaryActivity> activityRef;
private final boolean refreshSource;
GenerateViewIconTask(SymbolLayerMapillaryActivity activity, boolean refreshSource) {
this.activityRef = new WeakReference<>(activity);
this.refreshSource = refreshSource;
}
GenerateViewIconTask(SymbolLayerMapillaryActivity activity) {
this(activity, false);
}
@SuppressWarnings("WrongThread")
@Override
protected HashMap<String, Bitmap> doInBackground(FeatureCollection... params) {
SymbolLayerMapillaryActivity activity = activityRef.get();
if (activity != null) {
HashMap<String, Bitmap> imagesMap = new HashMap<>();
LayoutInflater inflater = LayoutInflater.from(activity);
FeatureCollection featureCollection = params[0];
for (Feature feature : featureCollection.getFeatures()) {
View view = inflater.inflate(R.layout.layout_callout, null);
String name = feature.getStringProperty(PROPERTY_TITLE);
TextView titleTv = (TextView) view.findViewById(R.id.title);
titleTv.setText(name);
String style = feature.getStringProperty(PROPERTY_STYLE);
TextView styleTv = (TextView) view.findViewById(R.id.style);
styleTv.setText(style);
boolean favourite = feature.getBooleanProperty(PROPERTY_FAVOURITE);
ImageView imageView = (ImageView) view.findViewById(R.id.logoView);
imageView.setImageResource(favourite ? R.drawable.ic_favorite : R.drawable.ic_favorite_border);
Bitmap bitmap = SymbolGenerator.generate(view);
imagesMap.put(name, bitmap);
viewMap.put(name, view);
}
return imagesMap;
} else {
return null;
}
}
@Override
protected void onPostExecute(HashMap<String, Bitmap> bitmapHashMap) {
super.onPostExecute(bitmapHashMap);
SymbolLayerMapillaryActivity activity = activityRef.get();
if (activity != null && bitmapHashMap != null) {
activity.setImageGenResults(viewMap, bitmapHashMap);
if (refreshSource) {
activity.refreshSource();
}
}
}
}
/**
* Async task which fetches pictures from around the POI using Mapillary services.
* https://www.mapillary.com/developer/api-documentation/
*/
private static class LoadMapillaryDataTask extends AsyncTask<Integer, Void, MapillaryDataLoadResult> {
static final String URL_IMAGE_PLACEHOLDER = "https://d1cuyjsrcm0gby.cloudfront.net/%s/thumb-320.jpg";
static final String KEY_UNIQUE_FEATURE = "key";
static final String TOKEN_UNIQUE_FEATURE = "{" + KEY_UNIQUE_FEATURE + "}";
static final String ID_SOURCE = "cluster_source";
static final String ID_LAYER_UNCLUSTERED = "unclustered_layer";
static final int IMAGE_SIZE = 128;
static final String API_URL = "https://a.mapillary.com/v3/images/"
+ "?lookat=%f,%f&closeto=%f,%f&radius=%d"
+ "&client_id=bjgtc1FDTnFPaXpxeTZuUDNabmJ5dzozOGE1ODhkMmEyYTkyZTI4";
private WeakReference<SymbolLayerMapillaryActivity> activityRef;
private MapboxMap map;
private Picasso picasso;
private final Handler progressHandler;
private int loadingProgress;
private boolean loadingIncrease = true;
private Feature feature;
public LoadMapillaryDataTask(SymbolLayerMapillaryActivity activity, MapboxMap map, Picasso picasso,
Handler progressHandler, Feature feature) {
this.activityRef = new WeakReference<>(activity);
this.map = map;
this.picasso = picasso;
this.progressHandler = progressHandler;
this.feature = feature;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingProgress = 0;
setLoadingState(true, false);
}
@Override
protected MapillaryDataLoadResult doInBackground(Integer... radius) {
progressHandler.post(progressRunnable);
try {
Thread.sleep(2500); //ensure loading visualisation
} catch (InterruptedException exception) {
exception.printStackTrace();
}
OkHttpClient okHttpClient = new OkHttpClient();
try {
Position poiPosition = (Position) feature.getGeometry().getCoordinates();
@SuppressLint("DefaultLocale") Request request = new Request.Builder()
.url(String.format(API_URL,
poiPosition.getLongitude(), poiPosition.getLatitude(),
poiPosition.getLongitude(), poiPosition.getLatitude(),
radius[0]
))
.build();
Response response = okHttpClient.newCall(request).execute();
FeatureCollection featureCollection = FeatureCollection.fromJson(response.body().string());
MapillaryDataLoadResult mapillaryDataLoadResult = new MapillaryDataLoadResult(featureCollection);
for (Feature feature : featureCollection.getFeatures()) {
String imageId = feature.getStringProperty(KEY_UNIQUE_FEATURE);
String imageUrl = String.format(URL_IMAGE_PLACEHOLDER, imageId);
Bitmap bitmap = picasso.load(imageUrl).resize(IMAGE_SIZE, IMAGE_SIZE).get();
//cropping bitmap to be circular
bitmap = getCroppedBitmap(bitmap);
mapillaryDataLoadResult.add(feature, bitmap);
}
return mapillaryDataLoadResult;
} catch (Exception exception) {
Timber.e(exception);
}
return null;
}
@Override
protected void onPostExecute(MapillaryDataLoadResult mapillaryDataLoadResult) {
super.onPostExecute(mapillaryDataLoadResult);
setLoadingState(false, true);
if (mapillaryDataLoadResult == null) {
SymbolLayerMapillaryActivity activity = activityRef.get();
if (activity != null) {
Toast.makeText(activity, "Error. Unable to load Mapillary data.", Toast.LENGTH_LONG).show();
}
return;
}
FeatureCollection featureCollection = mapillaryDataLoadResult.mapillaryFeatureCollection;
Map<Feature, Bitmap> bitmapMap = mapillaryDataLoadResult.bitmapHashMap;
for (Map.Entry<Feature, Bitmap> featureBitmapEntry : bitmapMap.entrySet()) {
Feature feature = featureBitmapEntry.getKey();
String key = feature.getStringProperty(KEY_UNIQUE_FEATURE);
map.addImage(key, featureBitmapEntry.getValue());
}
GeoJsonSource mapillarySource = (GeoJsonSource) map.getSource(ID_SOURCE);
if (mapillarySource == null) {
map.addSource(new GeoJsonSource(ID_SOURCE, featureCollection, new GeoJsonOptions()
.withCluster(true)
.withClusterMaxZoom(17)
.withClusterRadius(IMAGE_SIZE / 3)
));
// unclustered
map.addLayerBelow(new SymbolLayer(ID_LAYER_UNCLUSTERED, ID_SOURCE)
.withProperties(
iconImage(TOKEN_UNIQUE_FEATURE),
iconAllowOverlap(true),
iconSize(zoom(
exponential(
stop(18, iconSize(1.7f)),
stop(17, iconSize(1.4f)),
stop(16, iconSize(1.1f)),
stop(15, iconSize(0.8f)),
stop(12, iconSize(0.0f))
)
))
), MAKI_LAYER_ID);
// clustered
int[][] layers = new int[][] {
new int[] {20, Color.RED},
new int[] {10, Color.BLUE},
new int[] {0, Color.GREEN}
};
for (int i = 0; i < layers.length; i++) {
//Add cluster circles
CircleLayer clusterLayer = new CircleLayer("cluster-" + i, ID_SOURCE);
clusterLayer.setProperties(
circleColor(layers[i][1]),
circleRadius(zoom(
exponential(
stop(16, circleRadius(20f)),
stop(15, circleRadius(18f)),
stop(14, circleRadius(16f)),
stop(12, circleRadius(10f))
)
)),
circleOpacity(0.6f)
);
// Add a filter to the cluster layer that hides the circles based on "point_count"
clusterLayer.setFilter(
i == 0
? gte("point_count", layers[i][0]) :
all(gte("point_count", layers[i][0]), lt("point_count", layers[i - 1][0]))
);
map.addLayerBelow(clusterLayer, MAKI_LAYER_ID);
}
//Add the count labels
SymbolLayer count = new SymbolLayer("count", ID_SOURCE);
count.setProperties(
textField("{point_count}"),
textSize(8f),
textOffset(new Float[] {0.0f, 0.0f}),
textColor(Color.WHITE),
textIgnorePlacement(true)
);
map.addLayerBelow(count, MAKI_LAYER_ID);
} else {
mapillarySource.setGeoJson(featureCollection);
}
}
static Bitmap getCroppedBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
// canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
//Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
//return _bmp;
return output;
}