Convert more of the Android SKD files from Java to Kotlin (#670)
This commit is contained in:
committed by
GitHub
parent
9d99adc431
commit
4f15cf96e6
@@ -1,176 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import android.os.Parcel;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.mapbox.geojson.Feature;
|
||||
import com.mapbox.geojson.Geometry;
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
|
||||
import com.mapbox.turf.TurfMeasurement;
|
||||
|
||||
/**
|
||||
* An offline region defined by a style URL, geometry, zoom range, and
|
||||
* device pixel ratio.
|
||||
* <p>
|
||||
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
|
||||
* <p>
|
||||
* maxZoom may be ∞, in which case for each tile source, the region will include
|
||||
* tiles from minZoom up to the maximum zoom level provided by that source.
|
||||
* <p>
|
||||
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
|
||||
* <p>
|
||||
* if includeIdeographs is false, offline region will not include CJK glyphs
|
||||
*/
|
||||
public class OfflineGeometryRegionDefinition implements OfflineRegionDefinition {
|
||||
|
||||
@Keep
|
||||
private String styleURL;
|
||||
@Nullable
|
||||
@Keep
|
||||
private Geometry geometry;
|
||||
@Keep
|
||||
private double minZoom;
|
||||
@Keep
|
||||
private double maxZoom;
|
||||
@Keep
|
||||
private float pixelRatio;
|
||||
@Keep
|
||||
private boolean includeIdeographs;
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param geometry the geometry
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
*/
|
||||
@Keep
|
||||
public OfflineGeometryRegionDefinition(
|
||||
String styleURL, Geometry geometry, double minZoom, double maxZoom, float pixelRatio) {
|
||||
this(styleURL, geometry, minZoom, maxZoom, pixelRatio, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param geometry the geometry
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
* @param includeIdeographs include glyphs for CJK languages
|
||||
*/
|
||||
@Keep
|
||||
public OfflineGeometryRegionDefinition(
|
||||
String styleURL, Geometry geometry, double minZoom, double maxZoom, float pixelRatio,
|
||||
boolean includeIdeographs) {
|
||||
// Note: Also used in JNI
|
||||
this.styleURL = styleURL;
|
||||
this.geometry = geometry;
|
||||
this.minZoom = minZoom;
|
||||
this.maxZoom = maxZoom;
|
||||
this.pixelRatio = pixelRatio;
|
||||
this.includeIdeographs = includeIdeographs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from a Parcel.
|
||||
*
|
||||
* @param parcel the parcel to create the OfflineGeometryRegionDefinition from
|
||||
*/
|
||||
public OfflineGeometryRegionDefinition(Parcel parcel) {
|
||||
this.styleURL = parcel.readString();
|
||||
this.geometry = Feature.fromJson(parcel.readString()).geometry();
|
||||
this.minZoom = parcel.readDouble();
|
||||
this.maxZoom = parcel.readDouble();
|
||||
this.pixelRatio = parcel.readFloat();
|
||||
this.includeIdeographs = parcel.readByte() != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStyleURL() {
|
||||
return styleURL;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Geometry getGeometry() {
|
||||
return geometry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the bounding box for the Geometry it contains
|
||||
* to retain backwards compatibility
|
||||
*
|
||||
* @return the {@link LatLngBounds} or null
|
||||
*/
|
||||
@Nullable
|
||||
@Override
|
||||
public LatLngBounds getBounds() {
|
||||
if (geometry == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
double[] bbox = TurfMeasurement.bbox(geometry);
|
||||
return LatLngBounds.from(bbox[3], bbox[2], bbox[1], bbox[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getMinZoom() {
|
||||
return minZoom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getMaxZoom() {
|
||||
return maxZoom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getPixelRatio() {
|
||||
return pixelRatio;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getIncludeIdeographs() {
|
||||
return includeIdeographs;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String getType() {
|
||||
return "shaperegion";
|
||||
}
|
||||
|
||||
/*
|
||||
* Parceable
|
||||
*/
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(@NonNull Parcel dest, int flags) {
|
||||
dest.writeString(styleURL);
|
||||
dest.writeString(Feature.fromGeometry(geometry).toJson());
|
||||
dest.writeDouble(minZoom);
|
||||
dest.writeDouble(maxZoom);
|
||||
dest.writeFloat(pixelRatio);
|
||||
dest.writeByte((byte) (includeIdeographs ? 1 : 0));
|
||||
}
|
||||
|
||||
public static final Creator CREATOR = new Creator() {
|
||||
public OfflineGeometryRegionDefinition createFromParcel(@NonNull Parcel in) {
|
||||
return new OfflineGeometryRegionDefinition(in);
|
||||
}
|
||||
|
||||
public OfflineGeometryRegionDefinition[] newArray(int size) {
|
||||
return new OfflineGeometryRegionDefinition[size];
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import android.os.Parcel
|
||||
import android.os.Parcelable
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.geojson.Feature
|
||||
import com.mapbox.geojson.Geometry
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds.Companion.from
|
||||
import com.mapbox.turf.TurfMeasurement
|
||||
|
||||
/**
|
||||
* An offline region defined by a style URL, geometry, zoom range, and
|
||||
* device pixel ratio.
|
||||
*
|
||||
*
|
||||
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
|
||||
*
|
||||
*
|
||||
* maxZoom may be ∞, in which case for each tile source, the region will include
|
||||
* tiles from minZoom up to the maximum zoom level provided by that source.
|
||||
*
|
||||
*
|
||||
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
|
||||
*
|
||||
*
|
||||
* if includeIdeographs is false, offline region will not include CJK glyphs
|
||||
*/
|
||||
class OfflineGeometryRegionDefinition : OfflineRegionDefinition {
|
||||
@Keep
|
||||
override var styleURL: String?
|
||||
private set
|
||||
|
||||
@Keep
|
||||
var geometry: Geometry?
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var minZoom: Double
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var maxZoom: Double
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var pixelRatio: Float
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var includeIdeographs: Boolean
|
||||
private set
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param geometry the geometry
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
*/
|
||||
@Keep
|
||||
constructor(styleURL: String?, geometry: Geometry?, minZoom: Double, maxZoom: Double, pixelRatio: Float) : this(styleURL, geometry, minZoom, maxZoom, pixelRatio, false)
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param geometry the geometry
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
* @param includeIdeographs include glyphs for CJK languages
|
||||
*/
|
||||
@Keep
|
||||
constructor(styleURL: String?, geometry: Geometry?, minZoom: Double, maxZoom: Double, pixelRatio: Float, includeIdeographs: Boolean) {
|
||||
// Note: Also used in JNI
|
||||
this.styleURL = styleURL
|
||||
this.geometry = geometry
|
||||
this.minZoom = minZoom
|
||||
this.maxZoom = maxZoom
|
||||
this.pixelRatio = pixelRatio
|
||||
this.includeIdeographs = includeIdeographs
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineGeometryRegionDefinition from a Parcel.
|
||||
*
|
||||
* @param parcel the parcel to create the OfflineGeometryRegionDefinition from
|
||||
*/
|
||||
constructor(parcel: Parcel) {
|
||||
styleURL = parcel.readString()
|
||||
geometry = Feature.fromJson(parcel.readString()!!).geometry()
|
||||
minZoom = parcel.readDouble()
|
||||
maxZoom = parcel.readDouble()
|
||||
pixelRatio = parcel.readFloat()
|
||||
includeIdeographs = parcel.readByte().toInt() != 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the bounding box for the Geometry it contains
|
||||
* to retain backwards compatibility
|
||||
*
|
||||
* @return the [LatLngBounds] or null
|
||||
*/
|
||||
override val bounds: LatLngBounds?
|
||||
get() {
|
||||
if (geometry == null) {
|
||||
return null
|
||||
}
|
||||
val bbox = TurfMeasurement.bbox(geometry)
|
||||
return from(bbox[3], bbox[2], bbox[1], bbox[0])
|
||||
}
|
||||
|
||||
override val type: String
|
||||
get() = "shaperegion"
|
||||
|
||||
/*
|
||||
* Parceable
|
||||
*/
|
||||
override fun describeContents(): Int {
|
||||
return 0
|
||||
}
|
||||
|
||||
override fun writeToParcel(dest: Parcel, flags: Int) {
|
||||
dest.writeString(styleURL)
|
||||
dest.writeString(Feature.fromGeometry(geometry).toJson())
|
||||
dest.writeDouble(minZoom)
|
||||
dest.writeDouble(maxZoom)
|
||||
dest.writeFloat(pixelRatio)
|
||||
dest.writeByte((if (includeIdeographs) 1 else 0).toByte())
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmField
|
||||
val CREATOR: Parcelable.Creator<*> = object : Parcelable.Creator<Any?> {
|
||||
override fun createFromParcel(`in`: Parcel): OfflineGeometryRegionDefinition? {
|
||||
return OfflineGeometryRegionDefinition(`in`)
|
||||
}
|
||||
|
||||
override fun newArray(size: Int): Array<OfflineGeometryRegionDefinition?> {
|
||||
return arrayOfNulls(size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,743 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
import com.mapbox.mapboxsdk.LibraryLoader;
|
||||
import com.mapbox.mapboxsdk.R;
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
|
||||
import com.mapbox.mapboxsdk.net.ConnectivityReceiver;
|
||||
import com.mapbox.mapboxsdk.storage.FileSource;
|
||||
import com.mapbox.mapboxsdk.utils.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
|
||||
/**
|
||||
* The offline manager is the main entry point for offline-related functionality.
|
||||
* <p>
|
||||
* It'll help you list and create offline regions.
|
||||
* </p>
|
||||
*
|
||||
* @see <a href="https://docs.mapbox.com/help/troubleshooting/mobile-offline/">Offline Maps Information/</a>
|
||||
*/
|
||||
@UiThread
|
||||
public class OfflineManager {
|
||||
|
||||
private static final String TAG = "Mbgl - OfflineManager";
|
||||
|
||||
//
|
||||
// Static methods
|
||||
//
|
||||
|
||||
static {
|
||||
LibraryLoader.load();
|
||||
}
|
||||
|
||||
// Native peer pointer
|
||||
@Keep
|
||||
private long nativePtr;
|
||||
|
||||
// Reference to the file source to keep it alive for the
|
||||
// lifetime of this object
|
||||
private final FileSource fileSource;
|
||||
|
||||
// Makes sure callbacks come back to the main thread
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
// This object is implemented as a singleton
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private static OfflineManager instance;
|
||||
|
||||
// The application context
|
||||
private Context context;
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a list of all
|
||||
* OfflineRegion in the database or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface ListOfflineRegionsCallback {
|
||||
/**
|
||||
* Receives the list of offline regions.
|
||||
*
|
||||
* @param offlineRegions the offline region array
|
||||
*/
|
||||
void onList(OfflineRegion[] offlineRegions);
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the newly created
|
||||
* OfflineRegion in the database or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface CreateOfflineRegionCallback {
|
||||
/**
|
||||
* Receives the newly created offline region.
|
||||
*
|
||||
* @param offlineRegion the offline region to create
|
||||
*/
|
||||
void onCreate(OfflineRegion offlineRegion);
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message to be shown
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a list of all
|
||||
* OfflineRegion added to the database during the merge.
|
||||
*/
|
||||
@Keep
|
||||
public interface MergeOfflineRegionsCallback {
|
||||
/**
|
||||
* Receives the list of merged offline regions.
|
||||
*
|
||||
* @param offlineRegions the offline region array
|
||||
*/
|
||||
void onMerge(OfflineRegion[] offlineRegions);
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/*
|
||||
* Constructor
|
||||
*/
|
||||
private OfflineManager(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.fileSource = FileSource.getInstance(this.context);
|
||||
initialize(fileSource);
|
||||
|
||||
// Delete any existing previous ambient cache database
|
||||
deleteAmbientDatabase(this.context);
|
||||
}
|
||||
|
||||
private void deleteAmbientDatabase(final Context context) {
|
||||
final String path = FileSource.getInternalCachePath(context) + File.separator + "mbgl-cache.db";
|
||||
FileUtils.deleteFile(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the single instance of offline manager.
|
||||
*
|
||||
* @param context the context used to host the offline manager
|
||||
* @return the single instance of offline manager
|
||||
*/
|
||||
public static synchronized OfflineManager getInstance(@NonNull Context context) {
|
||||
if (instance == null) {
|
||||
instance = new OfflineManager(context);
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all regions in the offline database.
|
||||
* <p>
|
||||
* The query will be executed asynchronously and the results passed to the given
|
||||
* callback on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
public void listOfflineRegions(@NonNull final ListOfflineRegionsCallback callback) {
|
||||
fileSource.activate();
|
||||
listOfflineRegions(fileSource, new ListOfflineRegionsCallback() {
|
||||
|
||||
@Override
|
||||
public void onList(final OfflineRegion[] offlineRegions) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onList(offlineRegions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge offline regions from a secondary database into the main offline database.
|
||||
* <p>
|
||||
* When the merge is completed, or fails, the {@link MergeOfflineRegionsCallback} will be invoked on the main thread.
|
||||
* The callback reference is <b>strongly kept</b> throughout the process,
|
||||
* so it needs to be wrapped in a weak reference or released on the client side if necessary.
|
||||
* <p>
|
||||
* The secondary database may need to be upgraded to the latest schema.
|
||||
* This is done in-place and requires write-access to the provided path.
|
||||
* If the app's process doesn't have write-access to the provided path,
|
||||
* the file will be copied to the temporary, internal directory for the duration of the merge.
|
||||
* <p>
|
||||
* Only resources and tiles that belong to a region will be copied over. Identical
|
||||
* regions will be flattened into a single new region in the main database.
|
||||
* <p>
|
||||
* The operation will be aborted and {@link MergeOfflineRegionsCallback#onError(String)} with an appropriate message
|
||||
* will be invoked if the merge would result in the offline tile count limit being exceeded.
|
||||
* <p>
|
||||
* Merged regions may not be in a completed status if the secondary database
|
||||
* does not contain all the tiles or resources required by the region definition.
|
||||
*
|
||||
* @param path secondary database writable path
|
||||
* @param callback completion/error callback
|
||||
*/
|
||||
public void mergeOfflineRegions(@NonNull String path, @NonNull final MergeOfflineRegionsCallback callback) {
|
||||
final File src = new File(path);
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String errorMessage = null;
|
||||
if (src.canWrite()) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// path writable, merge and update schema in place if necessary
|
||||
mergeOfflineDatabaseFiles(src, callback, false);
|
||||
}
|
||||
});
|
||||
} else if (src.canRead()) {
|
||||
// path not writable, copy the the file to temp directory
|
||||
final File dst = new File(FileSource.getInternalCachePath(context), src.getName());
|
||||
try {
|
||||
copyTempDatabaseFile(src, dst);
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// merge and update schema using the copy
|
||||
OfflineManager.this.mergeOfflineDatabaseFiles(dst, callback, true);
|
||||
}
|
||||
});
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
errorMessage = ex.getMessage();
|
||||
}
|
||||
} else {
|
||||
// path not readable, abort
|
||||
errorMessage = "Secondary database needs to be located in a readable path.";
|
||||
}
|
||||
|
||||
if (errorMessage != null) {
|
||||
final String finalErrorMessage = errorMessage;
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
callback.onError(finalErrorMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete existing database and re-initialize.
|
||||
* <p>
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the database thread; it is the responsibility of the SDK bindings
|
||||
* to re-execute a user-provided callback on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked when the database was reset or when the operation erred.
|
||||
*/
|
||||
public void resetDatabase(@Nullable final FileSourceCallback callback) {
|
||||
fileSource.activate();
|
||||
nativeResetDatabase(new FileSourceCallback() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onSuccess();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the existing database file into a minimal amount of disk space.
|
||||
* <p>
|
||||
* This operation has a performance impact as it will vacuum the database,
|
||||
* forcing it to move pages on the filesystem.
|
||||
* </p>
|
||||
* <p>
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the database thread; it is the responsibility of the SDK bindings
|
||||
* to re-execute a user-provided callback on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked when the database was reset or when the operation erred.
|
||||
*/
|
||||
public void packDatabase(@Nullable final FileSourceCallback callback) {
|
||||
fileSource.activate();
|
||||
nativePackDatabase(new FileSourceCallback() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onSuccess();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces re-validation of the ambient cache.
|
||||
* <p>
|
||||
* Forces Mapbox GL Native to revalidate resources stored in the ambient
|
||||
* cache with the tile server before using them, making sure they
|
||||
* are the latest version. This is more efficient than cleaning the
|
||||
* cache because if the resource is considered valid after the server
|
||||
* lookup, it will not get downloaded again.
|
||||
* <p>
|
||||
* Resources overlapping with offline regions will not be affected
|
||||
* by this call.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked when the ambient cache was invalidated or when the operation erred.
|
||||
*/
|
||||
public void invalidateAmbientCache(@Nullable final FileSourceCallback callback) {
|
||||
fileSource.activate();
|
||||
nativeInvalidateAmbientCache(new FileSourceCallback() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onSuccess();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Erase resources from the ambient cache, freeing storage space.
|
||||
* <p>
|
||||
* Erases the ambient cache, freeing resources.
|
||||
* Note that this operation can be potentially slow if packing the database
|
||||
* occurs automatically ({@link OfflineManager#runPackDatabaseAutomatically(boolean)}).
|
||||
* </p>
|
||||
* <p>
|
||||
* Resources overlapping with offline regions will not be affected
|
||||
* by this call.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked when the ambient cache was cleared or when the operation erred.
|
||||
*/
|
||||
public void clearAmbientCache(@Nullable final FileSourceCallback callback) {
|
||||
fileSource.activate();
|
||||
nativeClearAmbientCache(new FileSourceCallback() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onSuccess();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum size in bytes for the ambient cache.
|
||||
* <p>
|
||||
* This call is potentially expensive because it will try
|
||||
* to trim the data in case the database is larger than the
|
||||
* size defined. The size of offline regions are not affected
|
||||
* by this settings, but the ambient cache will always try
|
||||
* to not exceed the maximum size defined, taking into account
|
||||
* the current size for the offline regions.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note that if you use the SDK's offline functionality, your ability to set the ambient cache size will be limited.
|
||||
* Space that offline regions take up detract from the space available for ambient caching, and the ambient cache
|
||||
* size does not block offline downloads. For example: if the maximum cache size is set to 50 MB and 40 MB are
|
||||
* already used by offline regions, the ambient cache size will effectively be 10 MB.
|
||||
* </p>
|
||||
* <p>
|
||||
* Setting the size to 0 will disable the cache if there is no
|
||||
* offline region on the database.
|
||||
* </p>
|
||||
* <[
|
||||
* <p>
|
||||
* This method should always be called at the start of an app, before setting the style and loading a map.
|
||||
* Otherwise, the map will instantiate with the default cache size of 50 MB.
|
||||
* </p>
|
||||
*
|
||||
* @param size the maximum size of the ambient cache
|
||||
* @param callback the callback to be invoked when the the maximum size has been set or when the operation erred.
|
||||
*/
|
||||
public void setMaximumAmbientCacheSize(long size, @Nullable final FileSourceCallback callback) {
|
||||
fileSource.activate();
|
||||
nativeSetMaximumAmbientCacheSize(size, new FileSourceCallback() {
|
||||
@Override
|
||||
public void onSuccess() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onSuccess();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
fileSource.activate();
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response indicating if an operation has succeeded or failed.
|
||||
*/
|
||||
@Keep
|
||||
public interface FileSourceCallback {
|
||||
|
||||
/**
|
||||
* Receives the success of an operation
|
||||
*/
|
||||
void onSuccess();
|
||||
|
||||
/**
|
||||
* Receives an error message if an operation was not successful
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
void onError(@NonNull String message);
|
||||
|
||||
}
|
||||
|
||||
private static void copyTempDatabaseFile(@NonNull File sourceFile, File destFile) throws IOException {
|
||||
if (!destFile.exists() && !destFile.createNewFile()) {
|
||||
throw new IOException("Unable to copy database file for merge.");
|
||||
}
|
||||
|
||||
FileChannel source = null;
|
||||
FileChannel destination = null;
|
||||
|
||||
try {
|
||||
source = new FileInputStream(sourceFile).getChannel();
|
||||
destination = new FileOutputStream(destFile).getChannel();
|
||||
destination.transferFrom(source, 0, source.size());
|
||||
} catch (IOException ex) {
|
||||
throw new IOException(String.format("Unable to copy database file for merge. %s", ex.getMessage()));
|
||||
} finally {
|
||||
if (source != null) {
|
||||
source.close();
|
||||
}
|
||||
if (destination != null) {
|
||||
destination.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void mergeOfflineDatabaseFiles(@NonNull final File file, @NonNull final MergeOfflineRegionsCallback callback,
|
||||
final boolean isTemporaryFile) {
|
||||
fileSource.activate();
|
||||
mergeOfflineRegions(fileSource, file.getAbsolutePath(), new MergeOfflineRegionsCallback() {
|
||||
@Override
|
||||
public void onMerge(final OfflineRegion[] offlineRegions) {
|
||||
if (isTemporaryFile) {
|
||||
file.delete();
|
||||
}
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onMerge(offlineRegions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
if (isTemporaryFile) {
|
||||
file.delete();
|
||||
}
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an offline region in the database by downloading the resources needed to use
|
||||
* the given region offline.
|
||||
* <p>
|
||||
* As of version 8.3.0 of the Maps SDK for Android, offline tile requests are no longer exempt from
|
||||
* billing on mobile. Developers are subject to separate Vector Tile or Raster Tile API pricing for
|
||||
* offline use. See <a href="https://www.mapbox.com/pricing/">our pricing page</a> for more information.
|
||||
* </p>
|
||||
* <p>
|
||||
* When the initial database queries have completed, the provided callback will be
|
||||
* executed on the main thread.
|
||||
* </p>
|
||||
* <p>
|
||||
* Note that the resulting region will be in an inactive download state; to begin
|
||||
* downloading resources, call `OfflineRegion.setDownloadState(DownloadState.STATE_ACTIVE)`,
|
||||
* optionally registering an `OfflineRegionObserver` beforehand.
|
||||
* </p>
|
||||
*
|
||||
* @param definition the offline region definition
|
||||
* @param metadata the metadata in bytes
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
public void createOfflineRegion(@NonNull OfflineRegionDefinition definition, @NonNull byte[] metadata,
|
||||
@NonNull final CreateOfflineRegionCallback callback) {
|
||||
if (!isValidOfflineRegionDefinition(definition)) {
|
||||
callback.onError(
|
||||
String.format(context.getString(R.string.maplibre_offline_error_region_definition_invalid),
|
||||
definition.getBounds())
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
ConnectivityReceiver.instance(context).activate();
|
||||
FileSource.getInstance(context).activate();
|
||||
createOfflineRegion(fileSource, definition, metadata, new CreateOfflineRegionCallback() {
|
||||
|
||||
@Override
|
||||
public void onCreate(final OfflineRegion offlineRegion) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ConnectivityReceiver.instance(context).deactivate();
|
||||
FileSource.getInstance(context).deactivate();
|
||||
callback.onCreate(offlineRegion);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ConnectivityReceiver.instance(context).deactivate();
|
||||
FileSource.getInstance(context).deactivate();
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if the offline region definition bounds is valid for an offline region download.
|
||||
*
|
||||
* @param definition the offline region definition
|
||||
* @return true if the region fits the world bounds.
|
||||
*/
|
||||
private boolean isValidOfflineRegionDefinition(OfflineRegionDefinition definition) {
|
||||
return LatLngBounds.world().contains(definition.getBounds());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum number of Mapbox-hosted tiles that may be downloaded and stored on the current device.
|
||||
* By default, the limit is set to 6,000.
|
||||
* <p>
|
||||
* Once this limit is reached, {@link OfflineRegion.OfflineRegionObserver#mapboxTileCountLimitExceeded(long)}
|
||||
* fires every additional attempt to download additional tiles until already downloaded tiles are removed
|
||||
* by calling {@link OfflineRegion#delete(OfflineRegion.OfflineRegionDeleteCallback)}.
|
||||
* </p>
|
||||
*
|
||||
* @param limit the maximum number of tiles allowed to be downloaded
|
||||
*/
|
||||
@Keep
|
||||
public native void setOfflineMapboxTileCountLimit(long limit);
|
||||
|
||||
|
||||
/**
|
||||
* Sets whether database file packing occurs automatically.
|
||||
* By default, the automatic database file packing is enabled.
|
||||
* <p>
|
||||
* If packing is enabled, database file packing occurs automatically
|
||||
* after an offline region is deleted by calling
|
||||
* {@link OfflineRegion#delete(OfflineRegion.OfflineRegionDeleteCallback)}
|
||||
* or the ambient cache is cleared by calling {@link OfflineManager#clearAmbientCache()}.
|
||||
*
|
||||
* If packing is disabled, disk space will not be freed after
|
||||
* resources are removed unless {@link OfflineManager#packDatabase()} is explicitly called.
|
||||
* </p>
|
||||
*
|
||||
* @param autopack flag setting the automatic database file packing.
|
||||
*/
|
||||
@Keep
|
||||
public native void runPackDatabaseAutomatically(boolean autopack);
|
||||
|
||||
@Keep
|
||||
private native void initialize(FileSource fileSource);
|
||||
|
||||
@Override
|
||||
@Keep
|
||||
protected native void finalize() throws Throwable;
|
||||
|
||||
@Keep
|
||||
private native void listOfflineRegions(FileSource fileSource, ListOfflineRegionsCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void createOfflineRegion(FileSource fileSource, OfflineRegionDefinition definition,
|
||||
byte[] metadata, CreateOfflineRegionCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void mergeOfflineRegions(FileSource fileSource, String path, MergeOfflineRegionsCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void nativeResetDatabase(@Nullable FileSourceCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void nativePackDatabase(@Nullable FileSourceCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void nativeInvalidateAmbientCache(@Nullable FileSourceCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void nativeClearAmbientCache(@Nullable FileSourceCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void nativeSetMaximumAmbientCacheSize(long size, @Nullable FileSourceCallback callback);
|
||||
|
||||
/**
|
||||
* Insert the provided resource into the ambient cache
|
||||
* This method mimics the caching that would take place if the equivalent
|
||||
* resource were requested in the process of map rendering.
|
||||
* Use this method to pre-warm the cache with resources you know
|
||||
* will be requested.
|
||||
* <p>
|
||||
* This call is asynchronous: the data may not be immediately available
|
||||
* for in-progress requests, although subsequent requests should have
|
||||
* access to the cached data.
|
||||
*
|
||||
* @param url The URL of the resource to insert
|
||||
* @param data Response data to store for this resource. Data is expected to be uncompressed;
|
||||
* internally, the cache will compress data as necessary.
|
||||
* @param modified Optional "modified" response header, in seconds since 1970, or 0 if not set
|
||||
* @param expires Optional "expires" response header, in seconds since 1970, or 0 if not set
|
||||
* @param etag Optional "entity tag" response header
|
||||
* @param mustRevalidate Indicates whether response can be used after it's stale
|
||||
*/
|
||||
@Keep
|
||||
public native void putResourceWithUrl(String url, byte[] data, long modified, long expires,
|
||||
String etag, boolean mustRevalidate);
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.annotation.Keep
|
||||
import androidx.annotation.UiThread
|
||||
import com.mapbox.mapboxsdk.LibraryLoader
|
||||
import com.mapbox.mapboxsdk.R
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds.Companion.world
|
||||
import com.mapbox.mapboxsdk.net.ConnectivityReceiver
|
||||
import com.mapbox.mapboxsdk.storage.FileSource
|
||||
import com.mapbox.mapboxsdk.utils.FileUtils
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.nio.channels.FileChannel
|
||||
|
||||
/**
|
||||
* The offline manager is the main entry point for offline-related functionality.
|
||||
*
|
||||
*
|
||||
* It'll help you list and create offline regions.
|
||||
*
|
||||
*
|
||||
* @see [Offline Maps Information/](https://docs.mapbox.com/help/troubleshooting/mobile-offline/)
|
||||
*/
|
||||
@UiThread
|
||||
class OfflineManager private constructor(context: Context) {
|
||||
// Native peer pointer
|
||||
@Keep
|
||||
private val nativePtr: Long = 0
|
||||
|
||||
// Reference to the file source to keep it alive for the
|
||||
// lifetime of this object
|
||||
private val fileSource: FileSource
|
||||
|
||||
// Makes sure callbacks come back to the main thread
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
// The application context
|
||||
private val context: Context
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a list of all
|
||||
* OfflineRegion in the database or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface ListOfflineRegionsCallback {
|
||||
/**
|
||||
* Receives the list of offline regions.
|
||||
*
|
||||
* @param offlineRegions the offline region array
|
||||
*/
|
||||
fun onList(offlineRegions: Array<OfflineRegion>?)
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the newly created
|
||||
* OfflineRegion in the database or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface CreateOfflineRegionCallback {
|
||||
/**
|
||||
* Receives the newly created offline region.
|
||||
*
|
||||
* @param offlineRegion the offline region to create
|
||||
*/
|
||||
fun onCreate(offlineRegion: OfflineRegion)
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message to be shown
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a list of all
|
||||
* OfflineRegion added to the database during the merge.
|
||||
*/
|
||||
@Keep
|
||||
interface MergeOfflineRegionsCallback {
|
||||
/**
|
||||
* Receives the list of merged offline regions.
|
||||
*
|
||||
* @param offlineRegions the offline region array
|
||||
*/
|
||||
fun onMerge(offlineRegions: Array<OfflineRegion>?)
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/*
|
||||
* Constructor
|
||||
*/
|
||||
init {
|
||||
this.context = context.applicationContext
|
||||
fileSource = FileSource.getInstance(this.context)
|
||||
initialize(fileSource)
|
||||
|
||||
// Delete any existing previous ambient cache database
|
||||
deleteAmbientDatabase(this.context)
|
||||
}
|
||||
|
||||
private fun deleteAmbientDatabase(context: Context) {
|
||||
val path = FileSource.getInternalCachePath(context) + File.separator + "mbgl-cache.db"
|
||||
FileUtils.deleteFile(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all regions in the offline database.
|
||||
*
|
||||
*
|
||||
* The query will be executed asynchronously and the results passed to the given
|
||||
* callback on the main thread.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
fun listOfflineRegions(callback: ListOfflineRegionsCallback) {
|
||||
fileSource.activate()
|
||||
listOfflineRegions(
|
||||
fileSource,
|
||||
object : ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onList(offlineRegions)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge offline regions from a secondary database into the main offline database.
|
||||
*
|
||||
*
|
||||
* When the merge is completed, or fails, the [MergeOfflineRegionsCallback] will be invoked on the main thread.
|
||||
* The callback reference is **strongly kept** throughout the process,
|
||||
* so it needs to be wrapped in a weak reference or released on the client side if necessary.
|
||||
*
|
||||
*
|
||||
* The secondary database may need to be upgraded to the latest schema.
|
||||
* This is done in-place and requires write-access to the provided path.
|
||||
* If the app's process doesn't have write-access to the provided path,
|
||||
* the file will be copied to the temporary, internal directory for the duration of the merge.
|
||||
*
|
||||
*
|
||||
* Only resources and tiles that belong to a region will be copied over. Identical
|
||||
* regions will be flattened into a single new region in the main database.
|
||||
*
|
||||
*
|
||||
* The operation will be aborted and [MergeOfflineRegionsCallback.onError] with an appropriate message
|
||||
* will be invoked if the merge would result in the offline tile count limit being exceeded.
|
||||
*
|
||||
*
|
||||
* Merged regions may not be in a completed status if the secondary database
|
||||
* does not contain all the tiles or resources required by the region definition.
|
||||
*
|
||||
* @param path secondary database writable path
|
||||
* @param callback completion/error callback
|
||||
*/
|
||||
fun mergeOfflineRegions(path: String, callback: MergeOfflineRegionsCallback) {
|
||||
val src = File(path)
|
||||
Thread {
|
||||
var errorMessage: String? = null
|
||||
if (src.canWrite()) {
|
||||
handler.post { // path writable, merge and update schema in place if necessary
|
||||
mergeOfflineDatabaseFiles(src, callback, false)
|
||||
}
|
||||
} else if (src.canRead()) {
|
||||
// path not writable, copy the the file to temp directory
|
||||
val dst = File(FileSource.getInternalCachePath(context), src.name)
|
||||
try {
|
||||
copyTempDatabaseFile(src, dst)
|
||||
handler.post { // merge and update schema using the copy
|
||||
mergeOfflineDatabaseFiles(dst, callback, true)
|
||||
}
|
||||
} catch (ex: IOException) {
|
||||
ex.printStackTrace()
|
||||
errorMessage = ex.message
|
||||
}
|
||||
} else {
|
||||
// path not readable, abort
|
||||
errorMessage = "Secondary database needs to be located in a readable path."
|
||||
}
|
||||
if (errorMessage != null) {
|
||||
val finalErrorMessage: String = errorMessage
|
||||
handler.post { callback.onError(finalErrorMessage) }
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete existing database and re-initialize.
|
||||
*
|
||||
*
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the database thread; it is the responsibility of the SDK bindings
|
||||
* to re-execute a user-provided callback on the main thread.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked when the database was reset or when the operation erred.
|
||||
*/
|
||||
fun resetDatabase(callback: FileSourceCallback?) {
|
||||
fileSource.activate()
|
||||
nativeResetDatabase(object : FileSourceCallback {
|
||||
override fun onSuccess() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the existing database file into a minimal amount of disk space.
|
||||
*
|
||||
*
|
||||
* This operation has a performance impact as it will vacuum the database,
|
||||
* forcing it to move pages on the filesystem.
|
||||
*
|
||||
*
|
||||
*
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the database thread; it is the responsibility of the SDK bindings
|
||||
* to re-execute a user-provided callback on the main thread.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked when the database was reset or when the operation erred.
|
||||
*/
|
||||
fun packDatabase(callback: FileSourceCallback?) {
|
||||
fileSource.activate()
|
||||
nativePackDatabase(object : FileSourceCallback {
|
||||
override fun onSuccess() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces re-validation of the ambient cache.
|
||||
*
|
||||
*
|
||||
* Forces Mapbox GL Native to revalidate resources stored in the ambient
|
||||
* cache with the tile server before using them, making sure they
|
||||
* are the latest version. This is more efficient than cleaning the
|
||||
* cache because if the resource is considered valid after the server
|
||||
* lookup, it will not get downloaded again.
|
||||
*
|
||||
*
|
||||
* Resources overlapping with offline regions will not be affected
|
||||
* by this call.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked when the ambient cache was invalidated or when the operation erred.
|
||||
*/
|
||||
fun invalidateAmbientCache(callback: FileSourceCallback?) {
|
||||
fileSource.activate()
|
||||
nativeInvalidateAmbientCache(object : FileSourceCallback {
|
||||
override fun onSuccess() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Erase resources from the ambient cache, freeing storage space.
|
||||
*
|
||||
*
|
||||
* Erases the ambient cache, freeing resources.
|
||||
* Note that this operation can be potentially slow if packing the database
|
||||
* occurs automatically ([OfflineManager.runPackDatabaseAutomatically]).
|
||||
*
|
||||
*
|
||||
*
|
||||
* Resources overlapping with offline regions will not be affected
|
||||
* by this call.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked when the ambient cache was cleared or when the operation erred.
|
||||
*/
|
||||
fun clearAmbientCache(callback: FileSourceCallback?) {
|
||||
fileSource.activate()
|
||||
nativeClearAmbientCache(object : FileSourceCallback {
|
||||
override fun onSuccess() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum size in bytes for the ambient cache.
|
||||
*
|
||||
*
|
||||
* This call is potentially expensive because it will try
|
||||
* to trim the data in case the database is larger than the
|
||||
* size defined. The size of offline regions are not affected
|
||||
* by this settings, but the ambient cache will always try
|
||||
* to not exceed the maximum size defined, taking into account
|
||||
* the current size for the offline regions.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Note that if you use the SDK's offline functionality, your ability to set the ambient cache size will be limited.
|
||||
* Space that offline regions take up detract from the space available for ambient caching, and the ambient cache
|
||||
* size does not block offline downloads. For example: if the maximum cache size is set to 50 MB and 40 MB are
|
||||
* already used by offline regions, the ambient cache size will effectively be 10 MB.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Setting the size to 0 will disable the cache if there is no
|
||||
* offline region on the database.
|
||||
*
|
||||
* <[
|
||||
*
|
||||
*
|
||||
* This method should always be called at the start of an app, before setting the style and loading a map.
|
||||
* Otherwise, the map will instantiate with the default cache size of 50 MB.
|
||||
*
|
||||
*
|
||||
* @param size the maximum size of the ambient cache
|
||||
* @param callback the callback to be invoked when the the maximum size has been set or when the operation erred.
|
||||
*/
|
||||
fun setMaximumAmbientCacheSize(size: Long, callback: FileSourceCallback?) {
|
||||
fileSource.activate()
|
||||
nativeSetMaximumAmbientCacheSize(
|
||||
size,
|
||||
object : FileSourceCallback {
|
||||
override fun onSuccess() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
fileSource.activate()
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response indicating if an operation has succeeded or failed.
|
||||
*/
|
||||
@Keep
|
||||
interface FileSourceCallback {
|
||||
/**
|
||||
* Receives the success of an operation
|
||||
*/
|
||||
fun onSuccess()
|
||||
|
||||
/**
|
||||
* Receives an error message if an operation was not successful
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
fun onError(message: String)
|
||||
}
|
||||
|
||||
private fun mergeOfflineDatabaseFiles(file: File, callback: MergeOfflineRegionsCallback, isTemporaryFile: Boolean) {
|
||||
fileSource.activate()
|
||||
mergeOfflineRegions(
|
||||
fileSource,
|
||||
file.absolutePath,
|
||||
object : MergeOfflineRegionsCallback {
|
||||
override fun onMerge(offlineRegions: Array<OfflineRegion>?) {
|
||||
if (isTemporaryFile) {
|
||||
file.delete()
|
||||
}
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onMerge(offlineRegions)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String) {
|
||||
if (isTemporaryFile) {
|
||||
file.delete()
|
||||
}
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an offline region in the database by downloading the resources needed to use
|
||||
* the given region offline.
|
||||
*
|
||||
*
|
||||
* As of version 8.3.0 of the Maps SDK for Android, offline tile requests are no longer exempt from
|
||||
* billing on mobile. Developers are subject to separate Vector Tile or Raster Tile API pricing for
|
||||
* offline use. See [our pricing page](https://www.mapbox.com/pricing/) for more information.
|
||||
*
|
||||
*
|
||||
*
|
||||
* When the initial database queries have completed, the provided callback will be
|
||||
* executed on the main thread.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Note that the resulting region will be in an inactive download state; to begin
|
||||
* downloading resources, call `OfflineRegion.setDownloadState(DownloadState.STATE_ACTIVE)`,
|
||||
* optionally registering an `OfflineRegionObserver` beforehand.
|
||||
*
|
||||
*
|
||||
* @param definition the offline region definition
|
||||
* @param metadata the metadata in bytes
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
fun createOfflineRegion(definition: OfflineRegionDefinition, metadata: ByteArray, callback: CreateOfflineRegionCallback) {
|
||||
if (!isValidOfflineRegionDefinition(definition)) {
|
||||
callback.onError(String.format(context.getString(R.string.maplibre_offline_error_region_definition_invalid), definition.bounds))
|
||||
return
|
||||
}
|
||||
ConnectivityReceiver.instance(context).activate()
|
||||
FileSource.getInstance(context).activate()
|
||||
createOfflineRegion(
|
||||
fileSource,
|
||||
definition,
|
||||
metadata,
|
||||
object : CreateOfflineRegionCallback {
|
||||
override fun onCreate(offlineRegion: OfflineRegion) {
|
||||
handler.post {
|
||||
ConnectivityReceiver.instance(context).deactivate()
|
||||
FileSource.getInstance(context).deactivate()
|
||||
callback.onCreate(offlineRegion)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String) {
|
||||
handler.post {
|
||||
ConnectivityReceiver.instance(context).deactivate()
|
||||
FileSource.getInstance(context).deactivate()
|
||||
callback.onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if the offline region definition bounds is valid for an offline region download.
|
||||
*
|
||||
* @param definition the offline region definition
|
||||
* @return true if the region fits the world bounds.
|
||||
*/
|
||||
private fun isValidOfflineRegionDefinition(definition: OfflineRegionDefinition): Boolean {
|
||||
return world().contains(definition.bounds!!)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the maximum number of Mapbox-hosted tiles that may be downloaded and stored on the current device.
|
||||
* By default, the limit is set to 6,000.
|
||||
*
|
||||
*
|
||||
* Once this limit is reached, [OfflineRegion.OfflineRegionObserver.mapboxTileCountLimitExceeded]
|
||||
* fires every additional attempt to download additional tiles until already downloaded tiles are removed
|
||||
* by calling [OfflineRegion.delete].
|
||||
*
|
||||
*
|
||||
* @param limit the maximum number of tiles allowed to be downloaded
|
||||
*/
|
||||
@Keep
|
||||
external fun setOfflineMapboxTileCountLimit(limit: Long)
|
||||
|
||||
/**
|
||||
* Sets whether database file packing occurs automatically.
|
||||
* By default, the automatic database file packing is enabled.
|
||||
*
|
||||
*
|
||||
* If packing is enabled, database file packing occurs automatically
|
||||
* after an offline region is deleted by calling
|
||||
* [OfflineRegion.delete]
|
||||
* or the ambient cache is cleared by calling [OfflineManager.clearAmbientCache].
|
||||
*
|
||||
* If packing is disabled, disk space will not be freed after
|
||||
* resources are removed unless [OfflineManager.packDatabase] is explicitly called.
|
||||
*
|
||||
*
|
||||
* @param autopack flag setting the automatic database file packing.
|
||||
*/
|
||||
|
||||
@Keep
|
||||
external fun runPackDatabaseAutomatically(autopack: Boolean)
|
||||
|
||||
@Keep
|
||||
private external fun initialize(fileSource: FileSource)
|
||||
|
||||
@Keep
|
||||
@Throws(Throwable::class)
|
||||
protected external fun finalize()
|
||||
|
||||
@Keep
|
||||
private external fun listOfflineRegions(fileSource: FileSource, callback: ListOfflineRegionsCallback)
|
||||
|
||||
@Keep
|
||||
private external fun createOfflineRegion(fileSource: FileSource, definition: OfflineRegionDefinition, metadata: ByteArray, callback: CreateOfflineRegionCallback)
|
||||
|
||||
@Keep
|
||||
private external fun mergeOfflineRegions(fileSource: FileSource, path: String, callback: MergeOfflineRegionsCallback)
|
||||
|
||||
@Keep
|
||||
private external fun nativeResetDatabase(callback: FileSourceCallback?)
|
||||
|
||||
@Keep
|
||||
private external fun nativePackDatabase(callback: FileSourceCallback?)
|
||||
|
||||
@Keep
|
||||
private external fun nativeInvalidateAmbientCache(callback: FileSourceCallback?)
|
||||
|
||||
@Keep
|
||||
private external fun nativeClearAmbientCache(callback: FileSourceCallback?)
|
||||
|
||||
@Keep
|
||||
private external fun nativeSetMaximumAmbientCacheSize(size: Long, callback: FileSourceCallback?)
|
||||
|
||||
/**
|
||||
* Insert the provided resource into the ambient cache
|
||||
* This method mimics the caching that would take place if the equivalent
|
||||
* resource were requested in the process of map rendering.
|
||||
* Use this method to pre-warm the cache with resources you know
|
||||
* will be requested.
|
||||
*
|
||||
*
|
||||
* This call is asynchronous: the data may not be immediately available
|
||||
* for in-progress requests, although subsequent requests should have
|
||||
* access to the cached data.
|
||||
*
|
||||
* @param url The URL of the resource to insert
|
||||
* @param data Response data to store for this resource. Data is expected to be uncompressed;
|
||||
* internally, the cache will compress data as necessary.
|
||||
* @param modified Optional "modified" response header, in seconds since 1970, or 0 if not set
|
||||
* @param expires Optional "expires" response header, in seconds since 1970, or 0 if not set
|
||||
* @param etag Optional "entity tag" response header
|
||||
* @param mustRevalidate Indicates whether response can be used after it's stale
|
||||
*/
|
||||
@Keep
|
||||
external fun putResourceWithUrl(url: String?, data: ByteArray?, modified: Long, expires: Long, etag: String?, mustRevalidate: Boolean)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "Mbgl - OfflineManager"
|
||||
|
||||
//
|
||||
// Static methods
|
||||
//
|
||||
init {
|
||||
LibraryLoader.load()
|
||||
}
|
||||
|
||||
// This object is implemented as a singleton
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
private var instance: OfflineManager? = null
|
||||
|
||||
/**
|
||||
* Get the single instance of offline manager.
|
||||
*
|
||||
* @param context the context used to host the offline manager
|
||||
* @return the single instance of offline manager
|
||||
*/
|
||||
@Synchronized
|
||||
fun getInstance(context: Context): OfflineManager {
|
||||
if (instance == null) {
|
||||
instance = OfflineManager(context)
|
||||
}
|
||||
return instance!!
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun copyTempDatabaseFile(sourceFile: File, destFile: File) {
|
||||
if (!destFile.exists() && !destFile.createNewFile()) {
|
||||
throw IOException("Unable to copy database file for merge.")
|
||||
}
|
||||
var source: FileChannel? = null
|
||||
var destination: FileChannel? = null
|
||||
try {
|
||||
source = FileInputStream(sourceFile).channel
|
||||
destination = FileOutputStream(destFile).channel
|
||||
destination.transferFrom(source, 0, source.size())
|
||||
} catch (ex: IOException) {
|
||||
throw IOException(String.format("Unable to copy database file for merge. %s", ex.message))
|
||||
} finally {
|
||||
source?.close()
|
||||
destination?.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,536 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import androidx.annotation.IntDef;
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import com.mapbox.mapboxsdk.LibraryLoader;
|
||||
import com.mapbox.mapboxsdk.Mapbox;
|
||||
import com.mapbox.mapboxsdk.net.ConnectivityReceiver;
|
||||
import com.mapbox.mapboxsdk.storage.FileSource;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* An offline region is the basic building block for offline mobile maps.
|
||||
* Use {@link com.mapbox.mapboxsdk.offline.OfflineManager.CreateOfflineRegionCallback}
|
||||
* to create a new offline region.
|
||||
*/
|
||||
public class OfflineRegion {
|
||||
|
||||
//
|
||||
// Static methods
|
||||
//
|
||||
|
||||
static {
|
||||
LibraryLoader.load();
|
||||
}
|
||||
|
||||
// Members
|
||||
|
||||
// Application context
|
||||
private final Context context;
|
||||
|
||||
// Holds the pointer to JNI OfflineRegion
|
||||
@Keep
|
||||
private long nativePtr;
|
||||
|
||||
// Holds a reference to the FileSource to keep it alive
|
||||
private FileSource fileSource;
|
||||
|
||||
//Region id
|
||||
private long id;
|
||||
|
||||
// delete status
|
||||
private boolean isDeleted;
|
||||
|
||||
private OfflineRegionDefinition definition;
|
||||
|
||||
/**
|
||||
* Arbitrary binary region metadata. The contents are opaque to the SDK implementation;
|
||||
* it just stores and retrieves a byte[]. Check the `OfflineActivity` in the TestApp
|
||||
* for a sample implementation that uses JSON to store an offline region name.
|
||||
*/
|
||||
private byte[] metadata;
|
||||
|
||||
// Makes sure callbacks come back to the main thread
|
||||
private final Handler handler = new Handler(Looper.getMainLooper());
|
||||
|
||||
/**
|
||||
* A region can have a single observer, which gets notified whenever a change
|
||||
* to the region's status occurs.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionObserver {
|
||||
/**
|
||||
* Implement this method to be notified of a change in the status of an
|
||||
* offline region. Status changes include any change in state of the members
|
||||
* of OfflineRegionStatus.
|
||||
* <p>
|
||||
* This method will be executed on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param status the changed status
|
||||
*/
|
||||
void onStatusChanged(OfflineRegionStatus status);
|
||||
|
||||
/**
|
||||
* Implement this method to be notified of errors encountered while downloading
|
||||
* regional resources. Such errors may be recoverable; for example the implementation
|
||||
* will attempt to re-request failed resources based on an exponential backoff
|
||||
* algorithm, or when it detects that network access has been restored.
|
||||
* <p>
|
||||
* This method will be executed on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param error the offline region error message
|
||||
*/
|
||||
void onError(OfflineRegionError error);
|
||||
|
||||
/*
|
||||
* Implement this method to be notified when the limit on the number of Mapbox
|
||||
* tiles stored for offline regions has been reached.
|
||||
*
|
||||
* Once the limit has been reached, the SDK will not download further offline
|
||||
* tiles from Mapbox APIs until existing tiles have been removed.
|
||||
*
|
||||
* This limit does not apply to non-Mapbox tile sources.
|
||||
*
|
||||
* This method will be executed on the main thread.
|
||||
*/
|
||||
void mapboxTileCountLimitExceeded(long limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the OfflineRegionStatus
|
||||
* of the offline region, or a {@link String} error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionStatusCallback {
|
||||
/**
|
||||
* Receives the status
|
||||
*
|
||||
* @param status the offline region status
|
||||
*/
|
||||
void onStatus(OfflineRegionStatus status);
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a notification when
|
||||
* an offline region has been deleted, or a {@link String} error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionDeleteCallback {
|
||||
/**
|
||||
* Receives the delete notification
|
||||
*/
|
||||
void onDelete();
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a notification when
|
||||
* an offline region has been invalidated, or a {@link String} error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionInvalidateCallback {
|
||||
/**
|
||||
* Receives the invalidate notification
|
||||
*/
|
||||
void onInvalidate();
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the newly update
|
||||
* OfflineMetadata in the database, or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionUpdateMetadataCallback {
|
||||
/**
|
||||
* Receives the newly update offline region metadata.
|
||||
*
|
||||
* @param metadata the offline metadata to u[date
|
||||
*/
|
||||
void onUpdate(byte[] metadata);
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message to be shown
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* A region is either inactive (not downloading, but previously-downloaded
|
||||
* resources are available for use), or active (resources are being downloaded
|
||||
* or will be downloaded, if necessary, when network access is available).
|
||||
* <p>
|
||||
* This state is independent of whether or not the complete set of resources
|
||||
* is currently available for offline use. To check if that is the case, use
|
||||
* `OfflineRegionStatus.isComplete()`.
|
||||
* </p>
|
||||
*/
|
||||
|
||||
@IntDef( {STATE_INACTIVE, STATE_ACTIVE})
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
public @interface DownloadState {
|
||||
}
|
||||
|
||||
public static final int STATE_INACTIVE = 0;
|
||||
public static final int STATE_ACTIVE = 1;
|
||||
|
||||
// Keep track of the region state
|
||||
private int state = STATE_INACTIVE;
|
||||
|
||||
private boolean deliverInactiveMessages = false;
|
||||
|
||||
/**
|
||||
* Gets whether or not the `OfflineRegionObserver` will continue to deliver messages even if
|
||||
* the region state has been set as STATE_INACTIVE.
|
||||
*
|
||||
* @return true if delivering inactive messages
|
||||
*/
|
||||
public boolean isDeliveringInactiveMessages() {
|
||||
return deliverInactiveMessages;
|
||||
}
|
||||
|
||||
/**
|
||||
* When set true, the `OfflineRegionObserver` will continue to deliver messages even if
|
||||
* the region state has been set as STATE_INACTIVE (operations happen asynchronously). If set
|
||||
* false, the client won't be notified of further messages.
|
||||
*
|
||||
* @param deliverInactiveMessages true if it should deliver inactive messages
|
||||
*/
|
||||
public void setDeliverInactiveMessages(boolean deliverInactiveMessages) {
|
||||
this.deliverInactiveMessages = deliverInactiveMessages;
|
||||
}
|
||||
|
||||
private boolean deliverMessages() {
|
||||
if (state == STATE_ACTIVE) {
|
||||
return true;
|
||||
}
|
||||
return isDeliveringInactiveMessages();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* <p>
|
||||
* For JNI use only, to create a new offline region, use
|
||||
* {@link OfflineManager#createOfflineRegion} instead.
|
||||
*/
|
||||
@Keep
|
||||
private OfflineRegion(long offlineRegionPtr, FileSource fileSource, long id,
|
||||
OfflineRegionDefinition definition, byte[] metadata) {
|
||||
this.context = Mapbox.getApplicationContext();
|
||||
this.fileSource = fileSource;
|
||||
this.id = id;
|
||||
this.definition = definition;
|
||||
this.metadata = metadata;
|
||||
initialize(offlineRegionPtr, fileSource);
|
||||
}
|
||||
|
||||
/*
|
||||
* Getters
|
||||
*/
|
||||
|
||||
public long getID() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public OfflineRegionDefinition getDefinition() {
|
||||
return definition;
|
||||
}
|
||||
|
||||
public byte[] getMetadata() {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an observer to be notified when the state of the region changes.
|
||||
*
|
||||
* @param observer the observer to be notified
|
||||
*/
|
||||
public void setObserver(@Nullable final OfflineRegionObserver observer) {
|
||||
setOfflineRegionObserver(new OfflineRegionObserver() {
|
||||
@Override
|
||||
public void onStatusChanged(final OfflineRegionStatus status) {
|
||||
if (deliverMessages()) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (observer != null) {
|
||||
observer.onStatusChanged(status);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final OfflineRegionError error) {
|
||||
if (deliverMessages()) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (observer != null) {
|
||||
observer.onError(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mapboxTileCountLimitExceeded(final long limit) {
|
||||
if (deliverMessages()) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (observer != null) {
|
||||
observer.mapboxTileCountLimitExceeded(limit);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause or resume downloading of regional resources.
|
||||
* <p>
|
||||
* After a download has been completed, you are required to reset the state of the region to STATE_INACTIVE.
|
||||
* </p>
|
||||
*
|
||||
* @param state the download state
|
||||
*/
|
||||
public void setDownloadState(@DownloadState int state) {
|
||||
if (this.state == state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == STATE_ACTIVE) {
|
||||
ConnectivityReceiver.instance(context).activate();
|
||||
fileSource.activate();
|
||||
} else {
|
||||
fileSource.deactivate();
|
||||
ConnectivityReceiver.instance(context).deactivate();
|
||||
}
|
||||
|
||||
this.state = state;
|
||||
setOfflineRegionDownloadState(state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the current status of the region. The query will be executed
|
||||
* asynchronously and the results passed to the given callback which will be
|
||||
* executed on the main thread.
|
||||
*
|
||||
* @param callback the callback to invoked.
|
||||
*/
|
||||
public void getStatus(@NonNull final OfflineRegionStatusCallback callback) {
|
||||
fileSource.activate();
|
||||
getOfflineRegionStatus(new OfflineRegionStatusCallback() {
|
||||
@Override
|
||||
public void onStatus(final OfflineRegionStatus status) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onStatus(status);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an offline region from the database and perform any resources evictions
|
||||
* necessary as a result.
|
||||
* <p>
|
||||
* Eviction works by removing the least-recently requested resources not also required
|
||||
* by other regions, until the database shrinks below a certain size.
|
||||
* </p>
|
||||
* <p>
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the main thread.
|
||||
* </p>
|
||||
* Note that this operation can be potentially slow if packing the database
|
||||
* occurs automatically ({@link OfflineManager#runPackDatabaseAutomatically(boolean)})
|
||||
* <p>
|
||||
* After you call this method, you may not call any additional methods on this object.
|
||||
* </p>
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
public void delete(@NonNull final OfflineRegionDeleteCallback callback) {
|
||||
if (!isDeleted) {
|
||||
isDeleted = true;
|
||||
fileSource.activate();
|
||||
deleteOfflineRegion(new OfflineRegionDeleteCallback() {
|
||||
@Override
|
||||
public void onDelete() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
callback.onDelete();
|
||||
OfflineRegion.this.finalize();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
isDeleted = false;
|
||||
fileSource.deactivate();
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all the tiles from an offline region forcing Mapbox GL to revalidate
|
||||
* the tiles with the server before using. This is more efficient than deleting the
|
||||
* offline region and downloading it again because if the data on the cache matches
|
||||
* the server, no new data gets transmitted.
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
public void invalidate(@Nullable final OfflineRegionInvalidateCallback callback) {
|
||||
fileSource.activate();
|
||||
invalidateOfflineRegion(new OfflineRegionInvalidateCallback() {
|
||||
|
||||
@Override
|
||||
public void onInvalidate() {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onInvalidate();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(@NonNull final String message) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fileSource.deactivate();
|
||||
if (callback != null) {
|
||||
callback.onError(message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an offline region metadata from the database.
|
||||
* <p>
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the main thread.
|
||||
* </p>
|
||||
*
|
||||
* @param bytes the metadata in bytes
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
public void updateMetadata(@NonNull final byte[] bytes, @NonNull final OfflineRegionUpdateMetadataCallback callback) {
|
||||
updateOfflineRegionMetadata(bytes, new OfflineRegionUpdateMetadataCallback() {
|
||||
@Override
|
||||
public void onUpdate(final byte[] metadata) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
OfflineRegion.this.metadata = metadata;
|
||||
callback.onUpdate(metadata);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(final String error) {
|
||||
handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
callback.onError(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Keep
|
||||
private native void initialize(long offlineRegionPtr, FileSource fileSource);
|
||||
|
||||
@Override
|
||||
@Keep
|
||||
protected native void finalize();
|
||||
|
||||
@Keep
|
||||
private native void setOfflineRegionObserver(OfflineRegionObserver callback);
|
||||
|
||||
@Keep
|
||||
private native void setOfflineRegionDownloadState(@DownloadState int offlineRegionDownloadState);
|
||||
|
||||
@Keep
|
||||
private native void getOfflineRegionStatus(OfflineRegionStatusCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void deleteOfflineRegion(OfflineRegionDeleteCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void updateOfflineRegionMetadata(byte[] metadata, OfflineRegionUpdateMetadataCallback callback);
|
||||
|
||||
@Keep
|
||||
private native void invalidateOfflineRegion(OfflineRegionInvalidateCallback callback);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.annotation.IntDef
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.mapboxsdk.LibraryLoader
|
||||
import com.mapbox.mapboxsdk.Mapbox
|
||||
import com.mapbox.mapboxsdk.net.ConnectivityReceiver
|
||||
import com.mapbox.mapboxsdk.storage.FileSource
|
||||
|
||||
/**
|
||||
* An offline region is the basic building block for offline mobile maps.
|
||||
* Use [com.mapbox.mapboxsdk.offline.OfflineManager.CreateOfflineRegionCallback]
|
||||
* to create a new offline region.
|
||||
*/
|
||||
class OfflineRegion @Keep private constructor(offlineRegionPtr: Long, fileSource: FileSource, idParam: Long, definition: OfflineRegionDefinition, metadata: ByteArray) {
|
||||
// Members
|
||||
// Application context
|
||||
private val context: Context
|
||||
|
||||
// Holds the pointer to JNI OfflineRegion
|
||||
@Keep
|
||||
private val nativePtr: Long = 0
|
||||
|
||||
// Holds a reference to the FileSource to keep it alive
|
||||
private val fileSource: FileSource
|
||||
|
||||
/*
|
||||
* Getters
|
||||
*/
|
||||
// Region id
|
||||
val id: Long
|
||||
|
||||
// delete status
|
||||
private var isDeleted = false
|
||||
val definition: OfflineRegionDefinition
|
||||
|
||||
/**
|
||||
* Arbitrary binary region metadata. The contents are opaque to the SDK implementation;
|
||||
* it just stores and retrieves a byte[]. Check the `OfflineActivity` in the TestApp
|
||||
* for a sample implementation that uses JSON to store an offline region name.
|
||||
*/
|
||||
var metadata: ByteArray
|
||||
private set
|
||||
|
||||
// Makes sure callbacks come back to the main thread
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
/**
|
||||
* A region can have a single observer, which gets notified whenever a change
|
||||
* to the region's status occurs.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionObserver {
|
||||
/**
|
||||
* Implement this method to be notified of a change in the status of an
|
||||
* offline region. Status changes include any change in state of the members
|
||||
* of OfflineRegionStatus.
|
||||
*
|
||||
*
|
||||
* This method will be executed on the main thread.
|
||||
*
|
||||
*
|
||||
* @param status the changed status
|
||||
*/
|
||||
fun onStatusChanged(status: OfflineRegionStatus)
|
||||
|
||||
/**
|
||||
* Implement this method to be notified of errors encountered while downloading
|
||||
* regional resources. Such errors may be recoverable; for example the implementation
|
||||
* will attempt to re-request failed resources based on an exponential backoff
|
||||
* algorithm, or when it detects that network access has been restored.
|
||||
*
|
||||
*
|
||||
* This method will be executed on the main thread.
|
||||
*
|
||||
*
|
||||
* @param error the offline region error message
|
||||
*/
|
||||
fun onError(error: OfflineRegionError)
|
||||
|
||||
/*
|
||||
* Implement this method to be notified when the limit on the number of Mapbox
|
||||
* tiles stored for offline regions has been reached.
|
||||
*
|
||||
* Once the limit has been reached, the SDK will not download further offline
|
||||
* tiles from Mapbox APIs until existing tiles have been removed.
|
||||
*
|
||||
* This limit does not apply to non-Mapbox tile sources.
|
||||
*
|
||||
* This method will be executed on the main thread.
|
||||
*/
|
||||
fun mapboxTileCountLimitExceeded(limit: Long)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the OfflineRegionStatus
|
||||
* of the offline region, or a [String] error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionStatusCallback {
|
||||
/**
|
||||
* Receives the status
|
||||
*
|
||||
* @param status the offline region status
|
||||
*/
|
||||
fun onStatus(status: OfflineRegionStatus?)
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String?)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a notification when
|
||||
* an offline region has been deleted, or a [String] error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionDeleteCallback {
|
||||
/**
|
||||
* Receives the delete notification
|
||||
*/
|
||||
fun onDelete()
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing a notification when
|
||||
* an offline region has been invalidated, or a [String] error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionInvalidateCallback {
|
||||
/**
|
||||
* Receives the invalidate notification
|
||||
*/
|
||||
fun onInvalidate()
|
||||
|
||||
/**
|
||||
* Receives the error message
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* This callback receives an asynchronous response containing the newly update
|
||||
* OfflineMetadata in the database, or an error message otherwise.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionUpdateMetadataCallback {
|
||||
/**
|
||||
* Receives the newly update offline region metadata.
|
||||
*
|
||||
* @param metadata the offline metadata to u[date
|
||||
*/
|
||||
fun onUpdate(metadata: ByteArray)
|
||||
|
||||
/**
|
||||
* Receives the error message.
|
||||
*
|
||||
* @param error the error message to be shown
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* A region is either inactive (not downloading, but previously-downloaded
|
||||
* resources are available for use), or active (resources are being downloaded
|
||||
* or will be downloaded, if necessary, when network access is available).
|
||||
*
|
||||
*
|
||||
* This state is independent of whether or not the complete set of resources
|
||||
* is currently available for offline use. To check if that is the case, use
|
||||
* `OfflineRegionStatus.isComplete()`.
|
||||
*
|
||||
*/
|
||||
@IntDef(*[STATE_INACTIVE, STATE_ACTIVE])
|
||||
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
|
||||
annotation class DownloadState
|
||||
|
||||
// Keep track of the region state
|
||||
private var state = STATE_INACTIVE
|
||||
|
||||
/**
|
||||
* Gets whether or not the `OfflineRegionObserver` will continue to deliver messages even if
|
||||
* the region state has been set as STATE_INACTIVE.
|
||||
*
|
||||
* @return true if delivering inactive messages
|
||||
*/
|
||||
var isDeliveringInactiveMessages = false
|
||||
private set
|
||||
|
||||
/**
|
||||
* When set true, the `OfflineRegionObserver` will continue to deliver messages even if
|
||||
* the region state has been set as STATE_INACTIVE (operations happen asynchronously). If set
|
||||
* false, the client won't be notified of further messages.
|
||||
*
|
||||
* @param deliverInactiveMessages true if it should deliver inactive messages
|
||||
*/
|
||||
fun setDeliverInactiveMessages(deliverInactiveMessages: Boolean) {
|
||||
isDeliveringInactiveMessages = deliverInactiveMessages
|
||||
}
|
||||
|
||||
private fun deliverMessages(): Boolean {
|
||||
return if (state == STATE_ACTIVE) {
|
||||
true
|
||||
} else {
|
||||
isDeliveringInactiveMessages
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
*
|
||||
* For JNI use only, to create a new offline region, use
|
||||
* [com.mapbox.mapboxsdk.offline.OfflineManager.createOfflineRegion] instead.
|
||||
*/
|
||||
init {
|
||||
context = Mapbox.getApplicationContext()
|
||||
this.fileSource = fileSource
|
||||
this.id = idParam
|
||||
this.definition = definition
|
||||
this.metadata = metadata
|
||||
initialize(offlineRegionPtr, fileSource)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an observer to be notified when the state of the region changes.
|
||||
*
|
||||
* @param observer the observer to be notified
|
||||
*/
|
||||
fun setObserver(observer: OfflineRegionObserver?) {
|
||||
setOfflineRegionObserver(object : OfflineRegionObserver {
|
||||
override fun onStatusChanged(status: OfflineRegionStatus) {
|
||||
if (deliverMessages()) {
|
||||
handler.post { observer?.onStatusChanged(status) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: OfflineRegionError) {
|
||||
if (deliverMessages()) {
|
||||
handler.post { observer?.onError(error) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun mapboxTileCountLimitExceeded(limit: Long) {
|
||||
if (deliverMessages()) {
|
||||
handler.post { observer?.mapboxTileCountLimitExceeded(limit) }
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause or resume downloading of regional resources.
|
||||
*
|
||||
*
|
||||
* After a download has been completed, you are required to reset the state of the region to STATE_INACTIVE.
|
||||
*
|
||||
*
|
||||
* @param state the download state
|
||||
*/
|
||||
fun setDownloadState(@DownloadState state: Int) {
|
||||
if (this.state == state) {
|
||||
return
|
||||
}
|
||||
if (state == STATE_ACTIVE) {
|
||||
ConnectivityReceiver.instance(context).activate()
|
||||
fileSource.activate()
|
||||
} else {
|
||||
fileSource.deactivate()
|
||||
ConnectivityReceiver.instance(context).deactivate()
|
||||
}
|
||||
this.state = state
|
||||
setOfflineRegionDownloadState(state)
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the current status of the region. The query will be executed
|
||||
* asynchronously and the results passed to the given callback which will be
|
||||
* executed on the main thread.
|
||||
*
|
||||
* @param callback the callback to invoked.
|
||||
*/
|
||||
fun getStatus(callback: OfflineRegionStatusCallback) {
|
||||
fileSource.activate()
|
||||
getOfflineRegionStatus(object : OfflineRegionStatusCallback {
|
||||
override fun onStatus(status: OfflineRegionStatus?) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onStatus(status)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String?) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onError(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an offline region from the database and perform any resources evictions
|
||||
* necessary as a result.
|
||||
*
|
||||
*
|
||||
* Eviction works by removing the least-recently requested resources not also required
|
||||
* by other regions, until the database shrinks below a certain size.
|
||||
*
|
||||
*
|
||||
*
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the main thread.
|
||||
*
|
||||
* Note that this operation can be potentially slow if packing the database
|
||||
* occurs automatically ([com.mapbox.mapboxsdk.offline.OfflineManager.runPackDatabaseAutomatically])
|
||||
*
|
||||
*
|
||||
* After you call this method, you may not call any additional methods on this object.
|
||||
*
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
fun delete(callback: OfflineRegionDeleteCallback) {
|
||||
if (!isDeleted) {
|
||||
isDeleted = true
|
||||
fileSource.activate()
|
||||
deleteOfflineRegion(object : OfflineRegionDeleteCallback {
|
||||
override fun onDelete() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback.onDelete()
|
||||
finalize()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String) {
|
||||
handler.post {
|
||||
isDeleted = false
|
||||
fileSource.deactivate()
|
||||
callback.onError(error)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all the tiles from an offline region forcing Mapbox GL to revalidate
|
||||
* the tiles with the server before using. This is more efficient than deleting the
|
||||
* offline region and downloading it again because if the data on the cache matches
|
||||
* the server, no new data gets transmitted.
|
||||
*
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
fun invalidate(callback: OfflineRegionInvalidateCallback?) {
|
||||
fileSource.activate()
|
||||
invalidateOfflineRegion(object : OfflineRegionInvalidateCallback {
|
||||
override fun onInvalidate() {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onInvalidate()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(message: String) {
|
||||
handler.post {
|
||||
fileSource.deactivate()
|
||||
callback?.onError(message)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an offline region metadata from the database.
|
||||
*
|
||||
*
|
||||
* When the operation is complete or encounters an error, the given callback will be
|
||||
* executed on the main thread.
|
||||
*
|
||||
*
|
||||
* @param bytes the metadata in bytes
|
||||
* @param callback the callback to be invoked
|
||||
*/
|
||||
fun updateMetadata(
|
||||
bytes: ByteArray,
|
||||
callback: OfflineRegionUpdateMetadataCallback
|
||||
) {
|
||||
updateOfflineRegionMetadata(
|
||||
bytes,
|
||||
object : OfflineRegionUpdateMetadataCallback {
|
||||
override fun onUpdate(metadata: ByteArray) {
|
||||
handler.post {
|
||||
this@OfflineRegion.metadata = metadata
|
||||
callback.onUpdate(metadata)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onError(error: String) {
|
||||
handler.post { callback.onError(error) }
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Keep
|
||||
private external fun initialize(offlineRegionPtr: Long, fileSource: FileSource)
|
||||
|
||||
@Keep
|
||||
protected external fun finalize()
|
||||
|
||||
@Keep
|
||||
private external fun setOfflineRegionObserver(callback: OfflineRegionObserver)
|
||||
|
||||
@Keep
|
||||
private external fun setOfflineRegionDownloadState(@DownloadState offlineRegionDownloadState: Int)
|
||||
|
||||
@Keep
|
||||
private external fun getOfflineRegionStatus(callback: OfflineRegionStatusCallback)
|
||||
|
||||
@Keep
|
||||
private external fun deleteOfflineRegion(callback: OfflineRegionDeleteCallback)
|
||||
|
||||
@Keep
|
||||
private external fun updateOfflineRegionMetadata(metadata: ByteArray, callback: OfflineRegionUpdateMetadataCallback)
|
||||
|
||||
@Keep
|
||||
private external fun invalidateOfflineRegion(callback: OfflineRegionInvalidateCallback)
|
||||
|
||||
companion object {
|
||||
//
|
||||
// Static methods
|
||||
//
|
||||
init {
|
||||
LibraryLoader.load()
|
||||
}
|
||||
|
||||
const val STATE_INACTIVE = 0
|
||||
const val STATE_ACTIVE = 1
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import android.os.Parcelable;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
|
||||
import com.mapbox.mapboxsdk.maps.MapboxMapOptions;
|
||||
|
||||
/**
|
||||
* This is the interface that all Offline Region definitions have to implement.
|
||||
* <p>
|
||||
* For the present, a tile pyramid is the only type of offline region.
|
||||
*/
|
||||
@Keep
|
||||
public interface OfflineRegionDefinition extends Parcelable {
|
||||
|
||||
/**
|
||||
* Gets the bounds of the OfflineRegion.
|
||||
*
|
||||
* @return the bounds of the OfflineRegion.
|
||||
*/
|
||||
LatLngBounds getBounds();
|
||||
|
||||
/**
|
||||
* Returns the map style url of the OfflineRegion.
|
||||
*
|
||||
* @return The URL of the map style.
|
||||
*/
|
||||
String getStyleURL();
|
||||
|
||||
/**
|
||||
* Gets the minimum zoom level the OfflineRegion map can be displayed at.
|
||||
*
|
||||
* @return The minimum zoom level.
|
||||
*/
|
||||
double getMinZoom();
|
||||
|
||||
/**
|
||||
* Gets the maximum zoom level the OfflineRegion map can be displayed at.
|
||||
*
|
||||
* @return The maximum zoom level.
|
||||
*/
|
||||
double getMaxZoom();
|
||||
|
||||
/**
|
||||
* Gets the pixel ratio of the OfflineRegion map.
|
||||
*
|
||||
* @return The pixel ratio of the OfflineRegion map.
|
||||
*/
|
||||
float getPixelRatio();
|
||||
|
||||
/**
|
||||
* Specifies whether to include ideographic glyphs in downloaded font data.
|
||||
* Ideographic glyphs make up the majority of downloaded font data, but
|
||||
* it is possible to configure the renderer to use locally installed fonts
|
||||
* instead of relying on fonts downloaded as part of the offline pack.
|
||||
*
|
||||
* Defaults to `true`
|
||||
*
|
||||
* @return true if offline region will include ideographic glyphs
|
||||
* @see MapboxMapOptions#localIdeographFontFamily(String)
|
||||
*/
|
||||
boolean getIncludeIdeographs();
|
||||
|
||||
/**
|
||||
* Gets the type of the OfflineRegionDefinition ("tileregion", "shaperegion").
|
||||
*
|
||||
* @return The type of the OfflineRegionDefinition.
|
||||
*/
|
||||
String getType();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import android.os.Parcelable
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds
|
||||
|
||||
/**
|
||||
* This is the interface that all Offline Region definitions have to implement.
|
||||
*
|
||||
*
|
||||
* For the present, a tile pyramid is the only type of offline region.
|
||||
*/
|
||||
@Keep
|
||||
interface OfflineRegionDefinition : Parcelable {
|
||||
/**
|
||||
* Gets the bounds of the OfflineRegion.
|
||||
*
|
||||
* @return the bounds of the OfflineRegion.
|
||||
*/
|
||||
val bounds: LatLngBounds?
|
||||
|
||||
/**
|
||||
* Returns the map style url of the OfflineRegion.
|
||||
*
|
||||
* @return The URL of the map style.
|
||||
*/
|
||||
val styleURL: String?
|
||||
|
||||
/**
|
||||
* Gets the minimum zoom level the OfflineRegion map can be displayed at.
|
||||
*
|
||||
* @return The minimum zoom level.
|
||||
*/
|
||||
val minZoom: Double
|
||||
|
||||
/**
|
||||
* Gets the maximum zoom level the OfflineRegion map can be displayed at.
|
||||
*
|
||||
* @return The maximum zoom level.
|
||||
*/
|
||||
val maxZoom: Double
|
||||
|
||||
/**
|
||||
* Gets the pixel ratio of the OfflineRegion map.
|
||||
*
|
||||
* @return The pixel ratio of the OfflineRegion map.
|
||||
*/
|
||||
val pixelRatio: Float
|
||||
|
||||
/**
|
||||
* Specifies whether to include ideographic glyphs in downloaded font data.
|
||||
* Ideographic glyphs make up the majority of downloaded font data, but
|
||||
* it is possible to configure the renderer to use locally installed fonts
|
||||
* instead of relying on fonts downloaded as part of the offline pack.
|
||||
*
|
||||
* Defaults to `true`
|
||||
*
|
||||
* @return true if offline region will include ideographic glyphs
|
||||
* @see MapboxMapOptions.localIdeographFontFamily
|
||||
*/
|
||||
val includeIdeographs: Boolean
|
||||
|
||||
/**
|
||||
* Gets the type of the OfflineRegionDefinition ("tileregion", "shaperegion").
|
||||
*
|
||||
* @return The type of the OfflineRegionDefinition.
|
||||
*/
|
||||
val type: String
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.StringDef;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
|
||||
/**
|
||||
* An Offline Region error
|
||||
*/
|
||||
public class OfflineRegionError {
|
||||
|
||||
/**
|
||||
* Error code, as a string, self-explanatory.
|
||||
*/
|
||||
@StringDef( {REASON_SUCCESS, REASON_NOT_FOUND, REASON_SERVER, REASON_CONNECTION, REASON_OTHER})
|
||||
@Retention(RetentionPolicy.SOURCE)
|
||||
public @interface ErrorReason {
|
||||
}
|
||||
|
||||
public static final String REASON_SUCCESS = "REASON_SUCCESS";
|
||||
public static final String REASON_NOT_FOUND = "REASON_NOT_FOUND";
|
||||
public static final String REASON_SERVER = "REASON_SERVER";
|
||||
public static final String REASON_CONNECTION = "REASON_CONNECTION";
|
||||
public static final String REASON_OTHER = "REASON_OTHER";
|
||||
|
||||
@NonNull
|
||||
@ErrorReason
|
||||
private final String reason;
|
||||
|
||||
/**
|
||||
* /* An error message from the request handler, e.g. a server message or a system message
|
||||
* /* informing the user about the reason for the failure.
|
||||
*/
|
||||
@NonNull
|
||||
private final String message;
|
||||
|
||||
// Constructors
|
||||
@Keep
|
||||
private OfflineRegionError(@NonNull String reason, @NonNull String message) {
|
||||
// For JNI use only
|
||||
this.reason = reason;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
// Getters
|
||||
|
||||
@NonNull
|
||||
@ErrorReason
|
||||
public String getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
OfflineRegionError that = (OfflineRegionError) o;
|
||||
|
||||
if (!reason.equals(that.reason)) {
|
||||
return false;
|
||||
}
|
||||
return message.equals(that.message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = reason.hashCode();
|
||||
result = 31 * result + message.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "OfflineRegionError{"
|
||||
+ "reason='" + reason + '\''
|
||||
+ ", message='" + message + '\''
|
||||
+ '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import androidx.annotation.Keep
|
||||
import androidx.annotation.StringDef
|
||||
|
||||
/**
|
||||
* An Offline Region error
|
||||
*/
|
||||
class OfflineRegionError // For JNI use only // Constructors
|
||||
@Keep private constructor( // Getters
|
||||
@field:ErrorReason
|
||||
@get:ErrorReason
|
||||
val reason: String,
|
||||
/**
|
||||
* / * An error message from the request handler, e.g. a server message or a system message
|
||||
* / * informing the user about the reason for the failure.
|
||||
*/
|
||||
val message: String
|
||||
) {
|
||||
/**
|
||||
* Error code, as a string, self-explanatory.
|
||||
*/
|
||||
@StringDef(*[REASON_SUCCESS, REASON_NOT_FOUND, REASON_SERVER, REASON_CONNECTION, REASON_OTHER])
|
||||
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
|
||||
annotation class ErrorReason
|
||||
|
||||
override fun equals(o: Any?): Boolean {
|
||||
if (this === o) {
|
||||
return true
|
||||
}
|
||||
if (o == null || javaClass != o.javaClass) {
|
||||
return false
|
||||
}
|
||||
val that = o as OfflineRegionError
|
||||
return if (reason != that.reason) {
|
||||
false
|
||||
} else {
|
||||
message == that.message
|
||||
}
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = reason.hashCode()
|
||||
result = 31 * result + message.hashCode()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return ("OfflineRegionError{" + "reason='" + reason + '\'' + ", message='" + message + '\'' + '}')
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val REASON_SUCCESS = "REASON_SUCCESS"
|
||||
const val REASON_NOT_FOUND = "REASON_NOT_FOUND"
|
||||
const val REASON_SERVER = "REASON_SERVER"
|
||||
const val REASON_CONNECTION = "REASON_CONNECTION"
|
||||
const val REASON_OTHER = "REASON_OTHER"
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
|
||||
/**
|
||||
* A region's status includes its active/inactive state as well as counts
|
||||
* of the number of resources that have completed downloading, their total
|
||||
* size in bytes, and the total number of resources that are required.
|
||||
* <p>
|
||||
* Note that the total required size in bytes is not currently available. A
|
||||
* future API release may provide an estimate of this number.
|
||||
* </p>
|
||||
*/
|
||||
public class OfflineRegionStatus {
|
||||
|
||||
@OfflineRegion.DownloadState
|
||||
private int downloadState;
|
||||
|
||||
/**
|
||||
* The number of resources (inclusive of tiles) that have been fully downloaded
|
||||
* and are ready for offline access.
|
||||
*/
|
||||
private final long completedResourceCount;
|
||||
|
||||
/**
|
||||
* The cumulative size, in bytes, of all resources (inclusive of tiles) that have
|
||||
* been fully downloaded.
|
||||
*/
|
||||
private final long completedResourceSize;
|
||||
|
||||
/**
|
||||
* The number of tiles that have been fully downloaded and are ready for
|
||||
* offline access.
|
||||
*/
|
||||
private final long completedTileCount;
|
||||
|
||||
/**
|
||||
* The cumulative size, in bytes, of all tiles that have been fully downloaded.
|
||||
*/
|
||||
private final long completedTileSize;
|
||||
|
||||
/**
|
||||
* The number of resources that are known to be required for this region. See the
|
||||
* documentation for `requiredResourceCountIsPrecise` for an important caveat
|
||||
* about this number.
|
||||
*/
|
||||
private final long requiredResourceCount;
|
||||
|
||||
/**
|
||||
* This property is true when the value of requiredResourceCount is a precise
|
||||
* count of the number of required resources, and false when it is merely a lower
|
||||
* bound.
|
||||
* <p>
|
||||
* Specifically, it is false during early phases of an offline download. Once
|
||||
* style and tile sources have been downloaded, it is possible to calculate the
|
||||
* precise number of required resources, at which point it is set to true.
|
||||
* </p>
|
||||
*/
|
||||
private final boolean requiredResourceCountIsPrecise;
|
||||
|
||||
/*
|
||||
* Use setObserver(OfflineRegionObserver observer) to obtain a OfflineRegionStatus object.
|
||||
*
|
||||
* For JNI use only
|
||||
*/
|
||||
@Keep
|
||||
private OfflineRegionStatus(int downloadState, long completedResourceCount,
|
||||
long completedResourceSize, long completedTileCount,
|
||||
long completedTileSize, long requiredResourceCount,
|
||||
boolean requiredResourceCountIsPrecise) {
|
||||
this.downloadState = downloadState;
|
||||
this.completedResourceCount = completedResourceCount;
|
||||
this.completedResourceSize = completedResourceSize;
|
||||
this.completedTileCount = completedTileCount;
|
||||
this.completedTileSize = completedTileSize;
|
||||
this.requiredResourceCount = requiredResourceCount;
|
||||
this.requiredResourceCountIsPrecise = requiredResourceCountIsPrecise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates if the region download has completed
|
||||
*
|
||||
* @return true if download is complete, false if not
|
||||
*/
|
||||
public boolean isComplete() {
|
||||
return completedResourceCount >= requiredResourceCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the download state.
|
||||
* <p>
|
||||
* State is defined as
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>{@link OfflineRegion#STATE_ACTIVE}</li>
|
||||
* <li>{@link OfflineRegion#STATE_INACTIVE}</li>
|
||||
* </ul>
|
||||
*
|
||||
* @return the download state.
|
||||
*/
|
||||
@OfflineRegion.DownloadState
|
||||
public int getDownloadState() {
|
||||
return downloadState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of resources (inclusive of tiles) that have been fully downloaded
|
||||
* and are ready for offline access.
|
||||
*
|
||||
* @return the amount of resources that have finished downloading.
|
||||
*/
|
||||
public long getCompletedResourceCount() {
|
||||
return completedResourceCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cumulative size, in bytes, of all resources (inclusive of tiles) that have
|
||||
* been fully downloaded.
|
||||
*
|
||||
* @return the size of the resources that have finished downloading
|
||||
*/
|
||||
public long getCompletedResourceSize() {
|
||||
return completedResourceSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of tiles that have been fully downloaded and are ready for
|
||||
* offline access.
|
||||
*
|
||||
* @return the completed tile count
|
||||
*/
|
||||
public long getCompletedTileCount() {
|
||||
return completedTileCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cumulative size, in bytes, of all tiles that have been fully downloaded.
|
||||
*
|
||||
* @return the completed tile size
|
||||
*/
|
||||
public long getCompletedTileSize() {
|
||||
return completedTileSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of resources that are known to be required for this region. See the
|
||||
* documentation for `requiredResourceCountIsPrecise` for an important caveat
|
||||
* about this number.
|
||||
*
|
||||
* @return the amount of resources that are required
|
||||
*/
|
||||
public long getRequiredResourceCount() {
|
||||
return requiredResourceCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns when the value of requiredResourceCount is a precise
|
||||
* count of the number of required resources, and false when it is merely a lower
|
||||
* bound.
|
||||
* <p>
|
||||
* Specifically, it is false during early phases of an offline download. Once
|
||||
* style and tile sources have been downloaded, it is possible to calculate the
|
||||
* precise number of required resources, at which point it is set to true.
|
||||
* </p>
|
||||
*
|
||||
* @return True if the required resource count is precise, false if not
|
||||
*/
|
||||
public boolean isRequiredResourceCountPrecise() {
|
||||
return requiredResourceCountIsPrecise;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.mapboxsdk.offline.OfflineRegion.DownloadState
|
||||
|
||||
/**
|
||||
* A region's status includes its active/inactive state as well as counts
|
||||
* of the number of resources that have completed downloading, their total
|
||||
* size in bytes, and the total number of resources that are required.
|
||||
*
|
||||
*
|
||||
* Note that the total required size in bytes is not currently available. A
|
||||
* future API release may provide an estimate of this number.
|
||||
*
|
||||
*/
|
||||
class OfflineRegionStatus
|
||||
/**
|
||||
* Returns when the value of requiredResourceCount is a precise
|
||||
* count of the number of required resources, and false when it is merely a lower
|
||||
* bound.
|
||||
*
|
||||
*
|
||||
* Specifically, it is false during early phases of an offline download. Once
|
||||
* style and tile sources have been downloaded, it is possible to calculate the
|
||||
* precise number of required resources, at which point it is set to true.
|
||||
*
|
||||
*
|
||||
* @return True if the required resource count is precise, false if not
|
||||
*/
|
||||
|
||||
/*
|
||||
* Use setObserver(OfflineRegionObserver observer) to obtain a OfflineRegionStatus object.
|
||||
*
|
||||
* For JNI use only
|
||||
*/ @Keep private constructor(
|
||||
/**
|
||||
* Returns the download state.
|
||||
*
|
||||
*
|
||||
* State is defined as
|
||||
*
|
||||
*
|
||||
* * [OfflineRegion.STATE_ACTIVE]
|
||||
* * [OfflineRegion.STATE_INACTIVE]
|
||||
*
|
||||
*
|
||||
* @return the download state.
|
||||
*/
|
||||
@field:DownloadState
|
||||
@get:DownloadState
|
||||
val downloadState: Int,
|
||||
/**
|
||||
* The number of resources (inclusive of tiles) that have been fully downloaded
|
||||
* and are ready for offline access.
|
||||
*/
|
||||
val completedResourceCount: Long,
|
||||
/**
|
||||
* The cumulative size, in bytes, of all resources (inclusive of tiles) that have
|
||||
* been fully downloaded.
|
||||
*/
|
||||
val completedResourceSize: Long,
|
||||
/**
|
||||
* The number of tiles that have been fully downloaded and are ready for
|
||||
* offline access.
|
||||
*/
|
||||
val completedTileCount: Long,
|
||||
/**
|
||||
* The cumulative size, in bytes, of all tiles that have been fully downloaded.
|
||||
*/
|
||||
val completedTileSize: Long,
|
||||
/**
|
||||
* The number of resources that are known to be required for this region. See the
|
||||
* documentation for `requiredResourceCountIsPrecise` for an important caveat
|
||||
* about this number.
|
||||
*/
|
||||
val requiredResourceCount: Long,
|
||||
/**
|
||||
* This property is true when the value of requiredResourceCount is a precise
|
||||
* count of the number of required resources, and false when it is merely a lower
|
||||
* bound.
|
||||
*
|
||||
*
|
||||
* Specifically, it is false during early phases of an offline download. Once
|
||||
* style and tile sources have been downloaded, it is possible to calculate the
|
||||
* precise number of required resources, at which point it is set to true.
|
||||
*
|
||||
*/
|
||||
val isRequiredResourceCountPrecise: Boolean
|
||||
) {
|
||||
/**
|
||||
* Get the number of resources (inclusive of tiles) that have been fully downloaded
|
||||
* and are ready for offline access.
|
||||
*
|
||||
* @return the amount of resources that have finished downloading.
|
||||
*/
|
||||
/**
|
||||
* The cumulative size, in bytes, of all resources (inclusive of tiles) that have
|
||||
* been fully downloaded.
|
||||
*
|
||||
* @return the size of the resources that have finished downloading
|
||||
*/
|
||||
/**
|
||||
* Get the number of tiles that have been fully downloaded and are ready for
|
||||
* offline access.
|
||||
*
|
||||
* @return the completed tile count
|
||||
*/
|
||||
/**
|
||||
* Get the cumulative size, in bytes, of all tiles that have been fully downloaded.
|
||||
*
|
||||
* @return the completed tile size
|
||||
*/
|
||||
/**
|
||||
* Get the number of resources that are known to be required for this region. See the
|
||||
* documentation for `requiredResourceCountIsPrecise` for an important caveat
|
||||
* about this number.
|
||||
*
|
||||
* @return the amount of resources that are required
|
||||
*/
|
||||
/**
|
||||
* Validates if the region download has completed
|
||||
*
|
||||
* @return true if download is complete, false if not
|
||||
*/
|
||||
val isComplete: Boolean
|
||||
get() = completedResourceCount >= requiredResourceCount
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.mapbox.mapboxsdk.geometry.LatLng;
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
|
||||
|
||||
/**
|
||||
* An offline region defined by a style URL, geographic bounding box, zoom range, and
|
||||
* device pixel ratio.
|
||||
* <p>
|
||||
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
|
||||
* <p>
|
||||
* maxZoom may be ∞, in which case for each tile source, the region will include
|
||||
* tiles from minZoom up to the maximum zoom level provided by that source.
|
||||
* <p>
|
||||
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
|
||||
* <p>
|
||||
* if includeIdeographs is false, offline region will not include CJK glyphs
|
||||
*/
|
||||
public class OfflineTilePyramidRegionDefinition implements OfflineRegionDefinition {
|
||||
|
||||
@Keep
|
||||
private String styleURL;
|
||||
@Keep
|
||||
private LatLngBounds bounds;
|
||||
@Keep
|
||||
private double minZoom;
|
||||
@Keep
|
||||
private double maxZoom;
|
||||
@Keep
|
||||
private float pixelRatio;
|
||||
@Keep
|
||||
private boolean includeIdeographs;
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param bounds the bounds
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
*/
|
||||
@Keep
|
||||
public OfflineTilePyramidRegionDefinition(
|
||||
String styleURL, LatLngBounds bounds, double minZoom, double maxZoom, float pixelRatio) {
|
||||
this(styleURL, bounds, minZoom, maxZoom, pixelRatio, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param bounds the bounds
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
* @param includeIdeographs include glyphs for CJK languages
|
||||
*/
|
||||
@Keep
|
||||
public OfflineTilePyramidRegionDefinition(
|
||||
String styleURL, LatLngBounds bounds, double minZoom, double maxZoom, float pixelRatio,
|
||||
boolean includeIdeographs) {
|
||||
// Note: Also used in JNI
|
||||
this.styleURL = styleURL;
|
||||
this.bounds = bounds;
|
||||
this.minZoom = minZoom;
|
||||
this.maxZoom = maxZoom;
|
||||
this.pixelRatio = pixelRatio;
|
||||
this.includeIdeographs = includeIdeographs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from a Parcel.
|
||||
*
|
||||
* @param parcel the parcel to create the OfflineTilePyramidDefinition from
|
||||
*/
|
||||
public OfflineTilePyramidRegionDefinition(Parcel parcel) {
|
||||
this.styleURL = parcel.readString();
|
||||
this.bounds = new LatLngBounds.Builder()
|
||||
.include(new LatLng(parcel.readDouble(), parcel.readDouble()))
|
||||
.include(new LatLng(parcel.readDouble(), parcel.readDouble()))
|
||||
.build();
|
||||
this.minZoom = parcel.readDouble();
|
||||
this.maxZoom = parcel.readDouble();
|
||||
this.pixelRatio = parcel.readFloat();
|
||||
this.includeIdeographs = parcel.readByte() != 0;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String getStyleURL() {
|
||||
return styleURL;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LatLngBounds getBounds() {
|
||||
return bounds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getMinZoom() {
|
||||
return minZoom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double getMaxZoom() {
|
||||
return maxZoom;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getPixelRatio() {
|
||||
return pixelRatio;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getIncludeIdeographs() {
|
||||
return includeIdeographs;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String getType() {
|
||||
return "tileregion";
|
||||
}
|
||||
|
||||
/*
|
||||
* Parceable
|
||||
*/
|
||||
|
||||
@Override
|
||||
public int describeContents() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToParcel(@NonNull Parcel dest, int flags) {
|
||||
dest.writeString(styleURL);
|
||||
dest.writeDouble(bounds.latitudeNorth);
|
||||
dest.writeDouble(bounds.longitudeEast);
|
||||
dest.writeDouble(bounds.latitudeSouth);
|
||||
dest.writeDouble(bounds.longitudeWest);
|
||||
dest.writeDouble(minZoom);
|
||||
dest.writeDouble(maxZoom);
|
||||
dest.writeFloat(pixelRatio);
|
||||
dest.writeByte((byte) (includeIdeographs ? 1 : 0));
|
||||
}
|
||||
|
||||
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
|
||||
public OfflineTilePyramidRegionDefinition createFromParcel(@NonNull Parcel in) {
|
||||
return new OfflineTilePyramidRegionDefinition(in);
|
||||
}
|
||||
|
||||
public OfflineTilePyramidRegionDefinition[] newArray(int size) {
|
||||
return new OfflineTilePyramidRegionDefinition[size];
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
|
||||
import android.os.Parcel
|
||||
import android.os.Parcelable
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.mapboxsdk.geometry.LatLng
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds
|
||||
|
||||
/**
|
||||
* An offline region defined by a style URL, geographic bounding box, zoom range, and
|
||||
* device pixel ratio.
|
||||
*
|
||||
*
|
||||
* Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
|
||||
*
|
||||
*
|
||||
* maxZoom may be ∞, in which case for each tile source, the region will include
|
||||
* tiles from minZoom up to the maximum zoom level provided by that source.
|
||||
*
|
||||
*
|
||||
* pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
|
||||
*
|
||||
*
|
||||
* if includeIdeographs is false, offline region will not include CJK glyphs
|
||||
*/
|
||||
class OfflineTilePyramidRegionDefinition : OfflineRegionDefinition {
|
||||
@Keep
|
||||
override var styleURL: String?
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override val bounds: LatLngBounds?
|
||||
|
||||
@Keep
|
||||
override var minZoom: Double
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var maxZoom: Double
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var pixelRatio: Float
|
||||
private set
|
||||
|
||||
@Keep
|
||||
override var includeIdeographs: Boolean
|
||||
private set
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param bounds the bounds
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
*/
|
||||
@Keep
|
||||
constructor(styleURL: String?, bounds: LatLngBounds, minZoom: Double, maxZoom: Double, pixelRatio: Float) : this(styleURL, bounds, minZoom, maxZoom, pixelRatio, false) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from parameters.
|
||||
*
|
||||
* @param styleURL the style
|
||||
* @param bounds the bounds
|
||||
* @param minZoom min zoom
|
||||
* @param maxZoom max zoom
|
||||
* @param pixelRatio pixel ratio of the device
|
||||
* @param includeIdeographs include glyphs for CJK languages
|
||||
*/
|
||||
@Keep
|
||||
constructor(styleURL: String?, bounds: LatLngBounds, minZoom: Double, maxZoom: Double, pixelRatio: Float, includeIdeographs: Boolean) {
|
||||
// Note: Also used in JNI
|
||||
this.styleURL = styleURL
|
||||
this.bounds = bounds
|
||||
this.minZoom = minZoom
|
||||
this.maxZoom = maxZoom
|
||||
this.pixelRatio = pixelRatio
|
||||
this.includeIdeographs = includeIdeographs
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor to create an OfflineTilePyramidDefinition from a Parcel.
|
||||
*
|
||||
* @param parcel the parcel to create the OfflineTilePyramidDefinition from
|
||||
*/
|
||||
constructor(parcel: Parcel) {
|
||||
styleURL = parcel.readString()
|
||||
bounds = LatLngBounds.Builder().include(LatLng(parcel.readDouble(), parcel.readDouble())).include(LatLng(parcel.readDouble(), parcel.readDouble())).build()
|
||||
minZoom = parcel.readDouble()
|
||||
maxZoom = parcel.readDouble()
|
||||
pixelRatio = parcel.readFloat()
|
||||
includeIdeographs = parcel.readByte().toInt() != 0
|
||||
}
|
||||
|
||||
override val type: String
|
||||
get() = "tileregion"
|
||||
|
||||
/*
|
||||
* Parceable
|
||||
*/
|
||||
override fun describeContents(): Int {
|
||||
return 0
|
||||
}
|
||||
|
||||
override fun writeToParcel(dest: Parcel, flags: Int) {
|
||||
dest.writeString(styleURL)
|
||||
if (bounds != null) {
|
||||
dest.writeDouble(bounds.latitudeNorth)
|
||||
dest.writeDouble(bounds.longitudeEast)
|
||||
dest.writeDouble(bounds.latitudeSouth)
|
||||
dest.writeDouble(bounds.longitudeWest)
|
||||
}
|
||||
dest.writeDouble(minZoom)
|
||||
dest.writeDouble(maxZoom)
|
||||
dest.writeFloat(pixelRatio)
|
||||
dest.writeByte((if (includeIdeographs) 1 else 0).toByte())
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmField
|
||||
val CREATOR: Parcelable.Creator<*> = object : Parcelable.Creator<Any?> {
|
||||
override fun createFromParcel(`in`: Parcel): OfflineTilePyramidRegionDefinition? {
|
||||
return OfflineTilePyramidRegionDefinition(`in`)
|
||||
}
|
||||
|
||||
override fun newArray(size: Int): Array<OfflineTilePyramidRegionDefinition?> {
|
||||
return arrayOfNulls(size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
* Contains the Mapbox Maps Android Offline API classes.
|
||||
*/
|
||||
package com.mapbox.mapboxsdk.offline;
|
||||
package com.mapbox.mapboxsdk.offline
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter;
|
||||
|
||||
import android.graphics.BitmapFactory;
|
||||
|
||||
class MapSnaphotUtil {
|
||||
|
||||
static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
|
||||
// Raw height and width of image
|
||||
final int height = options.outHeight;
|
||||
final int width = options.outWidth;
|
||||
int inSampleSize = 1;
|
||||
|
||||
if (height > reqHeight || width > reqWidth) {
|
||||
|
||||
final int halfHeight = height / 2;
|
||||
final int halfWidth = width / 2;
|
||||
|
||||
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
|
||||
// height and width larger than the requested height and width.
|
||||
while ((halfHeight / inSampleSize) >= reqHeight
|
||||
&& (halfWidth / inSampleSize) >= reqWidth) {
|
||||
inSampleSize *= 2;
|
||||
}
|
||||
}
|
||||
return inSampleSize;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
|
||||
internal object MapSnaphotUtil {
|
||||
fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
|
||||
// Raw height and width of image
|
||||
val height = options.outHeight
|
||||
val width = options.outWidth
|
||||
var inSampleSize = 1
|
||||
if (height > reqHeight || width > reqWidth) {
|
||||
val halfHeight = height / 2
|
||||
val halfWidth = width / 2
|
||||
|
||||
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
|
||||
// height and width larger than the requested height and width.
|
||||
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
return inSampleSize
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.PointF;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.mapbox.mapboxsdk.geometry.LatLng;
|
||||
|
||||
/**
|
||||
* A completed snapshot.
|
||||
*
|
||||
* @see MapSnapshotter
|
||||
*/
|
||||
public class MapSnapshot {
|
||||
|
||||
@Keep
|
||||
private long nativePtr = 0;
|
||||
private Bitmap bitmap;
|
||||
private String[] attributions;
|
||||
private boolean showLogo;
|
||||
|
||||
/**
|
||||
* Created from native side
|
||||
*/
|
||||
@Keep
|
||||
private MapSnapshot(long nativePtr, Bitmap bitmap, String[] attributions, boolean showLogo) {
|
||||
this.nativePtr = nativePtr;
|
||||
this.bitmap = bitmap;
|
||||
this.attributions = attributions;
|
||||
this.showLogo = showLogo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the large
|
||||
*/
|
||||
public Bitmap getBitmap() {
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the point in pixels on the Image from geographical coordinates.
|
||||
*
|
||||
* @param latLng the geographical coordinates
|
||||
* @return the point on the image
|
||||
*/
|
||||
@NonNull
|
||||
@Keep
|
||||
public native PointF pixelForLatLng(LatLng latLng);
|
||||
|
||||
/**
|
||||
* Calculate geographical coordinates from a point in pixels on the Image
|
||||
*
|
||||
* @param pointF the point in pixels
|
||||
* @return the geographical coordinates
|
||||
*/
|
||||
@NonNull
|
||||
@Keep
|
||||
public native LatLng latLngForPixel(PointF pointF);
|
||||
|
||||
/**
|
||||
* @return The attributions for the sources of this snapshot.
|
||||
*/
|
||||
protected String[] getAttributions() {
|
||||
return attributions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Flag indicating to show the Mapbox logo.
|
||||
*/
|
||||
boolean isShowLogo() {
|
||||
return showLogo;
|
||||
}
|
||||
|
||||
// Unused, needed for peer binding
|
||||
@Keep
|
||||
private native void initialize();
|
||||
|
||||
@Keep
|
||||
protected native void finalize();
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.PointF
|
||||
import androidx.annotation.Keep
|
||||
import com.mapbox.mapboxsdk.geometry.LatLng
|
||||
|
||||
/**
|
||||
* A completed snapshot.
|
||||
*
|
||||
* @see MapSnapshotter
|
||||
*/
|
||||
@Keep
|
||||
class MapSnapshot private constructor(val nativePtr: Long, bitmap: Bitmap, attributions: Array<String>, showLogo: Boolean) {
|
||||
|
||||
/**
|
||||
* @return the large
|
||||
*/
|
||||
val bitmap: Bitmap
|
||||
|
||||
/**
|
||||
* @return The attributions for the sources of this snapshot.
|
||||
*/
|
||||
val attributions: Array<String>
|
||||
|
||||
/**
|
||||
* @return Flag indicating to show the Mapbox logo.
|
||||
*/
|
||||
val isShowLogo: Boolean
|
||||
|
||||
/**
|
||||
* Created from native side
|
||||
*/
|
||||
init {
|
||||
this.bitmap = bitmap
|
||||
this.attributions = attributions
|
||||
isShowLogo = showLogo
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the point in pixels on the Image from geographical coordinates.
|
||||
*
|
||||
* @param latLng the geographical coordinates
|
||||
* @return the point on the image
|
||||
*/
|
||||
@Keep
|
||||
external fun pixelForLatLng(latLng: LatLng?): PointF
|
||||
|
||||
/**
|
||||
* Calculate geographical coordinates from a point in pixels on the Image
|
||||
*
|
||||
* @param pointF the point in pixels
|
||||
* @return the geographical coordinates
|
||||
*/
|
||||
@Keep
|
||||
external fun latLngForPixel(pointF: PointF?): LatLng
|
||||
|
||||
// Unused, needed for peer binding
|
||||
@Keep
|
||||
private external fun initialize()
|
||||
|
||||
@Keep
|
||||
protected external fun finalize()
|
||||
}
|
||||
@@ -1,885 +0,0 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Matrix;
|
||||
import android.graphics.PointF;
|
||||
import android.os.Handler;
|
||||
import android.text.Html;
|
||||
import android.text.TextUtils;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.TextView;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import com.mapbox.mapboxsdk.R;
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionLayout;
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionMeasure;
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionParser;
|
||||
import com.mapbox.mapboxsdk.camera.CameraPosition;
|
||||
import com.mapbox.mapboxsdk.constants.MapboxConstants;
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
|
||||
import com.mapbox.mapboxsdk.log.Logger;
|
||||
import com.mapbox.mapboxsdk.maps.Image;
|
||||
import com.mapbox.mapboxsdk.maps.Style;
|
||||
import com.mapbox.mapboxsdk.storage.FileSource;
|
||||
import com.mapbox.mapboxsdk.style.layers.Layer;
|
||||
import com.mapbox.mapboxsdk.style.sources.Source;
|
||||
import com.mapbox.mapboxsdk.utils.FontUtils;
|
||||
import com.mapbox.mapboxsdk.utils.ThreadUtils;
|
||||
|
||||
import static com.mapbox.mapboxsdk.maps.Style.toImage;
|
||||
|
||||
/**
|
||||
* The map snapshotter creates a large of the map, rendered
|
||||
* off the UI thread. The snapshotter itself must be used on
|
||||
* the UI thread (for access to the main looper)
|
||||
*/
|
||||
@UiThread
|
||||
public class MapSnapshotter {
|
||||
|
||||
private static final String TAG = "Mbgl-MapSnapshotter";
|
||||
|
||||
private static final int LOGO_MARGIN_DP = 4;
|
||||
|
||||
// Holds the pointer to JNI NativeMapView
|
||||
@Keep
|
||||
private long nativePtr = 0;
|
||||
|
||||
private final Context context;
|
||||
private boolean fullyLoaded = false;
|
||||
private Options options;
|
||||
|
||||
@Nullable
|
||||
private SnapshotReadyCallback callback;
|
||||
@Nullable
|
||||
private ErrorHandler errorHandler;
|
||||
@Nullable
|
||||
private Observer observer;
|
||||
|
||||
/**
|
||||
* Get notified on snapshot completion.
|
||||
*
|
||||
* @see MapSnapshotter#start(SnapshotReadyCallback, ErrorHandler)
|
||||
*/
|
||||
public interface SnapshotReadyCallback {
|
||||
|
||||
/**
|
||||
* Called when the snapshot is complete.
|
||||
*
|
||||
* @param snapshot the snapshot
|
||||
*/
|
||||
void onSnapshotReady(MapSnapshot snapshot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to get notified of errors
|
||||
* in snapshot generation
|
||||
*
|
||||
* @see MapSnapshotter#start(SnapshotReadyCallback, ErrorHandler)
|
||||
*/
|
||||
public interface ErrorHandler {
|
||||
|
||||
/**
|
||||
* Called on error. Snapshotting will not
|
||||
* continue
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
void onError(String error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to get notified on snapshotter style loading
|
||||
* completion.
|
||||
*
|
||||
* @see MapSnapshotter#setObserver(Observer)
|
||||
*/
|
||||
public interface Observer {
|
||||
|
||||
/**
|
||||
* Called when snapshotter finishes loading its style.
|
||||
*/
|
||||
void onDidFinishLoadingStyle();
|
||||
|
||||
/**
|
||||
* Called when the map is missing an icon.The icon should be added synchronously with
|
||||
* {@link MapSnapshotter#addImage(String, Bitmap, boolean)} to be rendered on the current zoom level.
|
||||
* When loading icons asynchronously, you can load a placeholder image and replace it when you icon has loaded.
|
||||
*
|
||||
* @param imageName the id of the icon that is missing
|
||||
*/
|
||||
void onStyleImageMissing(String imageName);
|
||||
}
|
||||
|
||||
/**
|
||||
* MapSnapshotter options
|
||||
*/
|
||||
public static class Options {
|
||||
private float pixelRatio = 1;
|
||||
private int width;
|
||||
private int height;
|
||||
private LatLngBounds region;
|
||||
private CameraPosition cameraPosition;
|
||||
private boolean showLogo = true;
|
||||
private String localIdeographFontFamily = MapboxConstants.DEFAULT_FONT;
|
||||
private String apiBaseUrl;
|
||||
private Style.Builder builder;
|
||||
|
||||
/**
|
||||
* @param width the width of the image
|
||||
* @param height the height of the image
|
||||
*/
|
||||
public Options(int width, int height) {
|
||||
if (width == 0 || height == 0) {
|
||||
throw new IllegalArgumentException("Unable to create a snapshot with width or height set to 0");
|
||||
}
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a style builder to snapshotter, the contents in builder like layers/sources/images will be applied
|
||||
* to snapshotter.
|
||||
*
|
||||
* @param builder The builder will applied to snapshotter
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withStyleBuilder(Style.Builder builder) {
|
||||
this.builder = builder;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Style.Builder getBuilder() {
|
||||
return builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The style URI to use
|
||||
* @return the mutated {@link Options}
|
||||
* @deprecated use {@link #withStyleBuilder(Style.Builder)} instead
|
||||
*/
|
||||
@NonNull
|
||||
public Options withStyle(String uri) {
|
||||
withStyleBuilder(new Style.Builder().fromUri(uri));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param styleJson The style json to use
|
||||
* @return the mutated {@link Options}
|
||||
* @deprecated use {@link #withStyleBuilder(Style.Builder)} instead
|
||||
*/
|
||||
@NonNull
|
||||
public Options withStyleJson(String styleJson) {
|
||||
withStyleBuilder(new Style.Builder().fromJson(styleJson));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param region the region to show in the snapshot.
|
||||
* This is applied after the camera position
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withRegion(LatLngBounds region) {
|
||||
this.region = region;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pixelRatio the pixel ratio to use (default: 1)
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withPixelRatio(float pixelRatio) {
|
||||
this.pixelRatio = pixelRatio;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param cameraPosition The camera position to use,
|
||||
* the {@link CameraPosition#target} is overridden
|
||||
* by region if set in conjunction.
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withCameraPosition(CameraPosition cameraPosition) {
|
||||
this.cameraPosition = cameraPosition;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param showLogo The flag indicating to show the Mapbox logo.
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withLogo(boolean showLogo) {
|
||||
this.showLogo = showLogo;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the font family for generating glyphs locally for ideographs in the 'CJK Unified Ideographs'
|
||||
* and 'Hangul Syllables' ranges.
|
||||
* <p>
|
||||
* The font family argument is passed to {@link android.graphics.Typeface#create(String, int)}.
|
||||
* Default system fonts are defined in '/system/etc/fonts.xml'
|
||||
* Default font for local ideograph font family is {@link MapboxConstants#DEFAULT_FONT}.
|
||||
* </p>
|
||||
*
|
||||
* @param fontFamily font family for local ideograph generation.
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withLocalIdeographFontFamily(String fontFamily) {
|
||||
this.localIdeographFontFamily = FontUtils.extractValidFont(fontFamily);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a font family from range of font families for generating glyphs locally for ideographs in the
|
||||
* 'CJK Unified Ideographs' and 'Hangul Syllables' ranges.
|
||||
* <p>
|
||||
* The font families are checked against the default system fonts defined in
|
||||
* '/system/etc/fonts.xml'. Default font for local ideograph font family is
|
||||
* {@link MapboxConstants#DEFAULT_FONT}.
|
||||
* </p>
|
||||
*
|
||||
* @param fontFamilies font families for local ideograph generation.
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withLocalIdeographFontFamily(String... fontFamilies) {
|
||||
this.localIdeographFontFamily = FontUtils.extractValidFont(fontFamilies);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the URL used for API endpoint.
|
||||
*
|
||||
* @param apiBaseUrl The base of our API endpoint
|
||||
* @return the mutated {@link Options}
|
||||
* @deprecated use {@link #withApiBaseUri(String)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
@NonNull
|
||||
public Options withApiBaseUrl(String apiBaseUrl) {
|
||||
this.apiBaseUrl = apiBaseUrl;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the URI used for API endpoint.
|
||||
*
|
||||
* @param apiBaseUri The base of our API endpoint
|
||||
* @return the mutated {@link Options}
|
||||
*/
|
||||
@NonNull
|
||||
public Options withApiBaseUri(String apiBaseUri) {
|
||||
this.apiBaseUrl = apiBaseUri;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the width of the image
|
||||
*/
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the height of the image
|
||||
*/
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the pixel ratio
|
||||
*/
|
||||
public float getPixelRatio() {
|
||||
return pixelRatio;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the region
|
||||
*/
|
||||
@Nullable
|
||||
public LatLngBounds getRegion() {
|
||||
return region;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the style url
|
||||
* @deprecated use {@link #getStyleUri()} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public String getStyleUrl() {
|
||||
return builder == null ? null : builder.getUri();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the style uri
|
||||
*/
|
||||
public String getStyleUri() {
|
||||
return builder == null ? null : builder.getUri();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the style json
|
||||
*/
|
||||
@Nullable
|
||||
public String getStyleJson() {
|
||||
return builder == null ? null : builder.getJson();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the camera position
|
||||
*/
|
||||
@Nullable
|
||||
public CameraPosition getCameraPosition() {
|
||||
return cameraPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the font family used for locally generating ideographs,
|
||||
* Default font for local ideograph font family is {@link MapboxConstants#DEFAULT_FONT}.
|
||||
*/
|
||||
public String getLocalIdeographFontFamily() {
|
||||
return localIdeographFontFamily;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The base of our API endpoint
|
||||
* @deprecated use {@link #getApiBaseUri()} instead
|
||||
*/
|
||||
@Nullable
|
||||
@Deprecated
|
||||
public String getApiBaseUrl() {
|
||||
return apiBaseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The base of our API endpoint
|
||||
*/
|
||||
@Nullable
|
||||
public String getApiBaseUri() {
|
||||
return apiBaseUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the Map snapshotter, but doesn't start rendering or
|
||||
* loading yet.
|
||||
*
|
||||
* @param context the Context that is or contains the Application context
|
||||
* @param options the options to use for the snapshot
|
||||
*/
|
||||
public MapSnapshotter(@NonNull Context context, @NonNull Options options) {
|
||||
checkThread();
|
||||
this.context = context.getApplicationContext();
|
||||
this.options = options;
|
||||
|
||||
FileSource fileSource = FileSource.getInstance(context);
|
||||
String apiBaseUrl = options.getApiBaseUrl();
|
||||
if (!TextUtils.isEmpty(apiBaseUrl)) {
|
||||
fileSource.setApiBaseUrl(apiBaseUrl);
|
||||
}
|
||||
|
||||
nativeInitialize(this, fileSource, options.pixelRatio, options.width,
|
||||
options.height, options.getStyleUri(), options.getStyleJson(), options.region, options.cameraPosition,
|
||||
options.showLogo, options.localIdeographFontFamily);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Starts loading and rendering the snapshot. The callback will be fired
|
||||
* on the calling thread.
|
||||
*
|
||||
* @param callback the callback to use when the snapshot is ready
|
||||
*/
|
||||
public void start(@NonNull SnapshotReadyCallback callback) {
|
||||
this.start(callback, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts loading and rendering the snapshot. The callbacks will be fired
|
||||
* on the calling thread.
|
||||
*
|
||||
* @param callback the callback to use when the snapshot is ready
|
||||
* @param errorHandler the error handler to use on snapshot errors
|
||||
*/
|
||||
public void start(@NonNull SnapshotReadyCallback callback, ErrorHandler errorHandler) {
|
||||
if (this.callback != null) {
|
||||
throw new IllegalStateException("Snapshotter was already started");
|
||||
}
|
||||
checkThread();
|
||||
this.callback = callback;
|
||||
this.errorHandler = errorHandler;
|
||||
nativeStart();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new size
|
||||
*
|
||||
* @param width the width
|
||||
* @param height the height
|
||||
*/
|
||||
@Keep
|
||||
public native void setSize(int width, int height);
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new {@link CameraPosition}
|
||||
*
|
||||
* @param cameraPosition the camera position
|
||||
*/
|
||||
@Keep
|
||||
public native void setCameraPosition(CameraPosition cameraPosition);
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new {@link LatLngBounds}
|
||||
*
|
||||
* @param region the region
|
||||
*/
|
||||
@Keep
|
||||
public native void setRegion(LatLngBounds region);
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new style url
|
||||
*
|
||||
* @param styleUrl the style url
|
||||
*/
|
||||
@Keep
|
||||
public native void setStyleUrl(String styleUrl);
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new style json
|
||||
*
|
||||
* @param styleJson the style json
|
||||
*/
|
||||
@Keep
|
||||
public native void setStyleJson(String styleJson);
|
||||
|
||||
/**
|
||||
* Adds the layer to the map. The layer must be newly created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param below the layer id to add this layer before
|
||||
*/
|
||||
private void addLayerBelow(Layer layer, String below) {
|
||||
nativeAddLayerBelow(layer.getNativePtr(), below);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the layer to the map. The layer must be newly created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param above the layer id to add this layer above
|
||||
*/
|
||||
private void addLayerAbove(@NonNull Layer layer, @NonNull String above) {
|
||||
nativeAddLayerAbove(layer.getNativePtr(), above);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the layer to the snapshotter at the specified index. The layer must be newly
|
||||
* created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param index the index to insert the layer at
|
||||
*/
|
||||
private void addLayerAt(Layer layer, int index) {
|
||||
nativeAddLayerAt(layer.getNativePtr(), index);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private void addSource(Source source) {
|
||||
nativeAddSource(source, source.getNativePtr());
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an image to be used in the snapshotter'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 Bitmap bitmap, boolean sdf) {
|
||||
nativeAddImages(new Image[] {toImage(new Style.Builder.ImageWrapper(name, bitmap, sdf))});
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called in on the thread
|
||||
* the object was created on.
|
||||
*/
|
||||
public void cancel() {
|
||||
checkThread();
|
||||
reset();
|
||||
nativeCancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets observer for a snapshotter
|
||||
*
|
||||
* @param observer an Observer object
|
||||
*/
|
||||
public void setObserver(@Nullable Observer observer) {
|
||||
checkThread();
|
||||
this.observer = observer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw an overlay on the map snapshot.
|
||||
*
|
||||
* @param mapSnapshot the map snapshot to draw the overlay on
|
||||
*/
|
||||
protected void addOverlay(@NonNull MapSnapshot mapSnapshot) {
|
||||
Bitmap snapshot = mapSnapshot.getBitmap();
|
||||
Canvas canvas = new Canvas(snapshot);
|
||||
int margin = (int) context.getResources().getDisplayMetrics().density * LOGO_MARGIN_DP;
|
||||
drawOverlay(mapSnapshot, snapshot, canvas, margin);
|
||||
}
|
||||
|
||||
private void drawOverlay(@NonNull MapSnapshot mapSnapshot, @NonNull Bitmap snapshot,
|
||||
@NonNull Canvas canvas, int margin) {
|
||||
AttributionMeasure measure = getAttributionMeasure(mapSnapshot, snapshot, margin);
|
||||
AttributionLayout layout = measure.measure();
|
||||
drawLogo(mapSnapshot, canvas, margin, layout);
|
||||
drawAttribution(mapSnapshot, canvas, measure, layout);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private AttributionMeasure getAttributionMeasure(@NonNull MapSnapshot mapSnapshot,
|
||||
@NonNull Bitmap snapshot, int margin) {
|
||||
Logo logo = createScaledLogo(snapshot);
|
||||
TextView longText = createTextView(mapSnapshot, false, logo.getScale());
|
||||
TextView shortText = createTextView(mapSnapshot, true, logo.getScale());
|
||||
|
||||
return new AttributionMeasure.Builder()
|
||||
.setSnapshot(snapshot)
|
||||
.setLogo(logo.getLarge())
|
||||
.setLogoSmall(logo.getSmall())
|
||||
.setTextView(longText)
|
||||
.setTextViewShort(shortText)
|
||||
.setMarginPadding(margin)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void drawLogo(MapSnapshot mapSnapshot, @NonNull Canvas canvas,
|
||||
int margin, @NonNull AttributionLayout layout) {
|
||||
if (mapSnapshot.isShowLogo()) {
|
||||
drawLogo(mapSnapshot.getBitmap(), canvas, margin, layout);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawLogo(@NonNull Bitmap snapshot, @NonNull Canvas canvas,
|
||||
int margin, AttributionLayout placement) {
|
||||
Bitmap selectedLogo = placement.getLogo();
|
||||
if (selectedLogo != null) {
|
||||
canvas.drawBitmap(selectedLogo, margin, snapshot.getHeight() - selectedLogo.getHeight() - margin, null);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawAttribution(@NonNull MapSnapshot mapSnapshot, @NonNull Canvas canvas,
|
||||
@NonNull AttributionMeasure measure, AttributionLayout layout) {
|
||||
// draw attribution
|
||||
PointF anchorPoint = layout.getAnchorPoint();
|
||||
if (anchorPoint != null) {
|
||||
drawAttribution(canvas, measure, anchorPoint);
|
||||
} else {
|
||||
Bitmap snapshot = mapSnapshot.getBitmap();
|
||||
Logger.e(TAG, String.format("Could not generate attribution for snapshot size: %s x %s."
|
||||
+ " You are required to provide your own attribution for the used sources: %s",
|
||||
snapshot.getWidth(), snapshot.getHeight(), mapSnapshot.getAttributions())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawAttribution(Canvas canvas, AttributionMeasure measure, PointF anchorPoint) {
|
||||
canvas.save();
|
||||
canvas.translate(anchorPoint.x, anchorPoint.y);
|
||||
measure.getTextView().draw(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private TextView createTextView(@NonNull MapSnapshot mapSnapshot, boolean shortText, float scale) {
|
||||
int textColor = ResourcesCompat.getColor(context.getResources(), R.color.maplibre_gray_dark, context.getTheme());
|
||||
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
|
||||
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
|
||||
TextView textView = new TextView(context);
|
||||
textView.setLayoutParams(new ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
);
|
||||
textView.setSingleLine(true);
|
||||
textView.setTextSize(10 * scale);
|
||||
textView.setTextColor(textColor);
|
||||
textView.setBackgroundResource(R.drawable.maplibre_rounded_corner);
|
||||
textView.setText(Html.fromHtml(createAttributionString(mapSnapshot, shortText)));
|
||||
textView.measure(widthMeasureSpec, heightMeasureSpec);
|
||||
textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
|
||||
return textView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the attribution string.
|
||||
*
|
||||
* @param mapSnapshot the map snapshot to create the attribution for
|
||||
* @param shortText indicates if the short variant of the string should be parsed
|
||||
* @return the parsed attribution string
|
||||
*/
|
||||
@NonNull
|
||||
private String createAttributionString(MapSnapshot mapSnapshot, boolean shortText) {
|
||||
AttributionParser attributionParser = new AttributionParser.Options(context)
|
||||
.withAttributionData(mapSnapshot.getAttributions())
|
||||
.withCopyrightSign(false)
|
||||
.withImproveMap(false)
|
||||
.build();
|
||||
|
||||
return attributionParser.createAttributionString(shortText);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a scaled logo for a map snapshot.
|
||||
*
|
||||
* @param snapshot the map snapshot where the logo should be placed on
|
||||
* @return the scaled large logo
|
||||
*/
|
||||
private Logo createScaledLogo(@NonNull Bitmap snapshot) {
|
||||
Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R.drawable.maplibre_logo_icon, null);
|
||||
float scale = calculateLogoScale(snapshot, logo);
|
||||
Matrix matrix = new Matrix();
|
||||
matrix.postScale(scale, scale);
|
||||
Bitmap helmet = BitmapFactory.decodeResource(context.getResources(), R.drawable.maplibre_logo_helmet, null);
|
||||
Bitmap large = Bitmap.createBitmap(logo, 0, 0, logo.getWidth(), logo.getHeight(), matrix, true);
|
||||
Bitmap small = Bitmap.createBitmap(helmet, 0, 0, helmet.getWidth(), helmet.getHeight(), matrix, true);
|
||||
return new Logo(large, small, scale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the scale of the logo, only allow downscaling.
|
||||
*
|
||||
* @param snapshot the large of the map snapshot
|
||||
* @param logo the large of the mapbox logo
|
||||
* @return the scale value
|
||||
*/
|
||||
private float calculateLogoScale(Bitmap snapshot, Bitmap logo) {
|
||||
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
|
||||
float widthRatio = displayMetrics.widthPixels / snapshot.getWidth();
|
||||
float heightRatio = displayMetrics.heightPixels / snapshot.getHeight();
|
||||
float prefWidth = logo.getWidth() / widthRatio;
|
||||
float prefHeight = logo.getHeight() / heightRatio;
|
||||
float calculatedScale = Math.min(prefWidth / logo.getWidth(), prefHeight / logo.getHeight()) * 2;
|
||||
if (calculatedScale > 1) {
|
||||
// don't allow over-scaling
|
||||
calculatedScale = 1.0f;
|
||||
} else if (calculatedScale < 0.60f) {
|
||||
// don't scale to low either
|
||||
calculatedScale = 0.60f;
|
||||
}
|
||||
return calculatedScale;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot is ready.
|
||||
* Always called on the origin (main) thread.
|
||||
*
|
||||
* @param snapshot the generated snapshot
|
||||
*/
|
||||
@Keep
|
||||
protected void onSnapshotReady(@NonNull final MapSnapshot snapshot) {
|
||||
new Handler().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (callback != null) {
|
||||
addOverlay(snapshot);
|
||||
callback.onSnapshotReady(snapshot);
|
||||
reset();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot has failed.
|
||||
*
|
||||
* @param reason the exception string
|
||||
*/
|
||||
@Keep
|
||||
protected void onSnapshotFailed(final String reason) {
|
||||
new Handler().post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (errorHandler != null) {
|
||||
errorHandler.onError(reason);
|
||||
reset();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style is ready.
|
||||
*/
|
||||
@Keep
|
||||
protected void onDidFailLoadingStyle(String reason) {
|
||||
onSnapshotFailed(reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style is loaded.
|
||||
*/
|
||||
@Keep
|
||||
protected void onDidFinishLoadingStyle() {
|
||||
if (!fullyLoaded) {
|
||||
fullyLoaded = true;
|
||||
Style.Builder builder = options.getBuilder();
|
||||
if (builder != null) {
|
||||
for (Source source : builder.getSources()) {
|
||||
nativeAddSource(source, source.getNativePtr());
|
||||
}
|
||||
|
||||
for (Style.Builder.LayerWrapper layerWrapper : builder.getLayers()) {
|
||||
if (layerWrapper instanceof Style.Builder.LayerAtWrapper) {
|
||||
addLayerAt(layerWrapper.getLayer(), ((Style.Builder.LayerAtWrapper) layerWrapper).getIndex());
|
||||
} else if (layerWrapper instanceof Style.Builder.LayerAboveWrapper) {
|
||||
addLayerAbove(layerWrapper.getLayer(), ((Style.Builder.LayerAboveWrapper) layerWrapper).getAboveLayer());
|
||||
} else if (layerWrapper instanceof Style.Builder.LayerBelowWrapper) {
|
||||
addLayerBelow(layerWrapper.getLayer(), ((Style.Builder.LayerBelowWrapper) layerWrapper).getBelowLayer());
|
||||
} else {
|
||||
addLayerBelow(layerWrapper.getLayer(), MapboxConstants.LAYER_ID_ANNOTATIONS);
|
||||
}
|
||||
}
|
||||
|
||||
for (Style.Builder.ImageWrapper image : builder.getImages()) {
|
||||
addImage(image.getId(), image.getBitmap(), image.isSdf());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (observer != null) {
|
||||
observer.onDidFinishLoadingStyle();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Layer of a style that is used by a snapshotter
|
||||
*
|
||||
* @param layerId the id of a Layer
|
||||
* @return the Layer object if Layer with layerId exists, null otherwise
|
||||
*/
|
||||
@Nullable
|
||||
public Layer getLayer(@NonNull String layerId) {
|
||||
checkThread();
|
||||
return fullyLoaded ? nativeGetLayer(layerId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Source of a style that is used by a snapshotter
|
||||
*
|
||||
* @param sourceId the id of a Source
|
||||
* @return the Source object if a Source with sourceId exists, null otherwise
|
||||
*/
|
||||
@Nullable
|
||||
public Source getSource(@NonNull String sourceId) {
|
||||
checkThread();
|
||||
return fullyLoaded ? nativeGetSource(sourceId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style image is missing.
|
||||
*/
|
||||
@Keep
|
||||
protected void onStyleImageMissing(String imageName) {
|
||||
if (observer != null) {
|
||||
observer.onStyleImageMissing(imageName);
|
||||
}
|
||||
}
|
||||
|
||||
private void checkThread() {
|
||||
ThreadUtils.checkThread(TAG);
|
||||
}
|
||||
|
||||
protected void reset() {
|
||||
callback = null;
|
||||
errorHandler = null;
|
||||
}
|
||||
|
||||
@Keep
|
||||
protected native void nativeInitialize(MapSnapshotter mapSnapshotter,
|
||||
FileSource fileSource, float pixelRatio,
|
||||
int width, int height, String styleUrl, String styleJson,
|
||||
LatLngBounds region, CameraPosition position,
|
||||
boolean showLogo, String localIdeographFontFamily);
|
||||
|
||||
@Keep
|
||||
protected native void nativeStart();
|
||||
|
||||
@Keep
|
||||
protected native void nativeCancel();
|
||||
|
||||
@Keep
|
||||
private native void nativeAddLayerBelow(long layerPtr, String below);
|
||||
|
||||
@Keep
|
||||
private native void nativeAddLayerAbove(long layerPtr, String above);
|
||||
|
||||
@Keep
|
||||
private native void nativeAddLayerAt(long layerPtr, int index);
|
||||
|
||||
@Keep
|
||||
private native void nativeAddSource(Source source, long sourcePtr);
|
||||
|
||||
@Keep
|
||||
private native void nativeAddImages(Image[] images);
|
||||
|
||||
@NonNull
|
||||
@Keep
|
||||
private native Layer nativeGetLayer(String layerId);
|
||||
|
||||
@NonNull
|
||||
@Keep
|
||||
private native Source nativeGetSource(String sourceId);
|
||||
|
||||
@Override
|
||||
@Keep
|
||||
protected native void finalize() throws Throwable;
|
||||
|
||||
private class Logo {
|
||||
private Bitmap large;
|
||||
private Bitmap small;
|
||||
private float scale;
|
||||
|
||||
Logo(Bitmap large, Bitmap small, float scale) {
|
||||
this.large = large;
|
||||
this.small = small;
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
public Bitmap getLarge() {
|
||||
return large;
|
||||
}
|
||||
|
||||
public Bitmap getSmall() {
|
||||
return small;
|
||||
}
|
||||
|
||||
public float getScale() {
|
||||
return scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,772 @@
|
||||
package com.mapbox.mapboxsdk.snapshotter
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.*
|
||||
import android.os.Handler
|
||||
import android.text.Html
|
||||
import android.text.TextUtils
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.Keep
|
||||
import androidx.annotation.UiThread
|
||||
import androidx.core.content.res.ResourcesCompat
|
||||
import com.mapbox.mapboxsdk.R
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionLayout
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionMeasure
|
||||
import com.mapbox.mapboxsdk.attribution.AttributionParser
|
||||
import com.mapbox.mapboxsdk.camera.CameraPosition
|
||||
import com.mapbox.mapboxsdk.constants.MapboxConstants
|
||||
import com.mapbox.mapboxsdk.geometry.LatLngBounds
|
||||
import com.mapbox.mapboxsdk.log.Logger
|
||||
import com.mapbox.mapboxsdk.maps.Image
|
||||
import com.mapbox.mapboxsdk.maps.Style
|
||||
import com.mapbox.mapboxsdk.maps.Style.Builder.*
|
||||
import com.mapbox.mapboxsdk.storage.FileSource
|
||||
import com.mapbox.mapboxsdk.style.layers.Layer
|
||||
import com.mapbox.mapboxsdk.style.sources.Source
|
||||
import com.mapbox.mapboxsdk.utils.FontUtils
|
||||
import com.mapbox.mapboxsdk.utils.ThreadUtils
|
||||
|
||||
/**
|
||||
* The map snapshotter creates a large of the map, rendered
|
||||
* off the UI thread. The snapshotter itself must be used on
|
||||
* the UI thread (for access to the main looper)
|
||||
*/
|
||||
@UiThread
|
||||
open class MapSnapshotter(context: Context, options: Options) {
|
||||
// Holds the pointer to JNI NativeMapView
|
||||
@Keep
|
||||
private val nativePtr: Long = 0
|
||||
private val context: Context
|
||||
private var fullyLoaded = false
|
||||
private val options: Options
|
||||
private var callback: SnapshotReadyCallback? = null
|
||||
private var errorHandler: ErrorHandler? = null
|
||||
private var observer: Observer? = null
|
||||
|
||||
/**
|
||||
* Get notified on snapshot completion.
|
||||
*
|
||||
* @see MapSnapshotter.start
|
||||
*/
|
||||
interface SnapshotReadyCallback {
|
||||
/**
|
||||
* Called when the snapshot is complete.
|
||||
*
|
||||
* @param snapshot the snapshot
|
||||
*/
|
||||
fun onSnapshotReady(snapshot: MapSnapshot)
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to get notified of errors
|
||||
* in snapshot generation
|
||||
*
|
||||
* @see MapSnapshotter.start
|
||||
*/
|
||||
interface ErrorHandler {
|
||||
/**
|
||||
* Called on error. Snapshotting will not
|
||||
* continue
|
||||
*
|
||||
* @param error the error message
|
||||
*/
|
||||
fun onError(error: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to get notified on snapshotter style loading
|
||||
* completion.
|
||||
*
|
||||
* @see MapSnapshotter.setObserver
|
||||
*/
|
||||
interface Observer {
|
||||
/**
|
||||
* Called when snapshotter finishes loading its style.
|
||||
*/
|
||||
fun onDidFinishLoadingStyle()
|
||||
|
||||
/**
|
||||
* Called when the map is missing an icon.The icon should be added synchronously with
|
||||
* [MapSnapshotter.addImage] to be rendered on the current zoom level.
|
||||
* When loading icons asynchronously, you can load a placeholder image and replace it when you icon has loaded.
|
||||
*
|
||||
* @param imageName the id of the icon that is missing
|
||||
*/
|
||||
fun onStyleImageMissing(imageName: String)
|
||||
}
|
||||
|
||||
/**
|
||||
* MapSnapshotter options
|
||||
*/
|
||||
class Options(width: Int, height: Int) {
|
||||
/**
|
||||
* @return the pixel ratio
|
||||
*/
|
||||
var pixelRatio = 1f
|
||||
private set
|
||||
|
||||
/**
|
||||
* @return the width of the image
|
||||
*/
|
||||
val width: Int
|
||||
|
||||
/**
|
||||
* @return the height of the image
|
||||
*/
|
||||
val height: Int
|
||||
|
||||
/**
|
||||
* @return the region
|
||||
*/
|
||||
var region: LatLngBounds? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* @return the camera position
|
||||
*/
|
||||
var cameraPosition: CameraPosition? = null
|
||||
private set
|
||||
|
||||
var showLogo = true
|
||||
|
||||
/**
|
||||
* @return the font family used for locally generating ideographs,
|
||||
* Default font for local ideograph font family is [MapboxConstants.DEFAULT_FONT].
|
||||
*/
|
||||
var localIdeographFontFamily = MapboxConstants.DEFAULT_FONT
|
||||
private set
|
||||
|
||||
/**
|
||||
* @return The base of our API endpoint
|
||||
*/
|
||||
@get:Deprecated("use {@link #getApiBaseUri()} instead")
|
||||
var apiBaseUri: String? = null
|
||||
private set
|
||||
get() = field
|
||||
|
||||
var builder: Style.Builder? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* @param width the width of the image
|
||||
* @param height the height of the image
|
||||
*/
|
||||
init {
|
||||
require(!(width == 0 || height == 0)) { "Unable to create a snapshot with width or height set to 0" }
|
||||
this.width = width
|
||||
this.height = height
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a style builder to snapshotter, the contents in builder like layers/sources/images will be applied
|
||||
* to snapshotter.
|
||||
*
|
||||
* @param builder The builder will applied to snapshotter
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withStyleBuilder(builder: Style.Builder?): Options {
|
||||
this.builder = builder
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param uri The style URI to use
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
@Deprecated("use {@link #withStyleBuilder(Style.Builder)} instead")
|
||||
fun withStyle(uri: String?): Options {
|
||||
withStyleBuilder(Style.Builder().fromUri(uri!!))
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param styleJson The style json to use
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
@Deprecated("use {@link #withStyleBuilder(Style.Builder)} instead")
|
||||
fun withStyleJson(styleJson: String?): Options {
|
||||
withStyleBuilder(Style.Builder().fromJson(styleJson!!))
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param region the region to show in the snapshot.
|
||||
* This is applied after the camera position
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withRegion(region: LatLngBounds?): Options {
|
||||
this.region = region
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pixelRatio the pixel ratio to use (default: 1)
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withPixelRatio(pixelRatio: Float): Options {
|
||||
this.pixelRatio = pixelRatio
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param cameraPosition The camera position to use,
|
||||
* the [CameraPosition.target] is overridden
|
||||
* by region if set in conjunction.
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withCameraPosition(cameraPosition: CameraPosition?): Options {
|
||||
this.cameraPosition = cameraPosition
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @param showLogo The flag indicating to show the Mapbox logo.
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withLogo(showLogo: Boolean): Options {
|
||||
this.showLogo = showLogo
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the font family for generating glyphs locally for ideographs in the 'CJK Unified Ideographs'
|
||||
* and 'Hangul Syllables' ranges.
|
||||
*
|
||||
*
|
||||
* The font family argument is passed to [android.graphics.Typeface.create].
|
||||
* Default system fonts are defined in '/system/etc/fonts.xml'
|
||||
* Default font for local ideograph font family is [MapboxConstants.DEFAULT_FONT].
|
||||
*
|
||||
*
|
||||
* @param fontFamily font family for local ideograph generation.
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withLocalIdeographFontFamily(fontFamily: String?): Options {
|
||||
localIdeographFontFamily = FontUtils.extractValidFont(fontFamily)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a font family from range of font families for generating glyphs locally for ideographs in the
|
||||
* 'CJK Unified Ideographs' and 'Hangul Syllables' ranges.
|
||||
*
|
||||
*
|
||||
* The font families are checked against the default system fonts defined in
|
||||
* '/system/etc/fonts.xml'. Default font for local ideograph font family is
|
||||
* [MapboxConstants.DEFAULT_FONT].
|
||||
*
|
||||
*
|
||||
* @param fontFamilies font families for local ideograph generation.
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withLocalIdeographFontFamily(vararg fontFamilies: String?): Options {
|
||||
localIdeographFontFamily = FontUtils.extractValidFont(*fontFamilies)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the URL used for API endpoint.
|
||||
*
|
||||
* @param apiBaseUrl The base of our API endpoint
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
@Deprecated("use {@link #withApiBaseUri(String)} instead")
|
||||
fun withApiBaseUrl(apiBaseUrl: String?): Options {
|
||||
apiBaseUri = apiBaseUrl
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the URI used for API endpoint.
|
||||
*
|
||||
* @param apiBaseUri The base of our API endpoint
|
||||
* @return the mutated [Options]
|
||||
*/
|
||||
fun withApiBaseUri(apiBaseUri: String?): Options {
|
||||
this.apiBaseUri = apiBaseUri
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the style url
|
||||
*/
|
||||
@get:Deprecated("use {@link #getStyleUri()} instead")
|
||||
val styleUrl: String?
|
||||
get() = if (builder == null) null else builder!!.uri
|
||||
|
||||
/**
|
||||
* @return the style uri
|
||||
*/
|
||||
val styleUri: String?
|
||||
get() = if (builder == null) null else builder!!.uri
|
||||
|
||||
/**
|
||||
* @return the style json
|
||||
*/
|
||||
val styleJson: String?
|
||||
get() = if (builder == null) null else builder!!.json
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the Map snapshotter, but doesn't start rendering or
|
||||
* loading yet.
|
||||
*
|
||||
* @param context the Context that is or contains the Application context
|
||||
* @param options the options to use for the snapshot
|
||||
*/
|
||||
init {
|
||||
checkThread()
|
||||
this.context = context.applicationContext
|
||||
this.options = options
|
||||
val fileSource = FileSource.getInstance(context)
|
||||
val apiBaseUrl = options.apiBaseUri
|
||||
if (!TextUtils.isEmpty(apiBaseUrl)) {
|
||||
fileSource.setApiBaseUrl(apiBaseUrl)
|
||||
}
|
||||
nativeInitialize(
|
||||
this,
|
||||
fileSource,
|
||||
options.pixelRatio,
|
||||
options.width,
|
||||
options.height,
|
||||
options.styleUri,
|
||||
options.styleJson,
|
||||
options.region,
|
||||
options.cameraPosition,
|
||||
options.showLogo,
|
||||
options.localIdeographFontFamily
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts loading and rendering the snapshot. The callbacks will be fired
|
||||
* on the calling thread.
|
||||
*
|
||||
* @param callback the callback to use when the snapshot is ready
|
||||
* @param errorHandler the error handler to use on snapshot errors
|
||||
*/
|
||||
@JvmOverloads
|
||||
fun start(callback: SnapshotReadyCallback, errorHandler: ErrorHandler? = null) {
|
||||
check(this.callback == null) { "Snapshotter was already started" }
|
||||
checkThread()
|
||||
this.callback = callback
|
||||
this.errorHandler = errorHandler
|
||||
nativeStart()
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new size
|
||||
*
|
||||
* @param width the width
|
||||
* @param height the height
|
||||
*/
|
||||
@Keep
|
||||
external fun setSize(width: Int, height: Int)
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new [CameraPosition]
|
||||
*
|
||||
* @param cameraPosition the camera position
|
||||
*/
|
||||
@Keep
|
||||
external fun setCameraPosition(cameraPosition: CameraPosition?)
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new [LatLngBounds]
|
||||
*
|
||||
* @param region the region
|
||||
*/
|
||||
@Keep
|
||||
external fun setRegion(region: LatLngBounds?)
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new style url
|
||||
*
|
||||
* @param styleUrl the style url
|
||||
*/
|
||||
@Keep
|
||||
external fun setStyleUrl(styleUrl: String?)
|
||||
|
||||
/**
|
||||
* Updates the snapshotter with a new style json
|
||||
*
|
||||
* @param styleJson the style json
|
||||
*/
|
||||
@Keep
|
||||
external fun setStyleJson(styleJson: String?)
|
||||
|
||||
/**
|
||||
* Adds the layer to the map. The layer must be newly created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param below the layer id to add this layer before
|
||||
*/
|
||||
private fun addLayerBelow(layer: Layer, below: String) {
|
||||
nativeAddLayerBelow(layer.nativePtr, below)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the layer to the map. The layer must be newly created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param above the layer id to add this layer above
|
||||
*/
|
||||
private fun addLayerAbove(layer: Layer, above: String) {
|
||||
nativeAddLayerAbove(layer.nativePtr, above)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the layer to the snapshotter at the specified index. The layer must be newly
|
||||
* created and not added to the snapshotter before
|
||||
*
|
||||
* @param layer the layer to add
|
||||
* @param index the index to insert the layer at
|
||||
*/
|
||||
private fun addLayerAt(layer: Layer, index: Int) {
|
||||
nativeAddLayerAt(layer.nativePtr, index)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
private fun addSource(source: Source) {
|
||||
nativeAddSource(source, source.nativePtr)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an image to be used in the snapshotter'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
|
||||
*/
|
||||
fun addImage(name: String, bitmap: Bitmap, sdf: Boolean) {
|
||||
nativeAddImages(arrayOf(Style.toImage(ImageWrapper(name, bitmap, sdf))))
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be called in on the thread
|
||||
* the object was created on.
|
||||
*/
|
||||
fun cancel() {
|
||||
checkThread()
|
||||
reset()
|
||||
nativeCancel()
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets observer for a snapshotter
|
||||
*
|
||||
* @param observer an Observer object
|
||||
*/
|
||||
fun setObserver(observer: Observer?) {
|
||||
checkThread()
|
||||
this.observer = observer
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw an overlay on the map snapshot.
|
||||
*
|
||||
* @param mapSnapshot the map snapshot to draw the overlay on
|
||||
*/
|
||||
protected open fun addOverlay(mapSnapshot: MapSnapshot) {
|
||||
val snapshot = mapSnapshot.bitmap
|
||||
val canvas = Canvas(snapshot!!)
|
||||
val margin = context.resources.displayMetrics.density.toInt() * LOGO_MARGIN_DP
|
||||
drawOverlay(mapSnapshot, snapshot, canvas, margin)
|
||||
}
|
||||
|
||||
private fun drawOverlay(mapSnapshot: MapSnapshot, snapshot: Bitmap, canvas: Canvas, margin: Int) {
|
||||
val measure = getAttributionMeasure(mapSnapshot, snapshot, margin)
|
||||
val layout = measure.measure()
|
||||
drawLogo(mapSnapshot, canvas, margin, layout!!)
|
||||
drawAttribution(mapSnapshot, canvas, measure, layout)
|
||||
}
|
||||
|
||||
private fun getAttributionMeasure(mapSnapshot: MapSnapshot, snapshot: Bitmap, margin: Int): AttributionMeasure {
|
||||
val logo = createScaledLogo(snapshot)
|
||||
val longText = createTextView(mapSnapshot, false, logo.scale)
|
||||
val shortText = createTextView(mapSnapshot, true, logo.scale)
|
||||
return AttributionMeasure.Builder().setSnapshot(snapshot).setLogo(logo.large).setLogoSmall(logo.small).setTextView(longText).setTextViewShort(shortText)
|
||||
.setMarginPadding(margin.toFloat()).build()
|
||||
}
|
||||
|
||||
private fun drawLogo(mapSnapshot: MapSnapshot, canvas: Canvas, margin: Int, layout: AttributionLayout) {
|
||||
if (mapSnapshot.isShowLogo) {
|
||||
drawLogo(mapSnapshot.bitmap, canvas, margin, layout)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawLogo(snapshot: Bitmap, canvas: Canvas, margin: Int, placement: AttributionLayout) {
|
||||
val selectedLogo = placement.logo
|
||||
if (selectedLogo != null) {
|
||||
canvas.drawBitmap(selectedLogo, margin.toFloat(), (snapshot.height - selectedLogo.height - margin).toFloat(), null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawAttribution(mapSnapshot: MapSnapshot, canvas: Canvas, measure: AttributionMeasure, layout: AttributionLayout?) {
|
||||
// draw attribution
|
||||
val anchorPoint = layout!!.anchorPoint
|
||||
if (anchorPoint != null) {
|
||||
drawAttribution(canvas, measure, anchorPoint)
|
||||
} else {
|
||||
val snapshot = mapSnapshot.bitmap
|
||||
Logger.e(
|
||||
TAG,
|
||||
String.format(
|
||||
"Could not generate attribution for snapshot size: %s x %s." + " You are required to provide your own attribution for the used sources: %s",
|
||||
snapshot.width,
|
||||
snapshot.height,
|
||||
mapSnapshot.attributions
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawAttribution(canvas: Canvas, measure: AttributionMeasure, anchorPoint: PointF) {
|
||||
canvas.save()
|
||||
canvas.translate(anchorPoint.x, anchorPoint.y)
|
||||
measure.textView.draw(canvas)
|
||||
canvas.restore()
|
||||
}
|
||||
|
||||
private fun createTextView(mapSnapshot: MapSnapshot, shortText: Boolean, scale: Float): TextView {
|
||||
val textColor = ResourcesCompat.getColor(context.resources, R.color.maplibre_gray_dark, context.theme)
|
||||
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
val textView = TextView(context)
|
||||
textView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
textView.isSingleLine = true
|
||||
textView.textSize = 10 * scale
|
||||
textView.setTextColor(textColor)
|
||||
textView.setBackgroundResource(R.drawable.maplibre_rounded_corner)
|
||||
textView.text = Html.fromHtml(createAttributionString(mapSnapshot, shortText))
|
||||
textView.measure(widthMeasureSpec, heightMeasureSpec)
|
||||
textView.layout(0, 0, textView.measuredWidth, textView.measuredHeight)
|
||||
return textView
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the attribution string.
|
||||
*
|
||||
* @param mapSnapshot the map snapshot to create the attribution for
|
||||
* @param shortText indicates if the short variant of the string should be parsed
|
||||
* @return the parsed attribution string
|
||||
*/
|
||||
private fun createAttributionString(mapSnapshot: MapSnapshot, shortText: Boolean): String {
|
||||
val attributionParser = AttributionParser.Options(context).withAttributionData(*mapSnapshot.attributions).withCopyrightSign(false).withImproveMap(false).build()
|
||||
return attributionParser.createAttributionString(shortText)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a scaled logo for a map snapshot.
|
||||
*
|
||||
* @param snapshot the map snapshot where the logo should be placed on
|
||||
* @return the scaled large logo
|
||||
*/
|
||||
private fun createScaledLogo(snapshot: Bitmap): Logo {
|
||||
val logo = BitmapFactory.decodeResource(context.resources, R.drawable.maplibre_logo_icon, null)
|
||||
val scale = calculateLogoScale(snapshot, logo)
|
||||
val matrix = Matrix()
|
||||
matrix.postScale(scale, scale)
|
||||
val helmet = BitmapFactory.decodeResource(context.resources, R.drawable.maplibre_logo_helmet, null)
|
||||
val large = Bitmap.createBitmap(logo, 0, 0, logo.width, logo.height, matrix, true)
|
||||
val small = Bitmap.createBitmap(helmet, 0, 0, helmet.width, helmet.height, matrix, true)
|
||||
return Logo(large, small, scale)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the scale of the logo, only allow downscaling.
|
||||
*
|
||||
* @param snapshot the large of the map snapshot
|
||||
* @param logo the large of the mapbox logo
|
||||
* @return the scale value
|
||||
*/
|
||||
private fun calculateLogoScale(snapshot: Bitmap, logo: Bitmap): Float {
|
||||
val displayMetrics = context.resources.displayMetrics
|
||||
val widthRatio = (displayMetrics.widthPixels / snapshot.width).toFloat()
|
||||
val heightRatio = (displayMetrics.heightPixels / snapshot.height).toFloat()
|
||||
val prefWidth = logo.width / widthRatio
|
||||
val prefHeight = logo.height / heightRatio
|
||||
var calculatedScale = Math.min(prefWidth / logo.width, prefHeight / logo.height) * 2
|
||||
if (calculatedScale > 1) {
|
||||
// don't allow over-scaling
|
||||
calculatedScale = 1.0f
|
||||
} else if (calculatedScale < 0.60f) {
|
||||
// don't scale to low either
|
||||
calculatedScale = 0.60f
|
||||
}
|
||||
return calculatedScale
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot is ready.
|
||||
* Always called on the origin (main) thread.
|
||||
*
|
||||
* @param snapshot the generated snapshot
|
||||
*/
|
||||
@Keep
|
||||
protected fun onSnapshotReady(snapshot: MapSnapshot) {
|
||||
Handler().post {
|
||||
if (callback != null) {
|
||||
addOverlay(snapshot)
|
||||
callback!!.onSnapshotReady(snapshot)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot has failed.
|
||||
*
|
||||
* @param reason the exception string
|
||||
*/
|
||||
@Keep
|
||||
protected fun onSnapshotFailed(reason: String) {
|
||||
Handler().post {
|
||||
if (errorHandler != null) {
|
||||
errorHandler!!.onError(reason)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style is ready.
|
||||
*/
|
||||
@Keep
|
||||
protected fun onDidFailLoadingStyle(reason: String) {
|
||||
onSnapshotFailed(reason)
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style is loaded.
|
||||
*/
|
||||
@Keep
|
||||
protected fun onDidFinishLoadingStyle() {
|
||||
if (!fullyLoaded) {
|
||||
fullyLoaded = true
|
||||
val builder = options.builder
|
||||
if (builder != null) {
|
||||
for (source in builder.sources) {
|
||||
nativeAddSource(source, source.nativePtr)
|
||||
}
|
||||
for (layerWrapper in builder.layers) {
|
||||
if (layerWrapper is LayerAtWrapper) {
|
||||
addLayerAt(layerWrapper.getLayer(), layerWrapper.index)
|
||||
} else if (layerWrapper is LayerAboveWrapper) {
|
||||
addLayerAbove(layerWrapper.getLayer(), layerWrapper.aboveLayer)
|
||||
} else if (layerWrapper is LayerBelowWrapper) {
|
||||
addLayerBelow(layerWrapper.getLayer(), layerWrapper.belowLayer)
|
||||
} else {
|
||||
addLayerBelow(layerWrapper.layer, MapboxConstants.LAYER_ID_ANNOTATIONS)
|
||||
}
|
||||
}
|
||||
for (image in builder.images) {
|
||||
addImage(image.id, image.bitmap, image.isSdf)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (observer != null) {
|
||||
observer!!.onDidFinishLoadingStyle()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Layer of a style that is used by a snapshotter
|
||||
*
|
||||
* @param layerId the id of a Layer
|
||||
* @return the Layer object if Layer with layerId exists, null otherwise
|
||||
*/
|
||||
fun getLayer(layerId: String): Layer? {
|
||||
checkThread()
|
||||
return if (fullyLoaded) nativeGetLayer(layerId) else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns Source of a style that is used by a snapshotter
|
||||
*
|
||||
* @param sourceId the id of a Source
|
||||
* @return the Source object if a Source with sourceId exists, null otherwise
|
||||
*/
|
||||
fun getSource(sourceId: String): Source? {
|
||||
checkThread()
|
||||
return if (fullyLoaded) nativeGetSource(sourceId) else null
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by JNI peer when snapshot style image is missing.
|
||||
*/
|
||||
@Keep
|
||||
protected fun onStyleImageMissing(imageName: String) {
|
||||
if (observer != null) {
|
||||
observer!!.onStyleImageMissing(imageName)
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkThread() {
|
||||
ThreadUtils.checkThread(TAG)
|
||||
}
|
||||
|
||||
protected fun reset() {
|
||||
callback = null
|
||||
errorHandler = null
|
||||
}
|
||||
|
||||
@Keep
|
||||
protected external fun nativeInitialize(
|
||||
mapSnapshotter: MapSnapshotter?,
|
||||
fileSource: FileSource?,
|
||||
pixelRatio: Float,
|
||||
width: Int,
|
||||
height: Int,
|
||||
styleUrl: String?,
|
||||
styleJson: String?,
|
||||
region: LatLngBounds?,
|
||||
position: CameraPosition?,
|
||||
showLogo: Boolean,
|
||||
localIdeographFontFamily: String?
|
||||
)
|
||||
|
||||
@Keep
|
||||
protected external fun nativeStart()
|
||||
|
||||
@Keep
|
||||
protected external fun nativeCancel()
|
||||
|
||||
@Keep
|
||||
private external fun nativeAddLayerBelow(layerPtr: Long, below: String)
|
||||
|
||||
@Keep
|
||||
private external fun nativeAddLayerAbove(layerPtr: Long, above: String)
|
||||
|
||||
@Keep
|
||||
private external fun nativeAddLayerAt(layerPtr: Long, index: Int)
|
||||
|
||||
@Keep
|
||||
private external fun nativeAddSource(source: Source, sourcePtr: Long)
|
||||
|
||||
@Keep
|
||||
private external fun nativeAddImages(images: Array<Image>)
|
||||
|
||||
@Keep
|
||||
private external fun nativeGetLayer(layerId: String): Layer
|
||||
|
||||
@Keep
|
||||
private external fun nativeGetSource(sourceId: String): Source
|
||||
|
||||
@Keep
|
||||
@Throws(Throwable::class)
|
||||
protected open external fun finalize()
|
||||
|
||||
private inner class Logo internal constructor(val large: Bitmap, val small: Bitmap, val scale: Float)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "Mbgl-MapSnapshotter"
|
||||
private const val LOGO_MARGIN_DP = 4
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
* Contains the Mapbox Maps Android Snapshotter API classes.
|
||||
*/
|
||||
package com.mapbox.mapboxsdk.snapshotter;
|
||||
package com.mapbox.mapboxsdk.snapshotter
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.mapbox.mapboxsdk.testapp.activity.offline
|
||||
|
||||
import android.annotation.TargetApi
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
@@ -77,11 +75,11 @@ class ChangeResourcesCachePathActivity :
|
||||
Toast.makeText(this, "New path: $path", Toast.LENGTH_LONG).show()
|
||||
|
||||
offlineManager.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<out OfflineRegion>?) {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
Logger.i(TAG, "Number of saved offline regions in the new path: ${offlineRegions?.size}")
|
||||
}
|
||||
|
||||
override fun onError(error: String?) {
|
||||
override fun onError(error: String) {
|
||||
Logger.e(TAG, error)
|
||||
}
|
||||
})
|
||||
@@ -90,34 +88,11 @@ class ChangeResourcesCachePathActivity :
|
||||
private fun Context.obtainExternalFilesPaths(): List<String> {
|
||||
val paths = ArrayList<String>()
|
||||
paths.add(this.filesDir.absolutePath)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
|
||||
paths.addAll(obtainExternalFilesPathsKitKat())
|
||||
} else {
|
||||
paths.addAll(obtainExternalFilesPathsLegacy())
|
||||
}
|
||||
paths.addAll(obtainExternalFilesPathsKitKat())
|
||||
paths.add("${File.separator}invalid${File.separator}cache${File.separator}path")
|
||||
return paths
|
||||
}
|
||||
|
||||
private fun Context.obtainExternalFilesPathsLegacy(): List<String> {
|
||||
val postFix =
|
||||
"${File.separator}Android${File.separator}data${File.separator}${this.packageName}${File.separator}files"
|
||||
val paths = ArrayList<String>()
|
||||
val externalStorage = System.getenv("EXTERNAL_STORAGE")
|
||||
val secondaryStorage = System.getenv("SECONDARY_STORAGE")
|
||||
if (externalStorage != null) {
|
||||
paths.add(externalStorage + postFix)
|
||||
}
|
||||
if (secondaryStorage != null) {
|
||||
val secPaths = secondaryStorage.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
|
||||
for (path in secPaths) {
|
||||
paths.add(path + postFix)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.KITKAT)
|
||||
private fun Context.obtainExternalFilesPathsKitKat(): List<String> {
|
||||
val paths = ArrayList<String>()
|
||||
val extDirs = this.getExternalFilesDirs(null)
|
||||
|
||||
@@ -101,8 +101,8 @@ class DeleteRegionActivity :
|
||||
|
||||
private fun loadOfflineRegions() {
|
||||
OfflineManager.getInstance(this).listOfflineRegions(object : ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>) {
|
||||
if (offlineRegions != null && offlineRegions.size > 0) {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
if (offlineRegions != null && offlineRegions.isNotEmpty()) {
|
||||
adapter!!.setOfflineRegions(Arrays.asList(*offlineRegions))
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ class DeleteRegionActivity :
|
||||
return position.toLong()
|
||||
}
|
||||
|
||||
override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
|
||||
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
|
||||
var convertView = convertView
|
||||
val holder: ViewHolder
|
||||
if (convertView == null) {
|
||||
@@ -150,7 +150,7 @@ class DeleteRegionActivity :
|
||||
holder = convertView.tag as ViewHolder
|
||||
}
|
||||
holder.text!!.text = OfflineUtils.convertRegionName(getItem(position).metadata)
|
||||
return convertView
|
||||
return convertView!!
|
||||
}
|
||||
|
||||
internal class ViewHolder {
|
||||
|
||||
@@ -89,10 +89,10 @@ class DownloadRegionActivity : AppCompatActivity(), OfflineRegion.OfflineRegionO
|
||||
definition,
|
||||
byteArrayOf(),
|
||||
object : OfflineManager.CreateOfflineRegionCallback {
|
||||
override fun onCreate(region: OfflineRegion) {
|
||||
logMessage("Region with id ${region.id} created")
|
||||
offlineRegion = region
|
||||
startDownload(region)
|
||||
override fun onCreate(offlineRegion: OfflineRegion) {
|
||||
logMessage("Region with id ${offlineRegion.id} created")
|
||||
this@DownloadRegionActivity.offlineRegion = offlineRegion
|
||||
startDownload(offlineRegion)
|
||||
binding.fab.visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
@@ -181,12 +181,12 @@ class DownloadRegionActivity : AppCompatActivity(), OfflineRegion.OfflineRegionO
|
||||
|
||||
fun deleteOldOfflineRegions(onCompleted: () -> Unit) {
|
||||
offlineManager.listOfflineRegions(object : OfflineManager.ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<out OfflineRegion>) {
|
||||
val count = offlineRegions.size
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
val count = offlineRegions?.size ?: 0
|
||||
var remainingCount = count
|
||||
if (count > 0) {
|
||||
logMessage("Deleting $count old region...")
|
||||
offlineRegions.forEach {
|
||||
offlineRegions?.forEach {
|
||||
it.delete(object : OfflineRegion.OfflineRegionDeleteCallback {
|
||||
override fun onDelete() {
|
||||
Timber.d("Deleted region with id ${it.id}")
|
||||
|
||||
@@ -42,13 +42,13 @@ class MergeOfflineRegionsActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private val onRegionMergedListener = object : OfflineManager.MergeOfflineRegionsCallback {
|
||||
override fun onMerge(offlineRegions: Array<OfflineRegion>) {
|
||||
override fun onMerge(offlineRegions: Array<OfflineRegion>?) {
|
||||
binding.mapView.getMapAsync {
|
||||
it.setStyle(Style.Builder().fromUri(TEST_STYLE))
|
||||
}
|
||||
Toast.makeText(
|
||||
this@MergeOfflineRegionsActivity,
|
||||
String.format("Merged %d regions.", offlineRegions.size),
|
||||
String.format("Merged %d regions.", offlineRegions?.size ?: 0),
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
@@ -69,11 +69,11 @@ class MergeOfflineRegionsActivity : AppCompatActivity() {
|
||||
*/
|
||||
private class MergeCallback(private var activityCallback: OfflineManager.MergeOfflineRegionsCallback?) : OfflineManager.MergeOfflineRegionsCallback {
|
||||
|
||||
override fun onMerge(offlineRegions: Array<out OfflineRegion>?) {
|
||||
override fun onMerge(offlineRegions: Array<OfflineRegion>?) {
|
||||
activityCallback?.onMerge(offlineRegions)
|
||||
}
|
||||
|
||||
override fun onError(error: String?) {
|
||||
override fun onError(error: String) {
|
||||
activityCallback?.onError(error)
|
||||
}
|
||||
|
||||
|
||||
@@ -145,9 +145,9 @@ class OfflineActivity : AppCompatActivity(), DownloadRegionDialogListener {
|
||||
|
||||
// Query the DB asynchronously
|
||||
offlineManager!!.listOfflineRegions(object : ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>) {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
// Check result
|
||||
if (offlineRegions == null || offlineRegions.size == 0) {
|
||||
if (offlineRegions == null || offlineRegions.isEmpty()) {
|
||||
Toast.makeText(
|
||||
this@OfflineActivity,
|
||||
"You have no regions yet.",
|
||||
|
||||
@@ -112,7 +112,7 @@ class UpdateMetadataActivity :
|
||||
|
||||
private fun loadOfflineRegions() {
|
||||
OfflineManager.getInstance(this).listOfflineRegions(object : ListOfflineRegionsCallback {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>) {
|
||||
override fun onList(offlineRegions: Array<OfflineRegion>?) {
|
||||
if (offlineRegions != null && offlineRegions.size > 0) {
|
||||
adapter!!.setOfflineRegions(Arrays.asList(*offlineRegions))
|
||||
}
|
||||
@@ -137,7 +137,7 @@ class UpdateMetadataActivity :
|
||||
}
|
||||
}
|
||||
|
||||
private class OfflineRegionMetadataAdapter internal constructor(private val context: Context) :
|
||||
private class OfflineRegionMetadataAdapter(private val context: Context) :
|
||||
BaseAdapter() {
|
||||
private var offlineRegions: List<OfflineRegion>
|
||||
fun setOfflineRegions(offlineRegions: List<OfflineRegion>) {
|
||||
@@ -157,8 +157,8 @@ class UpdateMetadataActivity :
|
||||
return position.toLong()
|
||||
}
|
||||
|
||||
override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
|
||||
var convertView = convertView
|
||||
override fun getView(position: Int, convertViewParam: View?, parent: ViewGroup): View {
|
||||
var convertView = convertViewParam
|
||||
val holder: ViewHolder
|
||||
if (convertView == null) {
|
||||
holder = ViewHolder()
|
||||
@@ -170,7 +170,7 @@ class UpdateMetadataActivity :
|
||||
holder = convertView.tag as ViewHolder
|
||||
}
|
||||
holder.text!!.text = OfflineUtils.convertRegionName(getItem(position).metadata)
|
||||
return convertView
|
||||
return convertView!!
|
||||
}
|
||||
|
||||
internal class ViewHolder {
|
||||
|
||||
@@ -153,17 +153,22 @@ class RenderTestActivity : AppCompatActivity() {
|
||||
Timber.d("Render test %s,%s", renderTestDefinition.name, renderTestDefinition.category)
|
||||
mapSnapshotter = RenderTestSnapshotter(this, renderTestDefinition.toOptions())
|
||||
mapSnapshotter.start(
|
||||
MapSnapshotter.SnapshotReadyCallback { result: MapSnapshot ->
|
||||
val snapshot = result.bitmap
|
||||
imageView!!.setImageBitmap(snapshot)
|
||||
renderResultMap[renderTestDefinition] = snapshot
|
||||
if (renderResultMap.size != testSize) {
|
||||
continueTesting(renderTestDefinition)
|
||||
} else {
|
||||
finishTesting()
|
||||
object : MapSnapshotter.SnapshotReadyCallback {
|
||||
override fun onSnapshotReady(snapshot: MapSnapshot) {
|
||||
imageView!!.setImageBitmap(snapshot.bitmap)
|
||||
renderResultMap[renderTestDefinition] = snapshot.bitmap
|
||||
if (renderResultMap.size != testSize) {
|
||||
continueTesting(renderTestDefinition)
|
||||
} else {
|
||||
finishTesting()
|
||||
}
|
||||
}
|
||||
},
|
||||
MapSnapshotter.ErrorHandler { error: String? -> Timber.e(error) }
|
||||
object : MapSnapshotter.ErrorHandler {
|
||||
override fun onError(error: String) {
|
||||
Timber.e(error)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -198,6 +198,7 @@ class MapSnapshotterActivity : AppCompatActivity() {
|
||||
}
|
||||
options.withStyleBuilder(builder)
|
||||
val snapshotter = MapSnapshotter(this@MapSnapshotterActivity, options)
|
||||
|
||||
snapshotter.setObserver(object : MapSnapshotter.Observer {
|
||||
override fun onDidFinishLoadingStyle() {
|
||||
Timber.i("onDidFinishLoadingStyle")
|
||||
@@ -209,15 +210,21 @@ class MapSnapshotterActivity : AppCompatActivity() {
|
||||
snapshotter.addImage(imageName, androidIcon!!, false)
|
||||
}
|
||||
})
|
||||
snapshotter.start { snapshot: MapSnapshot ->
|
||||
Timber.i("Got the snapshot")
|
||||
val imageView = ImageView(this@MapSnapshotterActivity)
|
||||
imageView.setImageBitmap(snapshot.bitmap)
|
||||
grid.addView(
|
||||
imageView,
|
||||
GridLayout.LayoutParams(GridLayout.spec(row), GridLayout.spec(column))
|
||||
)
|
||||
}
|
||||
|
||||
snapshotter.start(
|
||||
object : MapSnapshotter.SnapshotReadyCallback {
|
||||
override fun onSnapshotReady(snapshot: MapSnapshot) {
|
||||
Timber.i("Got the snapshot")
|
||||
val imageView = ImageView(this@MapSnapshotterActivity)
|
||||
imageView.setImageBitmap(snapshot.bitmap)
|
||||
grid.addView(
|
||||
imageView,
|
||||
GridLayout.LayoutParams(GridLayout.spec(row), GridLayout.spec(column))
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
snapshotters.add(snapshotter)
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,11 @@ class MapSnapshotterLocalStyleActivity : AppCompatActivity(), MapSnapshotter.Sna
|
||||
)
|
||||
mapSnapshotter!!.start(
|
||||
this@MapSnapshotterLocalStyleActivity,
|
||||
MapSnapshotter.ErrorHandler { error: String? -> Timber.e(error) }
|
||||
object : MapSnapshotter.ErrorHandler {
|
||||
override fun onError(error: String) {
|
||||
Timber.e(error)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.mapbox.mapboxsdk.geometry.LatLng
|
||||
import com.mapbox.mapboxsdk.maps.MapView
|
||||
import com.mapbox.mapboxsdk.maps.MapboxMap
|
||||
import com.mapbox.mapboxsdk.maps.Style
|
||||
import com.mapbox.mapboxsdk.snapshotter.MapSnapshot
|
||||
import com.mapbox.mapboxsdk.snapshotter.MapSnapshotter
|
||||
import com.mapbox.mapboxsdk.style.expressions.Expression.within
|
||||
import com.mapbox.mapboxsdk.style.layers.CircleLayer
|
||||
@@ -37,16 +38,18 @@ class MapSnapshotterWithinExpression : AppCompatActivity() {
|
||||
if (!snapshotInProgress) {
|
||||
snapshotInProgress = true
|
||||
snapshotter.setCameraPosition(mapboxMap.cameraPosition)
|
||||
snapshotter.start {
|
||||
binding.imageView.setImageBitmap(it.bitmap)
|
||||
snapshotInProgress = false
|
||||
}
|
||||
snapshotter.start(object : MapSnapshotter.SnapshotReadyCallback {
|
||||
override fun onSnapshotReady(snapshot: MapSnapshot) {
|
||||
binding.imageView.setImageBitmap(snapshot.bitmap)
|
||||
snapshotInProgress = false
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val snapshotterObserver = object : MapSnapshotter.Observer {
|
||||
override fun onStyleImageMissing(imageName: String?) {
|
||||
override fun onStyleImageMissing(imageName: String) {
|
||||
}
|
||||
|
||||
override fun onDidFinishLoadingStyle() {
|
||||
@@ -73,22 +76,14 @@ class MapSnapshotterWithinExpression : AppCompatActivity() {
|
||||
mapboxMap = map
|
||||
|
||||
// Setup camera position above Georgetown
|
||||
mapboxMap.cameraPosition = CameraPosition.Builder()
|
||||
.target(LatLng(38.90628988399711, -77.06574689337494))
|
||||
.zoom(15.5)
|
||||
.build()
|
||||
mapboxMap.cameraPosition = CameraPosition.Builder().target(LatLng(38.90628988399711, -77.06574689337494)).zoom(15.5).build()
|
||||
|
||||
// Wait for the map to become idle before manipulating the style and camera of the map
|
||||
binding.mapView.addOnDidBecomeIdleListener(object : MapView.OnDidBecomeIdleListener {
|
||||
override fun onDidBecomeIdle() {
|
||||
mapboxMap.easeCamera(
|
||||
CameraUpdateFactory.newCameraPosition(
|
||||
CameraPosition.Builder()
|
||||
.zoom(16.0)
|
||||
.target(LatLng(38.905156245642814, -77.06535338052844))
|
||||
.bearing(80.68015859462369)
|
||||
.tilt(55.0)
|
||||
.build()
|
||||
CameraPosition.Builder().zoom(16.0).target(LatLng(38.905156245642814, -77.06535338052844)).bearing(80.68015859462369).tilt(55.0).build()
|
||||
),
|
||||
1000
|
||||
)
|
||||
@@ -103,74 +98,55 @@ class MapSnapshotterWithinExpression : AppCompatActivity() {
|
||||
private fun setupStyle() {
|
||||
// Assume the route is represented by an array of coordinates.
|
||||
val coordinates = listOf<Point>(
|
||||
Point.fromLngLat(
|
||||
-77.06866264343262,
|
||||
38.90506061276737
|
||||
),
|
||||
Point.fromLngLat(
|
||||
-77.06283688545227,
|
||||
38.905194197410545
|
||||
),
|
||||
Point.fromLngLat(
|
||||
-77.06285834312439,
|
||||
38.906429843444094
|
||||
),
|
||||
Point.fromLngLat(
|
||||
-77.0630407333374,
|
||||
38.90680554236621
|
||||
)
|
||||
Point.fromLngLat(-77.06866264343262, 38.90506061276737),
|
||||
Point.fromLngLat(-77.06283688545227, 38.905194197410545),
|
||||
Point.fromLngLat(-77.06285834312439, 38.906429843444094),
|
||||
Point.fromLngLat(-77.0630407333374, 38.90680554236621)
|
||||
)
|
||||
|
||||
// Setup style with additional layers,
|
||||
// using streets as a base style
|
||||
mapboxMap.setStyle(
|
||||
Style.Builder()
|
||||
.fromUri(Style.getPredefinedStyle("Streets"))
|
||||
Style.Builder().fromUri(Style.getPredefinedStyle("Streets"))
|
||||
) {
|
||||
binding.mapView.addOnCameraDidChangeListener(cameraListener)
|
||||
}
|
||||
|
||||
val options = MapSnapshotter.Options(
|
||||
binding.imageView.measuredWidth / 2,
|
||||
binding.imageView.measuredHeight / 2
|
||||
)
|
||||
val options = MapSnapshotter.Options(binding.imageView.measuredWidth / 2, binding.imageView.measuredHeight / 2)
|
||||
.withCameraPosition(mapboxMap.cameraPosition)
|
||||
.withPixelRatio(2.0f)
|
||||
.withStyleBuilder(
|
||||
Style.Builder()
|
||||
.fromUri(Style.getPredefinedStyle("Streets"))
|
||||
.withSources(
|
||||
GeoJsonSource(
|
||||
POINT_ID,
|
||||
LineString.fromLngLats(coordinates)
|
||||
.withPixelRatio(2.0f).withStyleBuilder(
|
||||
Style.Builder().fromUri(Style.getPredefinedStyle("Streets")).withSources(
|
||||
GeoJsonSource(
|
||||
POINT_ID,
|
||||
LineString.fromLngLats(coordinates)
|
||||
),
|
||||
GeoJsonSource(
|
||||
FILL_ID,
|
||||
FeatureCollection.fromFeature(
|
||||
Feature.fromGeometry(bufferLineStringGeometry())
|
||||
),
|
||||
GeoJsonSource(
|
||||
FILL_ID,
|
||||
FeatureCollection.fromFeature(Feature.fromGeometry(bufferLineStringGeometry())),
|
||||
GeoJsonOptions().withBuffer(0).withTolerance(0.0f)
|
||||
)
|
||||
)
|
||||
.withLayerBelow(
|
||||
LineLayer(LINE_ID, POINT_ID)
|
||||
.withProperties(lineWidth(7.5f), lineColor(Color.LTGRAY)),
|
||||
"poi-label"
|
||||
)
|
||||
.withLayerBelow(
|
||||
CircleLayer(POINT_ID, POINT_ID)
|
||||
.withProperties(
|
||||
circleRadius(7.5f),
|
||||
circleColor(Color.DKGRAY),
|
||||
circleOpacity(0.75f)
|
||||
),
|
||||
"poi-label"
|
||||
).withLayerBelow(
|
||||
FillLayer(FILL_ID, FILL_ID)
|
||||
.withProperties(
|
||||
fillOpacity(0.12f),
|
||||
fillColor(Color.YELLOW)
|
||||
),
|
||||
LINE_ID
|
||||
GeoJsonOptions().withBuffer(0).withTolerance(0.0f)
|
||||
)
|
||||
).withLayerBelow(
|
||||
LineLayer(LINE_ID, POINT_ID).withProperties(
|
||||
lineWidth(7.5f),
|
||||
lineColor(Color.LTGRAY)
|
||||
),
|
||||
"poi-label"
|
||||
).withLayerBelow(
|
||||
CircleLayer(POINT_ID, POINT_ID).withProperties(
|
||||
circleRadius(7.5f),
|
||||
circleColor(Color.DKGRAY),
|
||||
circleOpacity(0.75f)
|
||||
),
|
||||
"poi-label"
|
||||
).withLayerBelow(
|
||||
FillLayer(FILL_ID, FILL_ID).withProperties(
|
||||
fillOpacity(0.12f),
|
||||
fillColor(Color.YELLOW)
|
||||
),
|
||||
LINE_ID
|
||||
)
|
||||
)
|
||||
snapshotter = MapSnapshotter(this, options)
|
||||
snapshotter.setObserver(snapshotterObserver)
|
||||
|
||||
2
platform/android/vendor/maplibre-java
vendored
2
platform/android/vendor/maplibre-java
vendored
Submodule platform/android/vendor/maplibre-java updated: c328d36ab5...b39bdb7262
Reference in New Issue
Block a user