summaryrefslogtreecommitdiff
path: root/platform/android/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxsdk/testapp/activity/style/SymbolLayerActivity.java
blob: ce2230895cfbcb0594973aadef1be398af5d0898 (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
package com.mapbox.mapboxsdk.testapp.activity.style;

import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
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.MapboxMapOptions;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.expressions.Expression;
import com.mapbox.mapboxsdk.style.layers.Property;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.testapp.R;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import timber.log.Timber;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatFontScale;
import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatTextColor;
import static com.mapbox.mapboxsdk.style.expressions.Expression.FormatOption.formatTextFont;
import static com.mapbox.mapboxsdk.style.expressions.Expression.concat;
import static com.mapbox.mapboxsdk.style.expressions.Expression.format;
import static com.mapbox.mapboxsdk.style.expressions.Expression.formatEntry;
import static com.mapbox.mapboxsdk.style.expressions.Expression.get;
import static com.mapbox.mapboxsdk.style.expressions.Expression.literal;
import static com.mapbox.mapboxsdk.style.expressions.Expression.rgb;
import static com.mapbox.mapboxsdk.style.expressions.Expression.switchCase;
import static com.mapbox.mapboxsdk.style.expressions.Expression.toBool;
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.iconColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconSize;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textAnchor;
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.textFont;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textRotationAlignment;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textSize;

/**
 * Test activity showcasing runtime manipulation of symbol layers.
 * <p>
 * Showcases the ability to offline render a symbol layer by using a packaged style and fonts from the assets folder.
 * </p>
 */
public class SymbolLayerActivity extends AppCompatActivity implements MapboxMap.OnMapClickListener, OnMapReadyCallback {

  private static final String MARKER_SOURCE = "marker-source";
  private static final String MARKER_LAYER = "marker-layer";
  private static final String ID_FEATURE_PROPERTY = "id";
  private static final String SELECTED_FEATURE_PROPERTY = "selected";
  private static final String TITLE_FEATURE_PROPERTY = "title";

  private static final String[] NORMAL_FONT_STACK = new String[] {"DIN Offc Pro Regular", "Arial Unicode MS Regular"};
  private static final String[] BOLD_FONT_STACK = new String[] {"DIN Offc Pro Bold", "Arial Unicode MS Regular"};

  private static final String MAPBOX_SIGN_SOURCE = "mapbox-sign-source";
  private static final String MAPBOX_SIGN_LAYER = "mapbox-sign-layer";

  private static final Expression TEXT_FIELD_EXPRESSION =
    switchCase(toBool(get(SELECTED_FEATURE_PROPERTY)),
      format(
        formatEntry(
          get(TITLE_FEATURE_PROPERTY),
          formatTextFont(BOLD_FONT_STACK)
        ),
        formatEntry("\nis fun!", formatFontScale(0.75))
      ),
      format(
        formatEntry("This is", formatFontScale(0.75)),
        formatEntry(
          concat(literal("\n"), get(TITLE_FEATURE_PROPERTY)),
          formatFontScale(1.25),
          formatTextFont(BOLD_FONT_STACK)
        )
      )
    );

  private final Random random = new Random();
  private GeoJsonSource markerSource;
  private FeatureCollection markerCollection;
  private SymbolLayer markerSymbolLayer;
  private SymbolLayer mapboxSignSymbolLayer;
  private MapboxMap mapboxMap;
  private MapView mapView;

  class AnimatedIcon {
    private Bitmap canvasBitmap;
    private Bitmap icon;
    private Canvas canvas;
    private String iconID;
    private ValueAnimator animator;
    private static final String PROPERTY_ROTATE = "rotate";
    PropertyValuesHolder propertyRotate = PropertyValuesHolder.ofInt(PROPERTY_ROTATE, 0, 360);
    private int angle;
    private final Paint paint = new Paint();

    public AnimatedIcon(String iconID_, Bitmap icon_) {
      iconID = iconID_;
      icon = icon_;
      canvasBitmap = Bitmap.createBitmap(icon_.getWidth(), icon_.getHeight(), icon_.getConfig());
      canvas = new Canvas(canvasBitmap);
      canvas.drawBitmap(icon,0,0, paint);
      animator = new ValueAnimator();
      animator.setValues(propertyRotate);
      animator.setInterpolator(new AccelerateDecelerateInterpolator());
      animator.setDuration(3000);
      animator.addUpdateListener(animation -> {
        angle = (int) animation.getAnimatedValue(PROPERTY_ROTATE);
        render();
      });
    }

    public Bitmap getCanvasBitmap() {
      return canvasBitmap;
    }

    public void animate() {
      animator.start();
    }

    public void render() {
      // TODO: interleave with onDidFinishRenderingFrame callback
      Matrix matrix = new Matrix();
      matrix.setRotate (angle, canvasBitmap.getWidth()/2, canvasBitmap.getHeight()/2);
      canvasBitmap.eraseColor(Color.TRANSPARENT);
      canvas.drawBitmap(icon, matrix, paint);
      Style style = mapboxMap.getStyle();
      if (style != null) {
        style.addImage(iconID, Objects.requireNonNull(getCanvasBitmap()));
      }
    }
  }

  private AnimatedIcon animatedIcon;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_symbollayer);

    // Create map configuration
    MapboxMapOptions mapboxMapOptions = new MapboxMapOptions();
    mapboxMapOptions.camera(new CameraPosition.Builder().target(
      new LatLng(52.35273, 4.91638))
      .zoom(13)
      .build()
    );

    // Create map programmatically, add to view hierarchy
    mapView = new MapView(this, mapboxMapOptions);
    mapView.getMapAsync(this);
    mapView.onCreate(savedInstanceState);
    ((ViewGroup) findViewById(R.id.container)).addView(mapView);

    // Use OnStyleImageMissing API to lazily load an icon
    mapView.addOnStyleImageMissingListener(id -> {
      Style style = mapboxMap.getStyle();
      if (style != null) {
        Timber.e("Adding image with id: %s", id);
        Bitmap androidIcon = BitmapUtils.getBitmapFromDrawable(getResources().getDrawable(R.drawable.ic_android_2));
        animatedIcon = new AnimatedIcon(id, androidIcon);
        style.addImage(id, Objects.requireNonNull(animatedIcon.getCanvasBitmap()));
      }
    });
  }

  @Override
  public void onMapReady(@NonNull MapboxMap mapboxMap) {
    this.mapboxMap = mapboxMap;
    Bitmap carBitmap = BitmapUtils.getBitmapFromDrawable(
      getResources().getDrawable(R.drawable.ic_directions_car_black));

    // marker source
    markerCollection = FeatureCollection.fromFeatures(new Feature[] {
      Feature.fromGeometry(Point.fromLngLat(4.91638, 52.35673), featureProperties("1", "Android")),
      Feature.fromGeometry(Point.fromLngLat(4.91638, 52.34673), featureProperties("2", "Car"))
    });
    markerSource = new GeoJsonSource(MARKER_SOURCE, markerCollection);

    // marker layer
    markerSymbolLayer = new SymbolLayer(MARKER_LAYER, MARKER_SOURCE)
      .withProperties(
        iconImage(get(TITLE_FEATURE_PROPERTY)),
        iconIgnorePlacement(true),
        iconAllowOverlap(true),
        iconSize(switchCase(toBool(get(SELECTED_FEATURE_PROPERTY)), literal(1.5f), literal(1.0f))),
        iconAnchor(Property.ICON_ANCHOR_BOTTOM),
        iconColor(Color.BLUE),
        textField(TEXT_FIELD_EXPRESSION),
        textFont(NORMAL_FONT_STACK),
        textColor(Color.BLUE),
        textAllowOverlap(true),
        textIgnorePlacement(true),
        textAnchor(Property.TEXT_ANCHOR_TOP),
        textSize(10f)
      );

    // mapbox sign layer
    Source mapboxSignSource = new GeoJsonSource(MAPBOX_SIGN_SOURCE, Point.fromLngLat(4.91638, 52.3510));
    mapboxSignSymbolLayer = new SymbolLayer(MAPBOX_SIGN_LAYER, MAPBOX_SIGN_SOURCE);
    shuffleMapboxSign();

    mapboxMap.setStyle(new Style.Builder()
      .fromUrl("asset://streets.json")
      .withImage("Car", Objects.requireNonNull(carBitmap), false)
      .withSources(markerSource, mapboxSignSource)
      .withLayers(markerSymbolLayer, mapboxSignSymbolLayer)
    );

    // Set a click-listener so we can manipulate the map
    mapboxMap.addOnMapClickListener(SymbolLayerActivity.this);
  }

  @Override
  public boolean onMapClick(@NonNull LatLng point) {
    // Query which features are clicked
    PointF screenLoc = mapboxMap.getProjection().toScreenLocation(point);
    List<Feature> markerFeatures = mapboxMap.queryRenderedFeatures(screenLoc, MARKER_LAYER);
    if (!markerFeatures.isEmpty()) {
      for (Feature feature : Objects.requireNonNull(markerCollection.features())) {
        if (feature.getStringProperty(ID_FEATURE_PROPERTY)
          .equals(markerFeatures.get(0).getStringProperty(ID_FEATURE_PROPERTY))) {

          // use DDS
          boolean selected = feature.getBooleanProperty(SELECTED_FEATURE_PROPERTY);
          feature.addBooleanProperty(SELECTED_FEATURE_PROPERTY, !selected);
        }
      }
      markerSource.setGeoJson(markerCollection);
    } else {
      List<Feature> mapboxSignFeatures = mapboxMap.queryRenderedFeatures(screenLoc, MAPBOX_SIGN_LAYER);
      if (!mapboxSignFeatures.isEmpty()) {
        shuffleMapboxSign();
      }
    }

    return false;
  }

  private void toggleTextSize() {
    if (markerSymbolLayer != null) {
      Number size = markerSymbolLayer.getTextSize().getValue();
      if (size != null) {
        markerSymbolLayer.setProperties((float) size > 10 ? textSize(10f) : textSize(20f));
      }
    }
  }

  private void toggleTextField() {
    if (markerSymbolLayer != null) {
      if (TEXT_FIELD_EXPRESSION.equals(markerSymbolLayer.getTextField().getExpression())) {
        markerSymbolLayer.setProperties(textField("āA"));
      } else {
        markerSymbolLayer.setProperties(textField(TEXT_FIELD_EXPRESSION));
      }
    }
  }

  private void toggleTextFont() {
    if (markerSymbolLayer != null) {
      if (Arrays.equals(markerSymbolLayer.getTextFont().getValue(), NORMAL_FONT_STACK)) {
        markerSymbolLayer.setProperties(textFont(BOLD_FONT_STACK));
      } else {
        markerSymbolLayer.setProperties(textFont(NORMAL_FONT_STACK));
      }
    }
  }

  private void animateStyleIcon() {
    animatedIcon.animate();
  }

  private void shuffleMapboxSign() {
    if (mapboxSignSymbolLayer != null) {
      mapboxSignSymbolLayer.setProperties(
        textField(
          format(
            formatEntry("M", formatFontScale(2)),
            getRandomColorEntryForString("a"),
            getRandomColorEntryForString("p"),
            getRandomColorEntryForString("b"),
            getRandomColorEntryForString("o"),
            getRandomColorEntryForString("x")
          )
        ),
        textColor(Color.BLACK),
        textFont(BOLD_FONT_STACK),
        textSize(25f),
        textRotationAlignment(Property.TEXT_ROTATION_ALIGNMENT_MAP)
      );
    }
  }

  private Expression.FormatEntry getRandomColorEntryForString(@NonNull String string) {
    return formatEntry(string,
      formatTextColor(
        rgb(
          random.nextInt(256),
          random.nextInt(256),
          random.nextInt(256)
        )
      ));
  }

  private JsonObject featureProperties(@NonNull String id, @NonNull String title) {
    JsonObject object = new JsonObject();
    object.add(ID_FEATURE_PROPERTY, new JsonPrimitive(id));
    object.add(TITLE_FEATURE_PROPERTY, new JsonPrimitive(title));
    object.add(SELECTED_FEATURE_PROPERTY, new JsonPrimitive(false));
    return object;
  }

  @Override
  protected void onStart() {
    super.onStart();
    mapView.onStart();
  }

  @Override
  protected void onResume() {
    super.onResume();
    mapView.onResume();
  }

  @Override
  protected void onPause() {
    super.onPause();
    mapView.onPause();
  }

  @Override
  protected void onStop() {
    super.onStop();
    mapView.onStop();
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (mapboxMap != null) {
      mapboxMap.removeOnMapClickListener(this);
    }
    mapView.onDestroy();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_symbol_layer, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.action_toggle_text_size:
        toggleTextSize();
        return true;
      case R.id.action_toggle_text_field:
        toggleTextField();
        return true;
      case R.id.action_toggle_text_font:
        toggleTextFont();
        return true;
      case R.id.action_animate_style_icon:
        animateStyleIcon();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
}