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

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;

import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.Polygon;
import com.mapbox.mapboxsdk.annotations.Polyline;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.ProjectedMeters;
import com.mapbox.mapboxsdk.offline.OfflineManager;
import com.mapbox.mapboxsdk.style.layers.CannotAddLayerException;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.NoSuchLayerException;
import com.mapbox.mapboxsdk.style.sources.CannotAddSourceException;
import com.mapbox.mapboxsdk.style.sources.NoSuchSourceException;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.services.commons.geojson.Feature;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import timber.log.Timber;

// Class that wraps the native methods for convenience
final class NativeMapView {

  // Holds the pointer to JNI NativeMapView
  private long nativePtr = 0;

  // Used for callbacks
  private MapView mapView;

  // Device density
  private final float pixelRatio;

  // Listeners for Map change events
  private CopyOnWriteArrayList<MapView.OnMapChangedListener> onMapChangedListeners = new CopyOnWriteArrayList<>();

  // Listener invoked to return a bitmap of the map
  private MapboxMap.SnapshotReadyCallback snapshotReadyCallback;

  //
  // Static methods
  //

  static {
    System.loadLibrary("mapbox-gl");
  }

  //
  // Constructors
  //

  NativeMapView(MapView mapView) {
    this.mapView = mapView;

    Context context = mapView.getContext();
    String cachePath = OfflineManager.getDatabasePath(context);

    pixelRatio = context.getResources().getDisplayMetrics().density;
    String apkPath = context.getPackageCodePath();

    int availableProcessors = Runtime.getRuntime().availableProcessors();

    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    activityManager.getMemoryInfo(memoryInfo);

    long totalMemory = memoryInfo.availMem;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
      totalMemory = memoryInfo.totalMem;
    }

    if (availableProcessors < 0) {
      throw new IllegalArgumentException("availableProcessors cannot be negative.");
    }

    if (totalMemory < 0) {
      throw new IllegalArgumentException("totalMemory cannot be negative.");
    }

    initialize(this, cachePath, apkPath, pixelRatio, availableProcessors, totalMemory);
  }

  //
  // Methods
  //

  private native void initialize(NativeMapView nativeMapView, String cachePath, String apkPath, float pixelRatio,
                                 int availableProcessors, long totalMemory);

  native void destroy();

  native void render();

  native void setStyleUrl(String url);

  native String getStyleUrl();

  native void setStyleJson(String styleJson);

  native String getStyleJson();

  native void setAccessToken(String accessToken);

  native String getAccessToken();

  native void cancelTransitions();

  native void setGestureInProgress(boolean inProgress);

  native void setLatLng(double latitude, double longitude);

  native void resetPosition();

  native double getPitch();

  native void setPitch(double pitch);

  @Deprecated
  void setPitch(double pitch, int duration) {
    setPitch(pitch);
  }

  native double getScale();

  native void setZoom(double zoom);

  native double getZoom();

  native void resetZoom();

  native void setMinZoom(double zoom);

  native double getMinZoom();

  native void setMaxZoom(double zoom);

  native double getMaxZoom();

  void onViewportChanged(int width, int height) {
    if (width < 0) {
      throw new IllegalArgumentException("width cannot be negative.");
    }

    if (height < 0) {
      throw new IllegalArgumentException("height cannot be negative.");
    }

    if (width > 65535) {
      // we have seen edge cases where devices return incorrect values #6111
      Timber.e("Device returned an out of range width size, "
        + "capping value at 65535 instead of " + width);
      width = 65535;
    }

    if (height > 65535) {
      // we have seen edge cases where devices return incorrect values #6111
      Timber.e("Device returned an out of range height size, "
        + "capping value at 65535 instead of " + height);
      height = 65535;
    }

    _onViewportChanged(width, height);
  }

  private native void _onViewportChanged(int width, int height);

  void update() {
    //TODO, this circle makes little sense atm...
    Timber.w("TODO; Implement update()");
    onInvalidate();
  }


  void moveBy(double dx, double dy) {
    Timber.i("Move by %sx%s", dx, dy);
    _moveBy(dx / pixelRatio, dy / pixelRatio);
  }

  private native void _moveBy(double dx, double dy);

  @Deprecated
  void moveBy(double dx, double dy, long duration) {
    moveBy(dx, dy);
  }

  void setLatLng(LatLng latLng) {
    Timber.i("setLatLng %sx%s - %s", latLng.getLatitude(), latLng.getLongitude());
    setLatLng(latLng.getLatitude(), latLng.getLongitude());
  }

  @Deprecated
  void setLatLng(LatLng latLng, long duration) {
    setLatLng(latLng);
  }

  LatLng getLatLng() {
    // wrap longitude values coming from core
    return _getLatLng().wrap();
  }

  private native LatLng _getLatLng();

  void scaleBy(double ds) {
    scaleBy(ds, Double.NaN, Double.NaN);
  }

  void scaleBy(double ds, double cx, double cy) {
    _scaleBy(ds, cx / pixelRatio, cy / pixelRatio);
  }

  private native void _scaleBy(double ds, double cx, double cy);

  @Deprecated
  void scaleBy(double ds, double cx, double cy, long duration) {
    scaleBy(ds, cx, cy);
  }

  void setScale(double scale) {
    setScale(scale, Double.NaN, Double.NaN);
  }

  void setScale(double scale, double cx, double cy) {
    _setScale(scale, cx / pixelRatio, cy / pixelRatio);
  }

  private native void _setScale(double scale, double cx, double cy);

  @Deprecated
  void setScale(double scale, double cx, double cy, long duration) {
    setScale(scale, cx, cy);
  }

  @Deprecated
  void setZoom(double zoom, long duration) {
    setZoom(zoom);
  }

  void rotateBy(double sx, double sy, double ex, double ey) {
    _rotateBy(sx / pixelRatio, sy / pixelRatio, ex, ey);
  }

  private native void _rotateBy(double sx, double sy, double ex, double ey);

  @Deprecated
  void rotateBy(double sx, double sy, double ex, double ey, long duration) {
    rotateBy(sx, sy, ex, ey);
  }

  void setContentPadding(int[] padding) {
    setContentPadding(
      padding[1] / pixelRatio,
      padding[0] / pixelRatio,
      padding[3] / pixelRatio,
      padding[2] / pixelRatio);
  }

  native void setContentPadding(double top, double left, double bottom, double right);

  @Deprecated
  void setBearing(double degrees, long duration) {
    setBearing(degrees);
  }

  native void setBearing(double degrees);

  void setBearing(double degrees, double cx, double cy) {
    _setBearingXY(degrees, cx / pixelRatio, cy / pixelRatio);
  }

  @Deprecated
  void setBearing(double degrees, double cx, double cy, long duration) {
    setBearing(degrees, cx, cy);
  }

  private native void _setBearingXY(double degrees, double cx, double cy);

  native double getBearing();

  native void resetNorth();

  long addMarker(Marker marker) {
    Marker[] markers = {marker};
    return addMarkers(markers)[0];
  }

  long[] addMarkers(List<Marker> markers) {
    return addMarkers(markers.toArray(new Marker[markers.size()]));
  }

  native long[] addMarkers(Marker... markers);

  long addPolyline(Polyline polyline) {
    Polyline[] polylines = {polyline};
    return addPolylines(polylines)[0];
  }

  long[] addPolylines(List<Polyline> polylines) {
    return addPolylines(polylines.toArray(new Polyline[polylines.size()]));
  }

  native long[] addPolylines(Polyline[] polylines);

  long addPolygon(Polygon polygon) {
    Polygon[] polygons = {polygon};
    return addPolygons(polygons)[0];
  }

  long[] addPolygons(List<Polygon> polygons) {
    return addPolygons(polygons.toArray(new Polygon[polygons.size()]));
  }

  native long[] addPolygons(Polygon[] polygons);

  void updateMarker(Marker marker) {
    LatLng position = marker.getPosition();
    updateMarker(marker.getId(), position.getLatitude(), position.getLongitude(), marker.getIcon().getId());
  }

  private native void updateMarker(long markerId, double lat, double lon, String iconId);

  void updatePolygon(Polygon polygon) {
    updatePolygon(polygon.getId(), polygon);
  }

  private native void updatePolygon(long polygonId, Polygon polygon);

  void updatePolyline(Polyline polyline) {
    updatePolyline(polyline.getId(), polyline);
  }

  private native void updatePolyline(long polylineId, Polyline polyline);

  void removeAnnotation(long id) {
    long[] ids = {id};
    removeAnnotations(ids);
  }

  native void removeAnnotations(long[] id);

  native long[] queryPointAnnotations(RectF rect);

  native void addAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels);

  @Deprecated
  void setVisibleCoordinateBounds(LatLng[] coordinates, RectF padding, double direction, long duration) {
    setVisibleCoordinateBounds(coordinates, padding, direction);
  }

  native void setVisibleCoordinateBounds(LatLng[] coordinates, RectF padding, double direction);

  native void onLowMemory();

  native void setDebug(boolean debug);

  native void cycleDebugOptions();

  native boolean getDebug();

  native boolean isFullyLoaded();

  double getMetersPerPixelAtLatitude(double lat) {
    return getMetersPerPixelAtLatitude(lat, getZoom());
  }

  private native double getMetersPerPixelAtLatitude(double lat, double zoom);

  ProjectedMeters projectedMetersForLatLng(LatLng latLng) {
    return projectedMetersForLatLng(latLng.getLatitude(), latLng.getLongitude());
  }

  native ProjectedMeters projectedMetersForLatLng(double latitude, double longitude);

  LatLng latLngForProjectedMeters(ProjectedMeters projectedMeters) {
    return latLngForProjectedMeters(projectedMeters.getNorthing(), projectedMeters.getEasting()).wrap();
  }

  private native LatLng latLngForProjectedMeters(double northing, double easting);

  LatLng latLngForPixel(PointF pixel) {
    return latLngForPixel(pixel.x / pixelRatio, pixel.y / pixelRatio).wrap();
  }

  private native LatLng latLngForPixel(float x, float y);

  PointF pixelForLatLng(LatLng latLng) {
    PointF pointF = pixelForLatLng(latLng.getLatitude(), latLng.getLongitude());
    pointF.set(pointF.x * pixelRatio, pointF.y * pixelRatio);
    return pointF;
  }

  private native PointF pixelForLatLng(double lat, double lon);

  native double getTopOffsetPixelsForAnnotationSymbol(String symbolName);

  @Deprecated
  void jumpTo(double angle, LatLng center, double pitch, double zoom) {
    Timber.w("Deprecated");
  }

  @Deprecated
  void easeTo(double angle, LatLng center, long duration, double pitch, double zoom,
              boolean easingInterpolator) {
    Timber.w("Deprecated");
  }

  @Deprecated
  void flyTo(double angle, LatLng center, long duration, double pitch, double zoom) {
    Timber.w("Deprecated");
  }

  // Runtime style Api

  native long getTransitionDuration();

  native void setTransitionDuration(long duration);

  native long getTransitionDelay();

  native void setTransitionDelay(long delay);

  native Layer getLayer(String layerId);

  void addLayer(@NonNull Layer layer, @Nullable String before) throws CannotAddLayerException {
    addLayer(layer.getNativePtr(), before);
  }

  private native void addLayer(long layerPtr, String before) throws CannotAddLayerException;

  void removeLayer(@NonNull String layerId) throws NoSuchLayerException {
    removeLayerById(layerId);
  }

  private native void removeLayerById(String layerId) throws NoSuchLayerException;

  void removeLayer(@NonNull Layer layer) throws NoSuchLayerException {
    removeLayer(layer.getNativePtr());
  }

  private native void removeLayer(long layerId) throws NoSuchLayerException;

  native Source getSource(String sourceId);

  void addSource(@NonNull Source source) throws CannotAddSourceException {
    addSource(source.getNativePtr());
  }

  private native void addSource(long nativeSourcePtr) throws CannotAddSourceException;

  void removeSource(@NonNull String sourceId) throws NoSuchSourceException {
    removeSourceById(sourceId);
  }

  private native void removeSourceById(String sourceId) throws NoSuchSourceException;

  void removeSource(@NonNull Source source) throws NoSuchSourceException {
    removeSource(source.getNativePtr());
  }

  private native void removeSource(long sourcePtr) throws NoSuchSourceException;

  void addImage(@NonNull String name, @NonNull Bitmap image) {
    // Check/correct config
    if (image.getConfig() != Bitmap.Config.ARGB_8888) {
      image = image.copy(Bitmap.Config.ARGB_8888, false);
    }

    // Get pixels
    ByteBuffer buffer = ByteBuffer.allocate(image.getByteCount());
    image.copyPixelsToBuffer(buffer);

    // Determine pixel ratio
    float density = image.getDensity() == Bitmap.DENSITY_NONE ? Bitmap.DENSITY_NONE : image.getDensity();
    float pixelRatio = density / DisplayMetrics.DENSITY_DEFAULT;

    addImage(name, image.getWidth(), image.getHeight(), pixelRatio, buffer.array());
  }

  private native void addImage(String name, int width, int height, float pixelRatio, byte[] array);

  native void removeImage(String name);

  // Feature querying //

  @NonNull
  List<Feature> queryRenderedFeatures(PointF coordinates, String... layerIds) {
    Feature[] features = queryRenderedFeaturesForPoint(coordinates.x / pixelRatio,
      coordinates.y / pixelRatio, layerIds);
    return features != null ? Arrays.asList(features) : new ArrayList<Feature>();
  }

  private native Feature[] queryRenderedFeaturesForPoint(float x, float y, String[] layerIds);

  @NonNull
  List<Feature> queryRenderedFeatures(RectF coordinates, String... layerIds) {
    Feature[] features = queryRenderedFeaturesForBox(
      coordinates.left / pixelRatio,
      coordinates.top / pixelRatio,
      coordinates.right / pixelRatio,
      coordinates.bottom / pixelRatio,
      layerIds);
    return features != null ? Arrays.asList(features) : new ArrayList<Feature>();
  }

  private native Feature[] queryRenderedFeaturesForBox(float left, float top, float right,
                                                       float bottom, String[] layerIds);

  float getPixelRatio() {
    return pixelRatio;
  }

  Context getContext() {
    return mapView.getContext();
  }

  //
  // Callbacks
  //

  /**
   * Called through JNI when the map needs to be re-rendered
   */
  protected void onInvalidate() {
    Timber.i("onInvalidate");
    mapView.onInvalidate();
  }

  /**
   * Called through JNI when the render thread needs to be woken up
   */
  protected void onWake() {
    Timber.i("wake!");
    mapView.requestRender();
  }

  /**
   * Called through JNI when the map state changed
   *
   * @param rawChange the mbgl::MapChange as an int
   */
  protected void onMapChanged(final int rawChange) {
    Timber.i("onMapChanged: %s", rawChange);
    if (onMapChangedListeners != null) {
      for (final MapView.OnMapChangedListener onMapChangedListener : onMapChangedListeners) {
        mapView.post(new Runnable() {
          @Override
          public void run() {
            onMapChangedListener.onMapChanged(rawChange);
          }
        });
      }
    }
  }

  /**
   * Called through JNI if fps is enabled and the fps changed
   *
   * @param fps the Frames Per Second
   */
  protected void onFpsChanged(double fps) {
    mapView.onFpsChanged(fps);
  }

  /**
   * Called through JNI when a requested snapshot is ready
   *
   * @param bitmap the snapshot as a bitmap
   */
  protected void onSnapshotReady(Bitmap bitmap) {
    if (snapshotReadyCallback != null && bitmap != null) {
      snapshotReadyCallback.onSnapshotReady(bitmap);
    }
  }

  native void setReachability(boolean status);

  native double[] getCameraValues();

  native void scheduleSnapshot();

  native void setApiBaseUrl(String baseUrl);

  native void enableFps(boolean enable);

  int getWidth() {
    return mapView.getWidth();
  }

  int getHeight() {
    return mapView.getHeight();
  }

  //
  // MapChangeEvents
  //

  void addOnMapChangedListener(@NonNull MapView.OnMapChangedListener listener) {
    onMapChangedListeners.add(listener);
  }

  void removeOnMapChangedListener(@NonNull MapView.OnMapChangedListener listener) {
    onMapChangedListeners.remove(listener);
  }

  //
  // Snapshot
  //

  void addSnapshotCallback(@NonNull MapboxMap.SnapshotReadyCallback callback) {
    snapshotReadyCallback = callback;
    scheduleSnapshot();
    render();
  }
}