diff options
Diffstat (limited to 'platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk')
88 files changed, 7533 insertions, 6165 deletions
diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/EmptyLocationSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/EmptyLocationSource.java deleted file mode 100644 index 8ea7e61eee..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/EmptyLocationSource.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.mapbox.mapboxsdk; - - -import android.location.Location; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.location.LocationSource; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.android.telemetry.location.LocationEngineListener; - -class EmptyLocationSource extends LocationSource { - - /** - * Activate the location engine which will connect whichever location provider you are using. You'll need to call - * this before requesting user location updates using {@link LocationEngine#requestLocationUpdates()}. - */ - @Override - public void activate() { - // Intentionally left empty - } - - /** - * Disconnect the location engine which is useful when you no longer need location updates or requesting the users - * {@link LocationEngine#getLastLocation()}. Before deactivating, you'll need to stop request user location updates - * using {@link LocationEngine#removeLocationUpdates()}. - */ - @Override - public void deactivate() { - // Intentionally left empty - } - - /** - * Check if your location provider has been activated/connected. This is mainly used internally but is also useful in - * the rare case when you'd like to know if your location engine is connected or not. - * - * @return boolean true if the location engine has been activated/connected, else false. - */ - @Override - public boolean isConnected() { - return false; - } - - /** - * Returns the Last known location is the location provider is connected and location permissions are granted. - * - * @return the last known location - */ - @Override - @Nullable - public Location getLastLocation() { - return null; - } - - /** - * Request location updates to the location provider. - */ - @Override - public void requestLocationUpdates() { - // Intentionally left empty - } - - /** - * Dismiss ongoing location update to the location provider. - */ - @Override - public void removeLocationUpdates() { - // Intentionally left empty - } - - /** - * Invoked when the Location has changed. - * - * @param location the new location - */ - @Override - public void onLocationChanged(Location location) { - // Intentionally left empty - } - - /** - * Useful when you'd like to add a location listener to handle location connections and update events. It is important - * to note, that the callback will continue getting called even when your application isn't in the foreground. - * Therefore, it is a good idea to use {@link LocationEngine#removeLocationEngineListener(LocationEngineListener)} - * inside your activities {@code onStop()} method. - * - * @param listener A {@link LocationEngineListener} which you'd like to add to your location engine. - * @since 2.0.0 - */ - @Override - public void addLocationEngineListener(LocationEngineListener listener) { - // Intentionally left empty - } - - /** - * If you no longer need your {@link LocationEngineListener} to be invoked with every location update, use this - * method to remove it. It's also important to remove your listeners before the activity is destroyed to prevent any - * potential memory leaks. - * - * @param listener the {@link LocationEngineListener} you'd like to remove from this {@link LocationEngine}. - * @return true. - * @since 2.0.0 - */ - @Override - public boolean removeLocationEngineListener(LocationEngineListener listener) { - return true; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoader.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoader.java index a024f0ab70..6633d5d952 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoader.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoader.java @@ -3,18 +3,46 @@ package com.mapbox.mapboxsdk; import timber.log.Timber; /** - * Centralises the knowledge about "mapbox-gl" library loading. + * Loads the mapbox-gl shared library + * <p> + * By default uses the {@link System#loadLibrary(String)}, + * use {@link #setLibraryLoader(LibraryLoader)} to provide an alternative library loading hook. + * </p> */ -public class LibraryLoader { +public abstract class LibraryLoader { + + private static final LibraryLoader DEFAULT = new LibraryLoader() { + @Override + public void load(String name) { + System.loadLibrary(name); + } + }; + + private static volatile LibraryLoader loader = DEFAULT; + + /** + * Set the library loader that loads the shared library. + * + * @param libraryLoader the library loader + */ + public static void setLibraryLoader(LibraryLoader libraryLoader) { + loader = libraryLoader; + } /** * Loads "libmapbox-gl.so" native shared library. + * <p> + * Catches UnsatisfiedLinkErrors and prints a warning to logcat. + * </p> */ public static void load() { try { - System.loadLibrary("mapbox-gl"); + loader.load("mapbox-gl"); } catch (UnsatisfiedLinkError error) { Timber.e(error, "Failed to load native shared library."); } } + + public abstract void load(String name); } + diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/Mapbox.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/Mapbox.java index 357bcd5f99..858c1eed67 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/Mapbox.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/Mapbox.java @@ -10,14 +10,8 @@ import android.text.TextUtils; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.exceptions.MapboxConfigurationException; -import com.mapbox.mapboxsdk.location.LocationSource; +import com.mapbox.mapboxsdk.maps.Telemetry; import com.mapbox.mapboxsdk.net.ConnectivityReceiver; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.android.telemetry.location.LocationEnginePriority; -import com.mapbox.services.android.telemetry.location.LocationEngineProvider; -import com.mapbox.services.android.telemetry.MapboxTelemetry; - -import timber.log.Timber; /** * The entry point to initialize the Mapbox Android SDK. @@ -35,7 +29,6 @@ public final class Mapbox { private Context context; private String accessToken; private Boolean connected; - private LocationEngine locationEngine; /** * Get an instance of Mapbox. @@ -51,27 +44,18 @@ public final class Mapbox { public static synchronized Mapbox getInstance(@NonNull Context context, @NonNull String accessToken) { if (INSTANCE == null) { Context appContext = context.getApplicationContext(); - LocationEngineProvider locationEngineProvider = new LocationEngineProvider(context); - LocationEngine locationEngine = locationEngineProvider.obtainBestLocationEngineAvailable(); - INSTANCE = new Mapbox(appContext, accessToken, locationEngine); - locationEngine.setPriority(LocationEnginePriority.NO_POWER); - - try { - MapboxTelemetry.getInstance().initialize( - appContext, accessToken, BuildConfig.MAPBOX_EVENTS_USER_AGENT, locationEngine); - } catch (Exception exception) { - Timber.e(exception, "Unable to instantiate Mapbox telemetry"); - } + INSTANCE = new Mapbox(appContext, accessToken); + Telemetry.initialize(); ConnectivityReceiver.instance(appContext); } + return INSTANCE; } - Mapbox(@NonNull Context context, @NonNull String accessToken, LocationEngine locationEngine) { + Mapbox(@NonNull Context context, @NonNull String accessToken) { this.context = context; this.accessToken = accessToken; - this.locationEngine = locationEngine; } /** @@ -144,25 +128,4 @@ public final class Mapbox { NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.isConnected()); } - - /** - * Returns a location source instance with empty methods. - * - * @return an empty location source implementation - * @deprecated Replaced by {@link Mapbox#getLocationEngine()} - */ - @Deprecated - public static LocationSource getLocationSource() { - return new EmptyLocationSource(); - } - - - /** - * Returns the location engine used by the SDK. - * - * @return the location engine configured - */ - public static LocationEngine getLocationEngine() { - return INSTANCE.locationEngine; - } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/package-info.java new file mode 100644 index 0000000000..57d840af52 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android Attribution API classes. + */ +package com.mapbox.mapboxsdk.attribution; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraPosition.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraPosition.java index c2f19072db..e732b2525f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraPosition.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraPosition.java @@ -8,7 +8,7 @@ import android.support.annotation.FloatRange; import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.services.android.telemetry.utils.MathUtils; +import com.mapbox.mapboxsdk.utils.MathUtils; /** * Resembles the position, angle, zoom and tilt of the user's viewpoint. diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdateFactory.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdateFactory.java index 50e33f4f9f..8ef0d5b523 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdateFactory.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdateFactory.java @@ -148,6 +148,26 @@ public final class CameraUpdateFactory { return new ZoomUpdate(ZoomUpdate.ZOOM_TO, zoom); } + /** + * Returns a CameraUpdate that moves the camera viewpoint to a particular bearing. + * + * @param bearing Bearing to change to + * @return CameraUpdate Final Camera Position + */ + public static CameraUpdate bearingTo(double bearing) { + return new CameraPositionUpdate(bearing, null, -1, -1); + } + + /** + * Returns a CameraUpdate that moves the camera viewpoint to a particular tilt. + * + * @param tilt Tilt to change to + * @return CameraUpdate Final Camera Position + */ + public static CameraUpdate tiltTo(double tilt) { + return new CameraPositionUpdate(-1, null, tilt, -1); + } + // // CameraUpdate types // diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/GeometryConstants.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/GeometryConstants.java new file mode 100644 index 0000000000..7a17e500ca --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/GeometryConstants.java @@ -0,0 +1,77 @@ +package com.mapbox.mapboxsdk.constants; + +/** + * Contains constants used throughout the sdk classes. + * + * @since 6.0.0 + */ +public class GeometryConstants { + + /** + * The <a href='http://en.wikipedia.org/wiki/Earth_radius#Equatorial_radius'>equatorial radius</a> + * value in meters + * + * @since 6.0.0 + */ + public static final int RADIUS_EARTH_METERS = 6378137; + + /** + * This constant represents the lowest longitude value available to represent a geolocation. + * + * @since 6.0.0 + */ + public static final double MIN_LONGITUDE = -180; + + /** + * This constant represents the highest longitude value available to represent a geolocation. + * + * @since 6.0.0 + */ + public static final double MAX_LONGITUDE = 180; + + /** + * This constant represents the lowest latitude value available to represent a geolocation. + * + * @since 6.0.0 + */ + public static final double MIN_LATITUDE = -90; + + /** + * This constant represents the latitude span when representing a geolocation. + * + * @since 6.0.0 + */ + public static final double LATITUDE_SPAN = 180; + + /** + * This constant represents the longitude span when representing a geolocation. + * + * @since 6.0.0 + */ + public static final double LONGITUDE_SPAN = 360; + + /** + * This constant represents the highest latitude value available to represent a geolocation. + * + * @since 6.0.0 + */ + public static final double MAX_LATITUDE = 90; + + /** + * Maximum latitude value in Mercator projection. + * + * @since 6.0.0 + */ + public static final double MAX_MERCATOR_LATITUDE = 85.05112877980659; + + /** + * Minimum latitude value in Mercator projection. + * + * @since 6.0.0 + */ + public static final double MIN_MERCATOR_LATITUDE = -85.05112877980659; + + private GeometryConstants() { + // Private constructor to prevent initializing of this class. + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MapboxConstants.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MapboxConstants.java index 60362dd2e9..640c70282c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MapboxConstants.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MapboxConstants.java @@ -48,6 +48,31 @@ public class MapboxConstants { public static final long VELOCITY_THRESHOLD_IGNORE_FLING = 1000; /** + * Value by which the default rotation threshold will be increased when scaling + */ + public static final float ROTATION_THRESHOLD_INCREASE_WHEN_SCALING = 25f; + + /** + * Time within which user needs to lift fingers for velocity animation to start. + */ + public static final long SCHEDULED_ANIMATION_TIMEOUT = 150L; + + /** + * Minimum angular velocity for rotation animation + */ + public static final float MINIMUM_ANGULAR_VELOCITY = 1.5f; + + /** + * Maximum angular velocity for rotation animation + */ + public static final float MAXIMUM_ANGULAR_VELOCITY = 20f; + + /** + * Factor to calculate tilt change based on pixel change during shove gesture. + */ + public static final float SHOVE_PIXEL_CHANGE_FACTOR = 0.1f; + + /** * The currently supported minimum zoom level. */ public static final float MINIMUM_ZOOM = 0.0f; @@ -78,14 +103,14 @@ public class MapboxConstants { public static final double MINIMUM_DIRECTION = 0; /** - * The currently used minimun scale factor to clamp to when a quick zoom gesture occurs + * The currently used minimum scale factor to clamp to when a quick zoom gesture occurs */ public static final float MINIMUM_SCALE_FACTOR_CLAMP = 0.00f; /** * The currently used maximum scale factor to clamp to when a quick zoom gesture occurs */ - public static final float MAXIMUM_SCALE_FACTOR_CLAMP = 0.45f; + public static final float MAXIMUM_SCALE_FACTOR_CLAMP = 0.15f; /** * Fragment Argument Key for MapboxMapOptions @@ -96,23 +121,13 @@ public class MapboxConstants { public static final String STATE_HAS_SAVED_STATE = "mapbox_savedState"; public static final String STATE_CAMERA_POSITION = "mapbox_cameraPosition"; public static final String STATE_ZOOM_ENABLED = "mapbox_zoomEnabled"; - public static final String STATE_ZOOM_ENABLED_CHANGE = "mapbox_zoomEnabledChange"; public static final String STATE_SCROLL_ENABLED = "mapbox_scrollEnabled"; - public static final String STATE_SCROLL_ENABLED_CHANGE = "mapbox_scrollEnabledChange"; public static final String STATE_ROTATE_ENABLED = "mapbox_rotateEnabled"; - public static final String STATE_ROTATE_ENABLED_CHANGE = "mapbox_rotateEnabledChange"; public static final String STATE_TILT_ENABLED = "mapbox_tiltEnabled"; - public static final String STATE_TILT_ENABLED_CHANGE = "mapbox_tiltEnabledChange"; public static final String STATE_ZOOM_CONTROLS_ENABLED = "mapbox_zoomControlsEnabled"; public static final String STATE_DOUBLE_TAP_ENABLED = "mapbox_doubleTapEnabled"; - public static final String STATE_DOUBLE_TAP_ENABLED_CHANGE = "mapbox_doubleTapEnabledChange"; public static final String STATE_DEBUG_ACTIVE = "mapbox_debugActive"; public static final String STATE_STYLE_URL = "mapbox_styleUrl"; - public static final String STATE_MY_LOCATION_ENABLED = "mapbox_myLocationEnabled"; - public static final String STATE_MY_LOCATION_TRACKING_MODE = "mapbox_myLocationTracking"; - public static final String STATE_MY_BEARING_TRACKING_MODE = "mapbox_myBearingTracking"; - public static final String STATE_MY_LOCATION_TRACKING_DISMISS = "mapbox_myLocationTrackingDismiss"; - public static final String STATE_MY_BEARING_TRACKING_DISMISS = "mapbox_myBearingTrackingDismiss"; public static final String STATE_COMPASS_ENABLED = "mapbox_compassEnabled"; public static final String STATE_COMPASS_GRAVITY = "mapbox_compassGravity"; public static final String STATE_COMPASS_MARGIN_LEFT = "mapbox_compassMarginLeft"; @@ -133,20 +148,12 @@ public class MapboxConstants { public static final String STATE_ATTRIBUTION_MARGIN_RIGHT = "mapbox_attrMarginRight"; public static final String STATE_ATTRIBUTION_MARGIN_BOTTOM = "mapbox_atrrMarginBottom"; public static final String STATE_ATTRIBUTION_ENABLED = "mapbox_atrrEnabled"; - public static final String STATE_LOCATION_CHANGE_ANIMATION_ENABLED = "mapbox_locationChangeAnimationEnabled"; - public static final String STATE_USING_CUSTOM_LOCATION_SOURCE = "mapbox_usingCustomLocationSource"; - public static final String STATE_LOCATION_VIEW_ENABLED = "mapbox_locViewEnabled"; - public static final String STATE_LOCATION_VIEW_FOREGROUND_DRAWABLE = "mapbox_locViewForegroundDrawable"; - public static final String STATE_LOCATION_VIEW_FOREGROUND_BEARING_DRAWABLE = "mapbox_locViewBearingDrawable"; - public static final String STATE_LOCATION_VIEW_FOREGROUND_TINT_COLOR = "mapbox_locViewForegroundTintColor"; - public static final String STATE_LOCATION_VIEW_BACKGROUND_DRAWABLE = "mapbox_locViewBackgroundDrawable"; - public static final String STATE_LOCATION_VIEW_BACKGROUND_OFFSET = "mapbox_locViewBackgroundOffset"; - public static final String STATE_LOCATION_VIEW_BACKGROUND_TINT_COLOR = "mapbox_locViewBackgroundTintColor"; - public static final String STATE_LOCATION_VIEW_ACCURACY_ALPHA = "mapbox_locViewAccuracyAlpha"; - public static final String STATE_LOCATION_VIEW_ACCURACY_TINT_COLOR = "mapbox_locViewAccuracyTintColor"; - public static final String STATE_LOCATION_VIEW_ACCURACY_THRESHOLD = "mapbox_locViewAccuracyThreshold"; - public static final String STATE_LOCATION_VIEW_PADDING = "mapbox_locViewPadding"; public static final String STATE_DESELECT_MARKER_ON_TAP = "mapbox_deselectMarkerOnTap"; public static final String STATE_USER_FOCAL_POINT = "mapbox_userFocalPoint"; + public static final String STATE_SCALE_ANIMATION_ENABLED = "mapbox_scaleAnimationEnabled"; + public static final String STATE_ROTATE_ANIMATION_ENABLED = "mapbox_rotateAnimationEnabled"; + public static final String STATE_FLING_ANIMATION_ENABLED = "mapbox_flingAnimationEnabled"; + public static final String STATE_INCREASE_ROTATE_THRESHOLD = "mapbox_increaseRotateThreshold"; + public static final String STATE_INCREASE_SCALE_THRESHOLD = "mapbox_increaseScaleThreshold"; } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyBearingTracking.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyBearingTracking.java deleted file mode 100644 index c042b00577..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyBearingTracking.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -import android.support.annotation.IntDef; - -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationView; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * MyBearingTracking exposes different types of bearing tracking modes. - * <p> - * These modes visualise the user direction by extracting the direction from either sensor or location data. - * </p> - * <p> - * Required to enable showing the user location first through {@link MapboxMap#setMyLocationEnabled(boolean)}. - * </p> - * - * @see com.mapbox.mapboxsdk.maps.TrackingSettings#setMyBearingTrackingMode(int) - * @see MyLocationView#setMyBearingTrackingMode(int) - */ -public class MyBearingTracking { - - @IntDef( {NONE, COMPASS, GPS, GPS_NORTH_FACING}) - @Retention(RetentionPolicy.SOURCE) - public @interface Mode { - } - - /** - * Bearing tracking is disabled - */ - public static final int NONE = 0x00000000; - - /** - * Tracking the bearing of the user based on sensor data - */ - public static final int COMPASS = 0x00000004; - - /** - * Tracking the bearing of the user based on GPS data - */ - public static final int GPS = 0x00000008; - - /** - * Tracking the bearing of the user based on GPS data, but camera always faces north direction - */ - public static final int GPS_NORTH_FACING = 0x0000000B; - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyLocationTracking.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyLocationTracking.java deleted file mode 100644 index 1283283fa5..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MyLocationTracking.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -import android.support.annotation.IntDef; - -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.TrackingSettings; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationView; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * MyLocationTracking exposes types of location tracking modes. - * * <p> - * This allows tracking the user location on screen by updating the camera position when a location update occurs. - * </p> - * <p> - * Required to enable showing the user location first through {@link MapboxMap#setMyLocationEnabled(boolean)}. - * </p> - * - * @see MapboxMap#setMyLocationEnabled(boolean) - * @see TrackingSettings#setMyLocationTrackingMode(int) - */ -public class MyLocationTracking { - - @IntDef( {TRACKING_NONE, TRACKING_FOLLOW}) - @Retention(RetentionPolicy.SOURCE) - public @interface Mode { - } - - /** - * Tracking the location of the user is disabled. - */ - public static final int TRACKING_NONE = 0x00000000; - - /** - * Tracking the location of the user. {@link MapView} will reposition to center of {@link MyLocationView} - */ - public static final int TRACKING_FOLLOW = 0x00000004; - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLng.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLng.java index eb57241196..79023e2fd9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLng.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLng.java @@ -5,8 +5,8 @@ import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.FloatRange; -import com.mapbox.services.android.telemetry.constants.GeoConstants; -import com.mapbox.services.android.telemetry.utils.MathUtils; +import com.mapbox.mapboxsdk.constants.GeometryConstants; + /** * A geographical location which contains a single latitude, longitude pair, with @@ -105,20 +105,20 @@ public class LatLng implements ILatLng, Parcelable { /** * Set the latitude, in degrees. * <p> - * This value is in the range of [-85.05112878, 85.05112878], see {@link GeoConstants#MIN_LATITUDE} and - * {@link GeoConstants#MAX_LATITUDE} + * This value is in the range of [-90, 90], see {@link GeometryConstants#MIN_LATITUDE} and + * {@link GeometryConstants#MAX_LATITUDE} * </p> * * @param latitude the latitude value in degrees - * @see GeoConstants#MIN_LATITUDE - * @see GeoConstants#MAX_LATITUDE + * @see GeometryConstants#MIN_LATITUDE + * @see GeometryConstants#MAX_LATITUDE */ public void setLatitude( - @FloatRange(from = GeoConstants.MIN_LATITUDE, to = GeoConstants.MAX_LATITUDE) double latitude) { + @FloatRange(from = GeometryConstants.MIN_LATITUDE, to = GeometryConstants.MAX_LATITUDE) double latitude) { if (Double.isNaN(latitude)) { throw new IllegalArgumentException("latitude must not be NaN"); } - if (Math.abs(latitude) > 90.0) { + if (Math.abs(latitude) > GeometryConstants.MAX_LATITUDE) { throw new IllegalArgumentException("latitude must be between -90 and 90"); } this.latitude = latitude; @@ -127,13 +127,13 @@ public class LatLng implements ILatLng, Parcelable { /** * Get the latitude, in degrees. * <p> - * This value is in the range of [-85.05112878, 85.05112878], see {@link GeoConstants#MIN_LATITUDE} and - * {@link GeoConstants#MAX_LATITUDE} + * This value is in the range of [-90, 90], see {@link GeometryConstants#MIN_LATITUDE} and + * {@link GeometryConstants#MAX_LATITUDE} * </p> * * @return the latitude value in degrees - * @see GeoConstants#MIN_LATITUDE - * @see GeoConstants#MAX_LATITUDE + * @see GeometryConstants#MIN_LATITUDE + * @see GeometryConstants#MAX_LATITUDE */ @Override public double getLatitude() { @@ -143,15 +143,15 @@ public class LatLng implements ILatLng, Parcelable { /** * Set the longitude, in degrees. * <p> - * This value is in the range of [-180, 180], see {@link GeoConstants#MIN_LONGITUDE} and - * {@link GeoConstants#MAX_LONGITUDE} + * This value is in the range of [-180, 180], see {@link GeometryConstants#MIN_LONGITUDE} and + * {@link GeometryConstants#MAX_LONGITUDE} * </p> * * @param longitude the longitude value in degrees - * @see GeoConstants#MIN_LONGITUDE - * @see GeoConstants#MAX_LONGITUDE + * @see GeometryConstants#MIN_LONGITUDE + * @see GeometryConstants#MAX_LONGITUDE */ - public void setLongitude(@FloatRange(from = GeoConstants.MIN_LONGITUDE, to = GeoConstants.MAX_LONGITUDE) + public void setLongitude(@FloatRange(from = GeometryConstants.MIN_LONGITUDE, to = GeometryConstants.MAX_LONGITUDE) double longitude) { if (Double.isNaN(longitude)) { throw new IllegalArgumentException("longitude must not be NaN"); @@ -165,13 +165,13 @@ public class LatLng implements ILatLng, Parcelable { /** * Get the longitude, in degrees. * <p> - * This value is in the range of [-180, 180], see {@link GeoConstants#MIN_LONGITUDE} and - * {@link GeoConstants#MAX_LONGITUDE} + * This value is in the range of [-180, 180], see {@link GeometryConstants#MIN_LONGITUDE} and + * {@link GeometryConstants#MAX_LONGITUDE} * </p> * * @return the longitude value in degrees - * @see GeoConstants#MIN_LONGITUDE - * @see GeoConstants#MAX_LONGITUDE + * @see GeometryConstants#MIN_LONGITUDE + * @see GeometryConstants#MAX_LONGITUDE */ @Override public double getLongitude() { @@ -204,8 +204,33 @@ public class LatLng implements ILatLng, Parcelable { * @return new LatLng object with wrapped Longitude */ public LatLng wrap() { - longitude = MathUtils.wrap(longitude, GeoConstants.MIN_LONGITUDE, GeoConstants.MAX_LONGITUDE); - return this; + return new LatLng(latitude, wrap(longitude, GeometryConstants.MIN_LONGITUDE, GeometryConstants.MAX_LONGITUDE)); + } + + + /** + * Constrains value to the given range (including min & max) via modular arithmetic. + * <p> + * Same formula as used in Core GL (wrap.hpp) + * std::fmod((std::fmod((value - min), d) + d), d) + min; + * + * Multiples of max value will be wrapped to max. + * + * @param value Value to wrap + * @param min Minimum value + * @param max Maximum value + * @return Wrapped value + */ + static double wrap(double value, double min, double max) { + double delta = max - min; + + double firstMod = (value - min) % delta; + double secondMod = (firstMod + delta) % delta; + + if (value >= max && secondMod == 0) { + return max; + } + return secondMod + min; } /** @@ -305,6 +330,6 @@ public class LatLng implements ILatLng, Parcelable { final double t3 = Math.sin(a1) * Math.sin(b1); final double tt = Math.acos(t1 + t2 + t3); - return GeoConstants.RADIUS_EARTH_METERS * tt; + return GeometryConstants.RADIUS_EARTH_METERS * tt; } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngBounds.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngBounds.java index 4fcb91033c..90cb56f605 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngBounds.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngBounds.java @@ -2,11 +2,12 @@ package com.mapbox.mapboxsdk.geometry; import android.os.Parcel; import android.os.Parcelable; +import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import com.mapbox.mapboxsdk.constants.GeometryConstants; import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException; -import com.mapbox.services.android.telemetry.constants.GeoConstants; import java.util.ArrayList; import java.util.List; @@ -27,6 +28,10 @@ public class LatLngBounds implements Parcelable { /** * Construct a new LatLngBounds based on its corners, given in NESW * order. + * <p> + * If eastern longitude is smaller than the western one, bounds will include antimeridian. + * For example, if the NE point is (10, -170) and the SW point is (-10, 170), then bounds will span over 20 degrees + * and cross the antimeridian. * * @param northLatitude Northern Latitude * @param eastLongitude Eastern Longitude @@ -47,10 +52,9 @@ public class LatLngBounds implements Parcelable { * @return the bounds representing the world */ public static LatLngBounds world() { - return new LatLngBounds.Builder() - .include(new LatLng(GeoConstants.MAX_LATITUDE, GeoConstants.MAX_LONGITUDE)) - .include(new LatLng(GeoConstants.MIN_LATITUDE, GeoConstants.MIN_LONGITUDE)) - .build(); + return LatLngBounds.from( + GeometryConstants.MAX_LATITUDE, GeometryConstants.MAX_LONGITUDE, + GeometryConstants.MIN_LATITUDE, GeometryConstants.MIN_LONGITUDE); } /** @@ -60,8 +64,20 @@ public class LatLngBounds implements Parcelable { * @return LatLng center of this LatLngBounds */ public LatLng getCenter() { - return new LatLng((this.latitudeNorth + this.latitudeSouth) / 2, - (this.longitudeEast + this.longitudeWest) / 2); + double latCenter = (this.latitudeNorth + this.latitudeSouth) / 2.0; + double longCenter; + + if (this.longitudeEast >= this.longitudeWest) { + longCenter = (this.longitudeEast + this.longitudeWest) / 2; + } else { + double halfSpan = (GeometryConstants.LONGITUDE_SPAN + this.longitudeEast - this.longitudeWest) / 2.0; + longCenter = this.longitudeWest + halfSpan; + if (longCenter >= GeometryConstants.MAX_LONGITUDE) { + longCenter = this.longitudeEast - halfSpan; + } + } + + return new LatLng(latCenter, longCenter); } /** @@ -162,9 +178,24 @@ public class LatLngBounds implements Parcelable { * @return Span distance */ public double getLongitudeSpan() { - return Math.abs(this.longitudeEast - this.longitudeWest); + double longSpan = Math.abs(this.longitudeEast - this.longitudeWest); + if (this.longitudeEast >= this.longitudeWest) { + return longSpan; + } + + // shortest span contains antimeridian + return GeometryConstants.LONGITUDE_SPAN - longSpan; } + static double getLongitudeSpan(final double longEast, final double longWest) { + double longSpan = Math.abs(longEast - longWest); + if (longEast >= longWest) { + return longSpan; + } + + // shortest span contains antimeridian + return GeometryConstants.LONGITUDE_SPAN - longSpan; + } /** * Validate if LatLngBounds is empty, determined if absolute distance is @@ -194,22 +225,45 @@ public class LatLngBounds implements Parcelable { * @return LatLngBounds */ static LatLngBounds fromLatLngs(final List<? extends ILatLng> latLngs) { - double minLat = 90; - double minLon = 180; - double maxLat = -90; - double maxLon = -180; + double minLat = GeometryConstants.MAX_LATITUDE; + double maxLat = GeometryConstants.MIN_LATITUDE; + + double eastLon = latLngs.get(0).getLongitude(); + double westLon = latLngs.get(1).getLongitude(); + double lonSpan = Math.abs(eastLon - westLon); + if (lonSpan < GeometryConstants.LONGITUDE_SPAN / 2) { + if (eastLon < westLon) { + double temp = eastLon; + eastLon = westLon; + westLon = temp; + } + } else { + lonSpan = GeometryConstants.LONGITUDE_SPAN - lonSpan; + if (westLon < eastLon) { + double temp = eastLon; + eastLon = westLon; + westLon = temp; + } + } for (final ILatLng gp : latLngs) { final double latitude = gp.getLatitude(); - final double longitude = gp.getLongitude(); - minLat = Math.min(minLat, latitude); - minLon = Math.min(minLon, longitude); maxLat = Math.max(maxLat, latitude); - maxLon = Math.max(maxLon, longitude); + + final double longitude = gp.getLongitude(); + if (!containsLongitude(eastLon, westLon, longitude)) { + final double eastSpan = getLongitudeSpan(longitude, westLon); + final double westSpan = getLongitudeSpan(eastLon, longitude); + if (eastSpan <= westSpan) { + eastLon = longitude; + } else { + westLon = longitude; + } + } } - return new LatLngBounds(maxLat, maxLon, minLat, minLon); + return new LatLngBounds(maxLat, eastLon, minLat, westLon); } /** @@ -224,13 +278,73 @@ public class LatLngBounds implements Parcelable { /** * Constructs a LatLngBounds from doubles representing a LatLng pair. * <p> + * This values of latNorth and latSouth should be in the range of [-90, 90], + * see {@link GeometryConstants#MIN_LATITUDE} and {@link GeometryConstants#MAX_LATITUDE}, + * otherwise IllegalArgumentException will be thrown. + * latNorth should be greater or equal latSouth, otherwise IllegalArgumentException will be thrown. + * <p> * This method doesn't recalculate most east or most west boundaries. + * Note that lonEast and lonWest will be wrapped to be in the range of [-180, 180], + * see {@link GeometryConstants#MIN_LONGITUDE} and {@link GeometryConstants#MAX_LONGITUDE} * </p> */ - public static LatLngBounds from(double latNorth, double lonEast, double latSouth, double lonWest) { + public static LatLngBounds from( + @FloatRange(from = GeometryConstants.MIN_LATITUDE, to = GeometryConstants.MAX_LATITUDE) double latNorth, + double lonEast, + @FloatRange(from = GeometryConstants.MIN_LATITUDE, to = GeometryConstants.MAX_LATITUDE) double latSouth, + double lonWest) { + + if (Double.isNaN(latNorth) || Double.isNaN(latSouth)) { + throw new IllegalArgumentException("latitude must not be NaN"); + } + + if (Double.isNaN(lonEast) || Double.isNaN(lonWest)) { + throw new IllegalArgumentException("longitude must not be NaN"); + } + + if (Double.isInfinite(lonEast) || Double.isInfinite(lonWest)) { + throw new IllegalArgumentException("longitude must not be infinite"); + } + + if (latNorth > GeometryConstants.MAX_LATITUDE || latNorth < GeometryConstants.MIN_LATITUDE + || latSouth > GeometryConstants.MAX_LATITUDE || latSouth < GeometryConstants.MIN_LATITUDE) { + throw new IllegalArgumentException("latitude must be between -90 and 90"); + } + + if (latNorth < latSouth) { + throw new IllegalArgumentException("LatSouth cannot be less than latNorth"); + } + + lonEast = LatLng.wrap(lonEast, GeometryConstants.MIN_LONGITUDE, GeometryConstants.MAX_LONGITUDE); + lonWest = LatLng.wrap(lonWest, GeometryConstants.MIN_LONGITUDE, GeometryConstants.MAX_LONGITUDE); + return new LatLngBounds(latNorth, lonEast, latSouth, lonWest); } + private static double lat_(int z, int y) { + double n = Math.PI - 2.0 * Math.PI * y / Math.pow(2.0, z); + return Math.toDegrees(Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))); + } + + private static double lon_(int z, int x) { + return x / Math.pow(2.0, z) * 360.0 - GeometryConstants.MAX_LONGITUDE; + } + + /** + * Constructs a LatLngBounds from a Tile identifier. + * <p> + * Returned bounds will have latitude in the range of Mercator projection. + * + * @param z Tile zoom level. + * @param x Tile X coordinate. + * @param y Tile Y coordinate. + * @see GeometryConstants#MIN_MERCATOR_LATITUDE + * @see GeometryConstants#MAX_MERCATOR_LATITUDE + */ + public static LatLngBounds from(int z, int x, int y) { + return new LatLngBounds(lat_(z, y), lon_(z, x + 1), lat_(z, y + 1), lon_(z, x)); + } + /** * Constructs a LatLngBounds from current bounds with an additional latitude-longitude pair. * @@ -266,6 +380,24 @@ public class LatLngBounds implements Parcelable { return false; } + + private boolean containsLatitude(final double latitude) { + return (latitude <= this.latitudeNorth) + && (latitude >= this.latitudeSouth); + } + + private boolean containsLongitude(final double longitude) { + return containsLongitude(this.longitudeEast, this.longitudeWest, longitude); + } + + static boolean containsLongitude(final double eastLon, final double westLon, final double longitude) { + if (eastLon >= westLon) { + return (longitude <= eastLon) + && (longitude >= westLon); + } + return (longitude < eastLon) || (longitude > westLon); + } + /** * Determines whether this LatLngBounds contains a point. * @@ -273,12 +405,8 @@ public class LatLngBounds implements Parcelable { * @return true, if the point is contained within the bounds */ public boolean contains(final ILatLng latLng) { - final double latitude = latLng.getLatitude(); - final double longitude = latLng.getLongitude(); - return ((latitude <= this.latitudeNorth) - && (latitude >= this.latitudeSouth)) - && ((longitude <= this.longitudeEast) - && (longitude >= this.longitudeWest)); + return containsLatitude(latLng.getLatitude()) + && containsLongitude(latLng.getLongitude()); } /** @@ -288,7 +416,8 @@ public class LatLngBounds implements Parcelable { * @return true, if the bounds is contained within the bounds */ public boolean contains(final LatLngBounds other) { - return contains(other.getNorthEast()) && contains(other.getSouthWest()); + return contains(other.getNorthEast()) + && contains(other.getSouthWest()); } /** @@ -305,17 +434,28 @@ public class LatLngBounds implements Parcelable { * Returns a new LatLngBounds that stretches to include another LatLngBounds, * given by corner points. * - * @param lonNorth Northern Longitude - * @param latEast Eastern Latitude - * @param lonSouth Southern Longitude - * @param latWest Western Longitude + * @param latNorth Northern Latitude + * @param lonEast Eastern Longitude + * @param latSouth Southern Latitude + * @param lonWest Western Longitude * @return BoundingBox */ - public LatLngBounds union(final double lonNorth, final double latEast, final double lonSouth, final double latWest) { - return new LatLngBounds((this.latitudeNorth < lonNorth) ? lonNorth : this.latitudeNorth, - (this.longitudeEast < latEast) ? latEast : this.longitudeEast, - (this.latitudeSouth > lonSouth) ? lonSouth : this.latitudeSouth, - (this.longitudeWest > latWest) ? latWest : this.longitudeWest); + public LatLngBounds union(final double latNorth, final double lonEast, final double latSouth, final double lonWest) { + double north = (this.latitudeNorth < latNorth) ? latNorth : this.latitudeNorth; + double south = (this.latitudeSouth > latSouth) ? latSouth : this.latitudeSouth; + + if (LatLngSpan.getLongitudeSpan(lonEast, this.longitudeWest) + < LatLngSpan.getLongitudeSpan(this.longitudeEast, lonWest)) { + return new LatLngBounds(north, + lonEast, + south, + this.longitudeWest); + } + + return new LatLngBounds(north, + this.longitudeEast, + south, + lonWest); } /** @@ -326,13 +466,13 @@ public class LatLngBounds implements Parcelable { */ @Nullable public LatLngBounds intersect(LatLngBounds box) { - double minLatWest = Math.max(getLonWest(), box.getLonWest()); - double maxLatEast = Math.min(getLonEast(), box.getLonEast()); - if (maxLatEast > minLatWest) { - double minLonSouth = Math.max(getLatSouth(), box.getLatSouth()); - double maxLonNorth = Math.min(getLatNorth(), box.getLatNorth()); - if (maxLonNorth > minLonSouth) { - return new LatLngBounds(maxLonNorth, maxLatEast, minLonSouth, minLatWest); + double minLonWest = Math.max(getLonWest(), box.getLonWest()); + double maxLonEast = Math.min(getLonEast(), box.getLonEast()); + if (maxLonEast > minLonWest) { + double minLatSouth = Math.max(getLatSouth(), box.getLatSouth()); + double maxLatNorth = Math.min(getLatNorth(), box.getLatNorth()); + if (maxLatNorth > minLatSouth) { + return new LatLngBounds(maxLatNorth, maxLonEast, minLatSouth, minLonWest); } } return null; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngSpan.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngSpan.java index 322c7dfb74..133949f743 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngSpan.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngSpan.java @@ -4,6 +4,8 @@ import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; +import com.mapbox.mapboxsdk.constants.GeometryConstants; + /** * A geographical span defined by its latitude and longitude span. */ @@ -136,4 +138,20 @@ public class LatLngSpan implements Parcelable { result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } + + /** + * Get the absolute distance, in degrees, between the west and + * east boundaries of this LatLngBounds + * + * @return Span distance + */ + static double getLongitudeSpan(double east, double west) { + double longSpan = Math.abs(east - west); + if (east > west) { + return longSpan; + } + + // shortest span contains antimeridian + return GeometryConstants.LONGITUDE_SPAN - longSpan; + } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HTTPRequest.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HTTPRequest.java index 3491ec5c85..d0e51f941f 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HTTPRequest.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HTTPRequest.java @@ -7,10 +7,10 @@ import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; +import com.mapbox.android.telemetry.TelemetryUtils; import com.mapbox.mapboxsdk.BuildConfig; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.services.android.telemetry.utils.TelemetryUtils; import java.io.IOException; import java.io.InterruptedIOException; @@ -29,7 +29,6 @@ import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; - import okhttp3.ResponseBody; import timber.log.Timber; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationSource.java deleted file mode 100644 index 1313587158..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationSource.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.location.Location; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.android.telemetry.location.LocationEngineListener; -import com.mapbox.services.android.telemetry.location.LocationEnginePriority; -import com.mapzen.android.lost.api.LocationListener; -import com.mapzen.android.lost.api.LocationRequest; -import com.mapzen.android.lost.api.LocationServices; -import com.mapzen.android.lost.api.LostApiClient; - -/** - * LocationEngine using the Open Source Lost library - * Manages locational updates. Contains methods to register and unregister location listeners. - * <ul> - * <li>You can register a LocationEngineListener with LocationSource#addLocationEngineListener(LocationEngineListener) - * to receive location updates.</li> - * <li> You can unregister a LocationEngineListener with - * LocationEngine#removeLocationEngineListener(LocationEngineListener)} to stop receiving location updates.</li> - * </ul> - * <p> - * Note: If registering a listener in your Activity.onStart() implementation, you should unregister it in - * Activity.onStop(). (You won't receive location updates when paused, and this will cut down on unnecessary system - * overhead). Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back - * in the history stack. - * </p> - * - * @deprecated Use a {@link Mapbox#getLocationEngine()} instead. - */ -@Deprecated -public class LocationSource extends LocationEngine implements LostApiClient.ConnectionCallbacks, LocationListener { - - private Context context; - private LostApiClient lostApiClient; - - /** - * Constructs a location source instance. - * - * @param context the context from which the Application context will be derived. - */ - public LocationSource(Context context) { - super(); - this.context = context.getApplicationContext(); - lostApiClient = new LostApiClient.Builder(this.context) - .addConnectionCallbacks(this) - .build(); - } - - /** - * Constructs a location source instance. - * Needed to create empty location source implementations. - */ - public LocationSource() { - } - - /** - * Activate the location engine which will connect whichever location provider you are using. You'll need to call - * this before requesting user location updates using {@link LocationEngine#requestLocationUpdates()}. - */ - @Override - public void activate() { - connect(); - } - - /** - * Disconnect the location engine which is useful when you no longer need location updates or requesting the users - * {@link LocationEngine#getLastLocation()}. Before deactivating, you'll need to stop request user location updates - * using {@link LocationEngine#removeLocationUpdates()}. - */ - @Override - public void deactivate() { - if (lostApiClient != null && lostApiClient.isConnected()) { - lostApiClient.disconnect(); - } - } - - /** - * Check if your location provider has been activated/connected. This is mainly used internally but is also useful in - * the rare case when you'd like to know if your location engine is connected or not. - * - * @return boolean true if the location engine has been activated/connected, else false. - */ - @Override - public boolean isConnected() { - return lostApiClient.isConnected(); - } - - /** - * Invoked when the location provider has connected. - */ - @Override - public void onConnected() { - for (LocationEngineListener listener : locationListeners) { - listener.onConnected(); - } - } - - /** - * Invoked when the location provider connection has been suspended. - */ - @Override - public void onConnectionSuspended() { - // Empty - } - - /** - * Returns the Last known location is the location provider is connected and location permissions are granted. - * - * @return the last known location - */ - @Override - @Nullable - public Location getLastLocation() { - if (lostApiClient.isConnected()) { - //noinspection MissingPermission - return LocationServices.FusedLocationApi.getLastLocation(lostApiClient); - } - return null; - } - - /** - * Request location updates to the location provider. - */ - @Override - public void requestLocationUpdates() { - LocationRequest request = LocationRequest.create(); - - if (interval != null) { - request.setInterval(interval); - } - if (fastestInterval != null) { - request.setFastestInterval(fastestInterval); - } - if (smallestDisplacement != null) { - request.setSmallestDisplacement(smallestDisplacement); - } - - if (priority == LocationEnginePriority.NO_POWER) { - request.setPriority(LocationRequest.PRIORITY_NO_POWER); - } else if (priority == LocationEnginePriority.LOW_POWER) { - request.setPriority(LocationRequest.PRIORITY_LOW_POWER); - } else if (priority == LocationEnginePriority.BALANCED_POWER_ACCURACY) { - request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); - } else if (priority == LocationEnginePriority.HIGH_ACCURACY) { - request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); - } - - if (lostApiClient.isConnected()) { - //noinspection MissingPermission - LocationServices.FusedLocationApi.requestLocationUpdates(lostApiClient, request, this); - } - } - - /** - * Dismiss ongoing location update to the location provider. - */ - @Override - public void removeLocationUpdates() { - if (lostApiClient.isConnected()) { - LocationServices.FusedLocationApi.removeLocationUpdates(lostApiClient, this); - } - } - - /** - * Returns the location engine type. - * - * @return Lost type - */ - @Override - public Type obtainType() { - return Type.LOST; - } - - /** - * Invoked when the Location has changed. - * - * @param location the new location - */ - @Override - public void onLocationChanged(Location location) { - for (LocationEngineListener listener : locationListeners) { - listener.onLocationChanged(location); - } - } - - private void connect() { - if (lostApiClient != null) { - if (lostApiClient.isConnected()) { - onConnected(); - } else { - lostApiClient.connect(); - } - } - } -}
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/package-info.java deleted file mode 100644 index b27559e95e..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Location API classes. - */ -package com.mapbox.mapboxsdk.location;
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AttributionDialogManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AttributionDialogManager.java index 48de768e64..39cd25631e 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AttributionDialogManager.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AttributionDialogManager.java @@ -11,12 +11,13 @@ import android.support.annotation.NonNull; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Toast; + +import com.mapbox.android.telemetry.TelemetryEnabler; import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.attribution.Attribution; import com.mapbox.mapboxsdk.attribution.AttributionParser; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.style.sources.Source; -import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.util.ArrayList; import java.util.List; @@ -31,17 +32,16 @@ import java.util.Set; * Additionally an telemetry option item is shown to configure telemetry settings. * </p> */ -class AttributionDialogManager implements View.OnClickListener, DialogInterface.OnClickListener { +public class AttributionDialogManager implements View.OnClickListener, DialogInterface.OnClickListener { private static final String MAP_FEEDBACK_URL = "https://www.mapbox.com/map-feedback"; private static final String MAP_FEEDBACK_LOCATION_FORMAT = MAP_FEEDBACK_URL + "/#/%f/%f/%d"; private final Context context; private final MapboxMap mapboxMap; - private String[] attributionTitles; private Set<Attribution> attributionSet; - AttributionDialogManager(@NonNull Context context, @NonNull MapboxMap mapboxMap) { + public AttributionDialogManager(@NonNull Context context, @NonNull MapboxMap mapboxMap) { this.context = context; this.mapboxMap = mapboxMap; } @@ -59,12 +59,11 @@ class AttributionDialogManager implements View.OnClickListener, DialogInterface. // check is hosting activity isn't finishing // https://github.com/mapbox/mapbox-gl-native/issues/11238 if (!isActivityFinishing) { - showAttributionDialog(); + showAttributionDialog(getAttributionTitles()); } } - private void showAttributionDialog() { - attributionTitles = getAttributionTitles(); + protected void showAttributionDialog(String[] attributionTitles) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.mapbox_attributionsDialogTitle); builder.setAdapter(new ArrayAdapter<>(context, R.layout.mapbox_attribution_list_item, attributionTitles), this); @@ -90,7 +89,7 @@ class AttributionDialogManager implements View.OnClickListener, DialogInterface. } private boolean isLatestEntry(int attributionKeyIndex) { - return attributionKeyIndex == attributionTitles.length - 1; + return attributionKeyIndex == getAttributionTitles().length - 1; } private void showTelemetryDialog() { @@ -100,7 +99,8 @@ class AttributionDialogManager implements View.OnClickListener, DialogInterface. builder.setPositiveButton(R.string.mapbox_attributionTelemetryPositive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - MapboxTelemetry.getInstance().setTelemetryEnabled(true); + TelemetryEnabler.updateTelemetryState(TelemetryEnabler.State.ENABLED); + Telemetry.obtainTelemetry().enable(); dialog.cancel(); } }); @@ -114,7 +114,8 @@ class AttributionDialogManager implements View.OnClickListener, DialogInterface. builder.setNegativeButton(R.string.mapbox_attributionTelemetryNegative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - MapboxTelemetry.getInstance().setTelemetryEnabled(false); + Telemetry.obtainTelemetry().disable(); + TelemetryEnabler.updateTelemetryState(TelemetryEnabler.State.DISABLED); dialog.cancel(); } }); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java index 07106689be..de9b4fdbc2 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java @@ -5,27 +5,32 @@ import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.PointF; -import android.location.Location; +import android.os.Handler; import android.support.annotation.Nullable; -import android.support.v4.view.GestureDetectorCompat; -import android.support.v4.view.ScaleGestureDetectorCompat; -import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.view.InputDevice; import android.view.MotionEvent; -import android.view.ScaleGestureDetector; -import android.view.VelocityTracker; -import android.view.ViewConfiguration; - -import com.almeros.android.multitouch.gesturedetectors.RotateGestureDetector; -import com.almeros.android.multitouch.gesturedetectors.ShoveGestureDetector; -import com.almeros.android.multitouch.gesturedetectors.TwoFingerGestureDetector; +import android.view.animation.DecelerateInterpolator; + +import com.mapbox.android.gestures.AndroidGesturesManager; +import com.mapbox.android.gestures.Constants; +import com.mapbox.android.gestures.MoveGestureDetector; +import com.mapbox.android.gestures.MultiFingerTapGestureDetector; +import com.mapbox.android.gestures.RotateGestureDetector; +import com.mapbox.android.gestures.ShoveGestureDetector; +import com.mapbox.android.gestures.StandardGestureDetector; +import com.mapbox.android.gestures.StandardScaleGestureDetector; +import com.mapbox.android.telemetry.Event; +import com.mapbox.android.telemetry.MapEventFactory; +import com.mapbox.android.telemetry.MapState; +import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.services.android.telemetry.MapboxEvent; -import com.mapbox.services.android.telemetry.MapboxTelemetry; -import com.mapbox.services.android.telemetry.utils.MathUtils; -import com.mapbox.services.android.telemetry.utils.TelemetryUtils; +import com.mapbox.mapboxsdk.utils.MathUtils; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_API_ANIMATION; @@ -33,24 +38,15 @@ import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.RE /** * Manages gestures events on a MapView. - * <p> - * Relies on gesture detection code in almeros.android.multitouch.gesturedetectors. - * </p> */ final class MapGestureDetector { private final Transform transform; private final Projection projection; private final UiSettings uiSettings; - private final TrackingSettings trackingSettings; private final AnnotationManager annotationManager; private final CameraChangeDispatcher cameraChangeDispatcher; - private GestureDetectorCompat gestureDetector; - private ScaleGestureDetector scaleGestureDetector; - private RotateGestureDetector rotateGestureDetector; - private ShoveGestureDetector shoveGestureDetector; - // deprecated map touch API private MapboxMap.OnMapClickListener onMapClickListener; private MapboxMap.OnMapLongClickListener onMapLongClickListener; @@ -70,44 +66,96 @@ final class MapGestureDetector { private final CopyOnWriteArrayList<MapboxMap.OnScrollListener> onScrollListenerList = new CopyOnWriteArrayList<>(); - private PointF focalPoint; + private final CopyOnWriteArrayList<MapboxMap.OnMoveListener> onMoveListenerList + = new CopyOnWriteArrayList<>(); + + private final CopyOnWriteArrayList<MapboxMap.OnRotateListener> onRotateListenerList + = new CopyOnWriteArrayList<>(); + + private final CopyOnWriteArrayList<MapboxMap.OnScaleListener> onScaleListenerList + = new CopyOnWriteArrayList<>(); - private boolean twoTap; - private boolean quickZoom; - private boolean tiltGestureOccurred; - private boolean scrollGestureOccurred; + private final CopyOnWriteArrayList<MapboxMap.OnShoveListener> onShoveListenerList + = new CopyOnWriteArrayList<>(); - private boolean scaleGestureOccurred; - private boolean recentScaleGestureOccurred; - private long scaleBeginTime; + /** + * User-set focal point. + */ + private PointF focalPoint; + + private AndroidGesturesManager gesturesManager; + private boolean executeDoubleTap; - private boolean scaleAnimating; - private boolean rotateAnimating; + private Animator scaleAnimator; + private Animator rotateAnimator; + private final List<Animator> scheduledAnimators = new ArrayList<>(); - private VelocityTracker velocityTracker; - private boolean wasZoomingIn; - private boolean wasClockwiseRotating; - private boolean rotateGestureOccurred; + /** + * Cancels scheduled velocity animations if user doesn't lift fingers within + * {@link MapboxConstants#SCHEDULED_ANIMATION_TIMEOUT} + */ + private Handler animationsTimeoutHandler = new Handler(); MapGestureDetector(Context context, Transform transform, Projection projection, UiSettings uiSettings, - TrackingSettings trackingSettings, AnnotationManager annotationManager, - CameraChangeDispatcher cameraChangeDispatcher) { + AnnotationManager annotationManager, CameraChangeDispatcher cameraChangeDispatcher) { this.annotationManager = annotationManager; this.transform = transform; this.projection = projection; this.uiSettings = uiSettings; - this.trackingSettings = trackingSettings; this.cameraChangeDispatcher = cameraChangeDispatcher; - // Touch gesture detectors + // Checking for context != null for testing purposes if (context != null) { - gestureDetector = new GestureDetectorCompat(context, new GestureListener()); - gestureDetector.setIsLongpressEnabled(true); - scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener()); - ScaleGestureDetectorCompat.setQuickScaleEnabled(scaleGestureDetector, true); - rotateGestureDetector = new RotateGestureDetector(context, new RotateGestureListener()); - shoveGestureDetector = new ShoveGestureDetector(context, new ShoveGestureListener()); + // Initialize gestures manager + AndroidGesturesManager androidGesturesManager = new AndroidGesturesManager(context); + initializeGesturesManager(androidGesturesManager, true); + + // Initialize gesture listeners + initializeGestureListeners(context, true); + } + } + + private void initializeGestureListeners(Context context, boolean attachDefaultListeners) { + if (attachDefaultListeners) { + StandardGestureListener standardGestureListener = new StandardGestureListener(); + MoveGestureListener moveGestureListener = new MoveGestureListener(); + ScaleGestureListener scaleGestureListener = new ScaleGestureListener( + context.getResources().getDimension(R.dimen.mapbox_minimum_scale_velocity)); + RotateGestureListener rotateGestureListener = new RotateGestureListener( + context.getResources().getDimension(R.dimen.mapbox_minimum_scale_span_when_rotating), + context.getResources().getDimension(R.dimen.mapbox_minimum_angular_velocity), + context.getResources().getDimension(R.dimen.mapbox_defaultScaleSpanSinceStartThreshold)); + ShoveGestureListener shoveGestureListener = new ShoveGestureListener(); + TapGestureListener tapGestureListener = new TapGestureListener(); + + gesturesManager.setStandardGestureListener(standardGestureListener); + gesturesManager.setMoveGestureListener(moveGestureListener); + gesturesManager.setStandardScaleGestureListener(scaleGestureListener); + gesturesManager.setRotateGestureListener(rotateGestureListener); + gesturesManager.setShoveGestureListener(shoveGestureListener); + gesturesManager.setMultiFingerTapGestureListener(tapGestureListener); + } + } + + private void initializeGesturesManager(AndroidGesturesManager androidGesturesManager, + boolean setDefaultMutuallyExclusives) { + if (setDefaultMutuallyExclusives) { + Set<Integer> shoveScaleSet = new HashSet<>(); + shoveScaleSet.add(AndroidGesturesManager.GESTURE_TYPE_SHOVE); + shoveScaleSet.add(AndroidGesturesManager.GESTURE_TYPE_SCALE); + + Set<Integer> shoveRotateSet = new HashSet<>(); + shoveRotateSet.add(AndroidGesturesManager.GESTURE_TYPE_SHOVE); + shoveRotateSet.add(AndroidGesturesManager.GESTURE_TYPE_ROTATE); + + Set<Integer> ScaleLongPressSet = new HashSet<>(); + ScaleLongPressSet.add(AndroidGesturesManager.GESTURE_TYPE_SCALE); + ScaleLongPressSet.add(AndroidGesturesManager.GESTURE_TYPE_LONG_PRESS); + + androidGesturesManager.setMutuallyExclusiveGestures(shoveScaleSet, shoveRotateSet, ScaleLongPressSet); } + + gesturesManager = androidGesturesManager; } /** @@ -133,8 +181,9 @@ final class MapGestureDetector { /** * Get the current active gesture focal point. * <p> - * This could be either the user provided focal point in {@link UiSettings#setFocalPoint(PointF)} or the focal point - * defined as a result of {@link TrackingSettings#setMyLocationEnabled(boolean)}. + * This could be either the user provided focal point in + * {@link UiSettings#setFocalPoint(PointF)}or <code>null</code>. + * If it's <code>null</code>, gestures will use focal pointed returned by the detector. * </p> * * @return the current active gesture focal point. @@ -145,128 +194,86 @@ final class MapGestureDetector { } /** - * Given coordinates from a gesture, use the current projection to translate it into - * a Location object. - * - * @param x coordinate - * @param y coordinate - * @return location - */ - private Location getLocationFromGesture(float x, float y) { - LatLng latLng = projection.fromScreenLocation(new PointF(x, y)); - return TelemetryUtils.buildLocation(latLng.getLongitude(), latLng.getLatitude()); - } - - /** * Called when user touches the screen, all positions are absolute. * <p> * Forwards event to the related gesture detectors. * </p> * - * @param event the MotionEvent + * @param motionEvent the MotionEvent * @return True if touch event is handled */ - boolean onTouchEvent(MotionEvent event) { - // framework can return null motion events in edge cases #9432 - if (event == null) { + boolean onTouchEvent(MotionEvent motionEvent) { + // Framework can return null motion events in edge cases #9432 + if (motionEvent == null) { return false; } // Check and ignore non touch or left clicks - if ((event.getButtonState() != 0) && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) { + if ((motionEvent.getButtonState() != 0) && (motionEvent.getButtonState() != MotionEvent.BUTTON_PRIMARY)) { return false; } - // Check two finger gestures first - scaleGestureDetector.onTouchEvent(event); - rotateGestureDetector.onTouchEvent(event); - shoveGestureDetector.onTouchEvent(event); + boolean result = gesturesManager.onTouchEvent(motionEvent); - // Handle two finger tap - switch (event.getActionMasked()) { + switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: - if (velocityTracker == null) { - velocityTracker = VelocityTracker.obtain(); - } else { - velocityTracker.clear(); - } - velocityTracker.addMovement(event); - // First pointer down, reset scaleGestureOccurred, used to avoid triggering a fling after a scale gesture #7666 - recentScaleGestureOccurred = false; + cancelAnimators(); transform.setGestureInProgress(true); break; + case MotionEvent.ACTION_UP: + transform.setGestureInProgress(false); - case MotionEvent.ACTION_POINTER_DOWN: - // Second pointer down - twoTap = event.getPointerCount() == 2 - && uiSettings.isZoomGesturesEnabled(); - if (twoTap) { - // Confirmed 2nd Finger Down - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(event.getX(), event.getY()), - MapboxEvent.GESTURE_TWO_FINGER_SINGLETAP, transform)); + // Start all awaiting velocity animations + animationsTimeoutHandler.removeCallbacksAndMessages(null); + for (Animator animator : scheduledAnimators) { + animator.start(); } + scheduledAnimators.clear(); break; - case MotionEvent.ACTION_POINTER_UP: - // Second pointer up + case MotionEvent.ACTION_CANCEL: + scheduledAnimators.clear(); + transform.setGestureInProgress(false); break; + } - case MotionEvent.ACTION_UP: - // First pointer up - long tapInterval = event.getEventTime() - event.getDownTime(); - boolean isTap = tapInterval <= ViewConfiguration.getTapTimeout(); - boolean inProgress = rotateGestureDetector.isInProgress() - || scaleGestureDetector.isInProgress() - || shoveGestureDetector.isInProgress(); - - if (twoTap && isTap && !inProgress) { - if (focalPoint != null) { - transform.zoom(false, focalPoint); - } else { - PointF focalPoint = TwoFingerGestureDetector.determineFocalPoint(event); - transform.zoom(false, focalPoint); - } - twoTap = false; - return true; - } + return result; + } - // Scroll / Pan Has Stopped - if (scrollGestureOccurred) { - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapDragEndEvent( - getLocationFromGesture(event.getX(), event.getY()), transform)); - scrollGestureOccurred = false; + void cancelAnimators() { + animationsTimeoutHandler.removeCallbacksAndMessages(null); + scheduledAnimators.clear(); - if (!scaleAnimating && !rotateAnimating) { - cameraChangeDispatcher.onCameraIdle(); - } - } + cancelAnimator(scaleAnimator); + cancelAnimator(rotateAnimator); + } - twoTap = false; - transform.setGestureInProgress(false); - if (velocityTracker != null) { - velocityTracker.recycle(); - } - velocityTracker = null; - break; + private void cancelAnimator(Animator animator) { + if (animator != null && animator.isStarted()) { + animator.cancel(); + } + } - case MotionEvent.ACTION_CANCEL: - twoTap = false; - transform.setGestureInProgress(false); - if (velocityTracker != null) { - velocityTracker.recycle(); - } - velocityTracker = null; - break; - case MotionEvent.ACTION_MOVE: - if (velocityTracker != null) { - velocityTracker.addMovement(event); - velocityTracker.computeCurrentVelocity(1000); - } - break; + /** + * Posted on main thread with {@link #animationsTimeoutHandler}. Cancels all scheduled animators if needed. + */ + private Runnable cancelAnimatorsRunnable = new Runnable() { + @Override + public void run() { + cancelAnimators(); } + }; - return gestureDetector.onTouchEvent(event); + /** + * Schedules a velocity animator to be executed when user lift fingers, + * unless canceled by the {@link #cancelAnimatorsRunnable}. + * + * @param animator animator ot be scheduled + */ + private void scheduleAnimator(Animator animator) { + scheduledAnimators.add(animator); + animationsTimeoutHandler.removeCallbacksAndMessages(null); + animationsTimeoutHandler.postDelayed(cancelAnimatorsRunnable, MapboxConstants.SCHEDULED_ANIMATION_TIMEOUT); } /** @@ -275,7 +282,7 @@ final class MapGestureDetector { * Examples of such events are mouse scroll events, mouse moves, joystick & trackpad. * </p> * - * @param event The MotionEvent occured + * @param event The MotionEvent occurred * @return True is the event is handled */ boolean onGenericMotionEvent(MotionEvent event) { @@ -297,7 +304,7 @@ final class MapGestureDetector { float scrollDist = event.getAxisValue(MotionEvent.AXIS_VSCROLL); // Scale the map by the appropriate power of two factor - transform.zoomBy(scrollDist, event.getX(), event.getY()); + transform.zoomBy(scrollDist, new PointF(event.getX(), event.getY())); return true; @@ -311,57 +318,14 @@ final class MapGestureDetector { return false; } - /** - * Responsible for handling one finger gestures. - */ - private class GestureListener extends android.view.GestureDetector.SimpleOnGestureListener { - + private final class StandardGestureListener extends StandardGestureDetector.SimpleStandardOnGestureListener { @Override - public boolean onDown(MotionEvent event) { - return true; - } - - @Override - public boolean onDoubleTapEvent(MotionEvent e) { - if (!uiSettings.isZoomGesturesEnabled() || !uiSettings.isDoubleTapGesturesEnabled()) { - return false; - } - - switch (e.getAction()) { - case MotionEvent.ACTION_DOWN: - break; - case MotionEvent.ACTION_MOVE: - break; - case MotionEvent.ACTION_UP: - if (quickZoom) { - cameraChangeDispatcher.onCameraIdle(); - quickZoom = false; - break; - } - - // notify camera change listener - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - - // Single finger double tap - if (focalPoint != null) { - // User provided focal point - transform.zoom(true, focalPoint); - } else { - // Zoom in on gesture - transform.zoom(true, new PointF(e.getX(), e.getY())); - } - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(e.getX(), e.getY()), - MapboxEvent.GESTURE_DOUBLETAP, transform)); - break; - } - + public boolean onDown(MotionEvent motionEvent) { return true; } @Override public boolean onSingleTapUp(MotionEvent motionEvent) { - // Cancel any animation transform.cancelTransitions(); return true; } @@ -380,27 +344,60 @@ final class MapGestureDetector { notifyOnMapClickListeners(tapPoint); } - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(motionEvent.getX(), motionEvent.getY()), - MapboxEvent.GESTURE_SINGLETAP, transform)); + sendTelemetryEvent(Telemetry.SINGLE_TAP, new PointF(motionEvent.getX(), motionEvent.getY())); return true; } @Override - public void onLongPress(MotionEvent motionEvent) { - PointF longClickPoint = new PointF(motionEvent.getX(), motionEvent.getY()); + public boolean onDoubleTapEvent(MotionEvent motionEvent) { + int action = motionEvent.getActionMasked(); + if (action == MotionEvent.ACTION_DOWN) { + executeDoubleTap = true; + } + if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { + if (!uiSettings.isZoomGesturesEnabled() || !uiSettings.isDoubleTapGesturesEnabled() || !executeDoubleTap) { + return false; + } + + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); + + PointF zoomFocalPoint; + // Single finger double tap + if (focalPoint != null) { + // User provided focal point + zoomFocalPoint = focalPoint; + } else { + // Zoom in on gesture + zoomFocalPoint = new PointF(motionEvent.getX(), motionEvent.getY()); + } - if (!quickZoom) { - notifyOnMapLongClickListeners(longClickPoint); + zoomInAnimated(zoomFocalPoint, false); + + sendTelemetryEvent(Telemetry.DOUBLE_TAP, new PointF(motionEvent.getX(), motionEvent.getY())); + + return true; } + return super.onDoubleTapEvent(motionEvent); + } + + @Override + public void onLongPress(MotionEvent motionEvent) { + PointF longClickPoint = new PointF(motionEvent.getX(), motionEvent.getY()); + notifyOnMapLongClickListeners(longClickPoint); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { - if ((!trackingSettings.isScrollGestureCurrentlyEnabled()) || recentScaleGestureOccurred) { - // don't allow a fling is scroll is disabled - // and ignore when a scale gesture has occurred + if (!uiSettings.isScrollGesturesEnabled()) { + // don't allow a fling if scroll is disabled + return false; + } + + notifyOnFlingListeners(); + + if (!uiSettings.isFlingVelocityAnimationEnabled()) { return false; } @@ -413,11 +410,7 @@ final class MapGestureDetector { return false; } - trackingSettings.resetTrackingModesIfRequired(true, false, false); - - // cancel any animation transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); // tilt results in a bigger translation, limiting input for #5281 @@ -432,487 +425,600 @@ final class MapGestureDetector { // update transformation transform.moveBy(offsetX, offsetY, animationTime); - notifyOnFlingListeners(); return true; } + } - // Called for drags + private final class MoveGestureListener extends MoveGestureDetector.SimpleOnMoveGestureListener { @Override - public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + public boolean onMoveBegin(MoveGestureDetector detector) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } - if (tiltGestureOccurred) { - return false; - } + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - if (!scrollGestureOccurred) { - scrollGestureOccurred = true; + sendTelemetryEvent(Telemetry.PAN, detector.getFocalPoint()); - // Cancel any animation - if (!scaleGestureOccurred) { - transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - } + notifyOnMoveBeginListeners(detector); - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(e1.getX(), e1.getY()), - MapboxEvent.GESTURE_PAN_START, transform)); - } + return true; + } - // reset tracking if needed - trackingSettings.resetTrackingModesIfRequired(true, false, false); + @Override + public boolean onMove(MoveGestureDetector detector, float distanceX, float distanceY) { + // dispatching start even once more if another detector ended, and this one didn't + cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); // Scroll the map transform.moveBy(-distanceX, -distanceY, 0 /*no duration*/); notifyOnScrollListeners(); + notifyOnMoveListeners(detector); return true; } - } - - void notifyOnMapClickListeners(PointF tapPoint) { - // deprecated API - if (onMapClickListener != null) { - onMapClickListener.onMapClick(projection.fromScreenLocation(tapPoint)); - } - // new API - for (MapboxMap.OnMapClickListener listener : onMapClickListenerList) { - listener.onMapClick(projection.fromScreenLocation(tapPoint)); + @Override + public void onMoveEnd(MoveGestureDetector detector, float velocityX, float velocityY) { + cameraChangeDispatcher.onCameraIdle(); + notifyOnMoveEndListeners(detector); } } - void notifyOnMapLongClickListeners(PointF longClickPoint) { - // deprecated API - if (onMapLongClickListener != null) { - onMapLongClickListener.onMapLongClick(projection.fromScreenLocation(longClickPoint)); - } + private final class ScaleGestureListener extends StandardScaleGestureDetector.SimpleStandardOnScaleGestureListener { - // new API - for (MapboxMap.OnMapLongClickListener listener : onMapLongClickListenerList) { - listener.onMapLongClick(projection.fromScreenLocation(longClickPoint)); - } - } + private final float minimumVelocity; - void notifyOnFlingListeners() { - // deprecated API - if (onFlingListener != null) { - onFlingListener.onFling(); - } + private PointF scaleFocalPoint; + private boolean quickZoom; - // new API - for (MapboxMap.OnFlingListener listener : onFlingListenerList) { - listener.onFling(); + ScaleGestureListener(float minimumVelocity) { + this.minimumVelocity = minimumVelocity; } - } - void notifyOnScrollListeners() { - //deprecated API - if (onScrollListener != null) { - onScrollListener.onScroll(); - } + @Override + public boolean onScaleBegin(StandardScaleGestureDetector detector) { + if (!uiSettings.isZoomGesturesEnabled()) { + return false; + } - // new API - for (MapboxMap.OnScrollListener listener : onScrollListenerList) { - listener.onScroll(); - } - } + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - /** - * Responsible for handling two finger gestures and double-tap drag gestures. - */ - private class ScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { + quickZoom = detector.getPointersCount() == 1; + if (quickZoom) { + // when quickzoom, dismiss double tap and disable move gesture + executeDoubleTap = false; + gesturesManager.getMoveGestureDetector().setEnabled(false); + } + + if (uiSettings.isIncreaseRotateThresholdWhenScaling()) { + // increase rotate angle threshold when scale is detected first + gesturesManager.getRotateGestureDetector().setAngleThreshold( + Constants.DEFAULT_ROTATE_ANGLE_THRESHOLD + + MapboxConstants.ROTATION_THRESHOLD_INCREASE_WHEN_SCALING + ); + } + + // setting focalPoint in #onScaleBegin() as well, because #onScale() might not get called before #onScaleEnd() + setScaleFocalPoint(detector); - private static final int ANIMATION_TIME_MULTIPLIER = 77; - private static final double ZOOM_DISTANCE_DIVIDER = 5; + sendTelemetryEvent(Telemetry.PINCH, scaleFocalPoint); - private float scaleFactor = 1.0f; - private PointF scalePointBegin; + notifyOnScaleBeginListeners(detector); + + return true; + } - // Called when two fingers first touch the screen @Override - public boolean onScaleBegin(ScaleGestureDetector detector) { - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } + public boolean onScale(StandardScaleGestureDetector detector) { + // dispatching start even once more if another detector ended, and this one didn't + cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); + + setScaleFocalPoint(detector); + + float scaleFactor = detector.getScaleFactor(); + double zoomBy = getNewZoom(scaleFactor, quickZoom); + transform.zoomBy(zoomBy, scaleFocalPoint); + + notifyOnScaleListeners(detector); - recentScaleGestureOccurred = true; - scalePointBegin = new PointF(detector.getFocusX(), detector.getFocusY()); - scaleBeginTime = detector.getEventTime(); - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(detector.getFocusX(), detector.getFocusY()), - MapboxEvent.GESTURE_PINCH_START, transform)); return true; } - // Called each time a finger moves - // Called for pinch zooms and quickzooms/quickscales @Override - public boolean onScale(ScaleGestureDetector detector) { - if (!uiSettings.isZoomGesturesEnabled()) { - return super.onScale(detector); - } + public void onScaleEnd(StandardScaleGestureDetector detector, float velocityX, float velocityY) { + cameraChangeDispatcher.onCameraIdle(); - wasZoomingIn = (Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2)) > 0; - if (tiltGestureOccurred) { - return false; + if (quickZoom) { + //if quickzoom, re-enabling move gesture detector + gesturesManager.getMoveGestureDetector().setEnabled(true); } - // Ignore short touches in case it is a tap - // Also ignore small scales - long time = detector.getEventTime(); - long interval = time - scaleBeginTime; - if (!scaleGestureOccurred && (interval <= ViewConfiguration.getTapTimeout())) { - return false; + if (uiSettings.isIncreaseRotateThresholdWhenScaling()) { + // resetting default angle threshold + gesturesManager.getRotateGestureDetector().setAngleThreshold( + Constants.DEFAULT_ROTATE_ANGLE_THRESHOLD + ); } - // If scale is large enough ignore a tap - scaleFactor *= detector.getScaleFactor(); - if ((scaleFactor > 1.1f) || (scaleFactor < 0.9f)) { - // notify camera change listener - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - scaleGestureOccurred = true; - } + notifyOnScaleEndListeners(detector); - if (!scaleGestureOccurred) { - return false; + if (!uiSettings.isScaleVelocityAnimationEnabled()) { + return; } - // Gesture is a quickzoom if there aren't two fingers - if (!quickZoom && !twoTap) { - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); + float velocityXY = Math.abs(velocityX) + Math.abs(velocityY); + if (velocityXY > minimumVelocity) { + double zoomAddition = calculateScale(velocityXY, detector.isScalingOut()); + double currentZoom = transform.getRawZoom(); + long animationTime = (long) (Math.abs(zoomAddition) * 1000 / 4); + scaleAnimator = createScaleAnimator(currentZoom, zoomAddition, scaleFocalPoint, animationTime); + scheduleAnimator(scaleAnimator); } - quickZoom = !twoTap; + } - // make an assumption here; if the zoom center is specified by the gesture, it's NOT going - // to be in the center of the map. Therefore the zoom will translate the map center, so tracking - // should be disabled. - trackingSettings.resetTrackingModesIfRequired(!quickZoom, false, false); - // Scale the map + private void setScaleFocalPoint(StandardScaleGestureDetector detector) { if (focalPoint != null) { - // arround user provided focal point - transform.zoomBy(Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2), focalPoint.x, focalPoint.y); + // around user provided focal point + scaleFocalPoint = focalPoint; } else if (quickZoom) { - cameraChangeDispatcher.onCameraMove(); + // around center + scaleFocalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); + } else { + // around gesture + scaleFocalPoint = detector.getFocalPoint(); + } + } + + private double calculateScale(double velocityXY, boolean isScalingOut) { + double zoomAddition = (float) Math.log(velocityXY / 1000 + 1); + if (isScalingOut) { + zoomAddition = -zoomAddition; + } + return zoomAddition; + } + + private double getNewZoom(float scaleFactor, boolean quickZoom) { + double zoomBy = Math.log(scaleFactor) / Math.log(Math.PI / 2); + if (quickZoom) { // clamp scale factors we feed to core #7514 - float scaleFactor = detector.getScaleFactor(); - // around center map - double zoomBy = Math.log(scaleFactor) / Math.log(Math.PI / 2); boolean negative = zoomBy < 0; zoomBy = MathUtils.clamp(Math.abs(zoomBy), MapboxConstants.MINIMUM_SCALE_FACTOR_CLAMP, MapboxConstants.MAXIMUM_SCALE_FACTOR_CLAMP); - transform.zoomBy(negative ? -zoomBy : zoomBy, uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - recentScaleGestureOccurred = true; - } else { - // around gesture - transform.zoomBy(Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2), - scalePointBegin.x, scalePointBegin.y); + return negative ? -zoomBy : zoomBy; } + return zoomBy; + } + } + + private final class RotateGestureListener extends RotateGestureDetector.SimpleOnRotateGestureListener { + private PointF rotateFocalPoint; + private final float minimumScaleSpanWhenRotating; + private final float minimumAngularVelocity; + private final float defaultSpanSinceStartThreshold; + + public RotateGestureListener(float minimumScaleSpanWhenRotating, float minimumAngularVelocity, + float defaultSpanSinceStartThreshold) { + this.minimumScaleSpanWhenRotating = minimumScaleSpanWhenRotating; + this.minimumAngularVelocity = minimumAngularVelocity; + this.defaultSpanSinceStartThreshold = defaultSpanSinceStartThreshold; + } + + @Override + public boolean onRotateBegin(RotateGestureDetector detector) { + if (!uiSettings.isRotateGesturesEnabled()) { + return false; + } + + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); + + if (uiSettings.isIncreaseScaleThresholdWhenRotating()) { + // when rotation starts, interrupting scale and increasing the threshold + // to make rotation without scaling easier + gesturesManager.getStandardScaleGestureDetector().setSpanSinceStartThreshold(minimumScaleSpanWhenRotating); + gesturesManager.getStandardScaleGestureDetector().interrupt(); + } + + // setting in #onRotateBegin() as well, because #onRotate() might not get called before #onRotateEnd() + setRotateFocalPoint(detector); + + sendTelemetryEvent(Telemetry.ROTATION, rotateFocalPoint); + + notifyOnRotateBeginListeners(detector); + + return true; + } + + @Override + public boolean onRotate(RotateGestureDetector detector, float rotationDegreesSinceLast, + float rotationDegreesSinceFirst) { + // dispatching start even once more if another detector ended, and this one didn't + cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); + + setRotateFocalPoint(detector); + + // Calculate map bearing value + double bearing = transform.getRawBearing() + rotationDegreesSinceLast; + + // Rotate the map + transform.setBearing(bearing, rotateFocalPoint.x, rotateFocalPoint.y); + + notifyOnRotateListeners(detector); + return true; } - // Called when fingers leave screen @Override - public void onScaleEnd(final ScaleGestureDetector detector) { - if (velocityTracker == null) { + public void onRotateEnd(RotateGestureDetector detector, float velocityX, float velocityY, float angularVelocity) { + cameraChangeDispatcher.onCameraIdle(); + + if (uiSettings.isIncreaseScaleThresholdWhenRotating()) { + // resetting default scale threshold values + gesturesManager.getStandardScaleGestureDetector().setSpanSinceStartThreshold(defaultSpanSinceStartThreshold); + } + + notifyOnRotateEndListeners(detector); + + if (!uiSettings.isRotateVelocityAnimationEnabled()) { return; } - if (rotateGestureOccurred || quickZoom) { - reset(); + if (Math.abs(angularVelocity) < minimumAngularVelocity) { return; } - double velocityXY = Math.abs(velocityTracker.getYVelocity()) + Math.abs(velocityTracker.getXVelocity()); - if (velocityXY > MapboxConstants.VELOCITY_THRESHOLD_IGNORE_FLING / 2) { - scaleAnimating = true; - double zoomAddition = calculateScale(velocityXY); - double currentZoom = transform.getRawZoom(); - long animationTime = (long) (Math.log(velocityXY) * ANIMATION_TIME_MULTIPLIER); - createScaleAnimator(currentZoom, zoomAddition, animationTime).start(); - } else if (!scaleAnimating) { - reset(); + boolean negative = angularVelocity < 0; + angularVelocity = (float) Math.pow(angularVelocity, 2); + angularVelocity = MathUtils.clamp( + angularVelocity, MapboxConstants.MINIMUM_ANGULAR_VELOCITY, MapboxConstants.MAXIMUM_ANGULAR_VELOCITY); + + long animationTime = (long) (Math.log(angularVelocity + 1) * 500); + + if (negative) { + angularVelocity = -angularVelocity; } - } - private void reset() { - scaleAnimating = false; - scaleGestureOccurred = false; - scaleBeginTime = 0; - scaleFactor = 1.0f; - cameraChangeDispatcher.onCameraIdle(); + rotateAnimator = createRotateAnimator(angularVelocity, animationTime); + scheduleAnimator(rotateAnimator); } - private double calculateScale(double velocityXY) { - double zoomAddition = (float) (Math.log(velocityXY) / ZOOM_DISTANCE_DIVIDER); - if (!wasZoomingIn) { - zoomAddition = -zoomAddition; + private void setRotateFocalPoint(RotateGestureDetector detector) { + if (focalPoint != null) { + // User provided focal point + rotateFocalPoint = focalPoint; + } else { + // around gesture + rotateFocalPoint = detector.getFocalPoint(); } - return zoomAddition; } - private Animator createScaleAnimator(double currentZoom, double zoomAddition, long animationTime) { - ValueAnimator animator = ValueAnimator.ofFloat((float) currentZoom, (float) (currentZoom + zoomAddition)); + private Animator createRotateAnimator(float angularVelocity, long animationTime) { + ValueAnimator animator = ValueAnimator.ofFloat(angularVelocity, 0f); animator.setDuration(animationTime); - animator.setInterpolator(new FastOutSlowInInterpolator()); + animator.setInterpolator(new DecelerateInterpolator()); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override public void onAnimationUpdate(ValueAnimator animation) { - PointF scalePoint = focalPoint != null ? focalPoint : scalePointBegin; - transform.setZoom((Float) animation.getAnimatedValue(), scalePoint, 0, true); + transform.setBearing( + transform.getRawBearing() + (float) animation.getAnimatedValue(), + rotateFocalPoint.x, rotateFocalPoint.y, + 0L + ); } }); + animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { + transform.cancelTransitions(); cameraChangeDispatcher.onCameraMoveStarted(REASON_API_ANIMATION); } @Override public void onAnimationCancel(Animator animation) { - reset(); + cameraChangeDispatcher.onCameraIdle(); } @Override public void onAnimationEnd(Animator animation) { - reset(); + cameraChangeDispatcher.onCameraIdle(); } }); + return animator; } } - /** - * Responsible for handling rotation gestures. - */ - private class RotateGestureListener extends RotateGestureDetector.SimpleOnRotateGestureListener { - - private static final float ROTATE_INVOKE_ANGLE = 15.30f; - private static final float ROTATE_LIMITATION_ANGLE = 3.35f; - private static final float ROTATE_LIMITATION_DURATION = ROTATE_LIMITATION_ANGLE * 1.85f; - - private long beginTime = 0; - private boolean started = false; - - // Called when two fingers first touch the screen + private final class ShoveGestureListener extends ShoveGestureDetector.SimpleOnShoveGestureListener { @Override - public boolean onRotateBegin(RotateGestureDetector detector) { - if (!trackingSettings.isRotateGestureCurrentlyEnabled()) { + public boolean onShoveBegin(ShoveGestureDetector detector) { + if (!uiSettings.isTiltGesturesEnabled()) { return false; } - // notify camera change listener + transform.cancelTransitions(); cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - beginTime = detector.getEventTime(); + sendTelemetryEvent(Telemetry.PITCH, detector.getFocalPoint()); + + // disabling move gesture during shove + gesturesManager.getMoveGestureDetector().setEnabled(false); + + notifyOnShoveBeginListeners(detector); + return true; } - // Called each time one of the two fingers moves - // Called for rotation @Override - public boolean onRotate(RotateGestureDetector detector) { - if (!trackingSettings.isRotateGestureCurrentlyEnabled() || tiltGestureOccurred) { - return false; - } + public boolean onShove(ShoveGestureDetector detector, float deltaPixelsSinceLast, float deltaPixelsSinceStart) { + // dispatching start even once more if another detector ended, and this one didn't + cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); - // If rotate is large enough ignore a tap - // Also is zoom already started, don't rotate - float angle = detector.getRotationDegreesDelta(); - if (Math.abs(angle) >= ROTATE_INVOKE_ANGLE) { - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(detector.getFocusX(), detector.getFocusY()), - MapboxEvent.GESTURE_ROTATION_START, transform)); - started = true; - } + // Get tilt value (scale and clamp) + double pitch = transform.getTilt(); + pitch -= MapboxConstants.SHOVE_PIXEL_CHANGE_FACTOR * deltaPixelsSinceLast; + pitch = MathUtils.clamp(pitch, MapboxConstants.MINIMUM_TILT, MapboxConstants.MAXIMUM_TILT); - if (!started) { - return false; - } + // Tilt the map + transform.setTilt(pitch); + + notifyOnShoveListeners(detector); - wasClockwiseRotating = detector.getRotationDegreesDelta() > 0; - if (scaleBeginTime != 0) { - rotateGestureOccurred = true; + return true; + } + + @Override + public void onShoveEnd(ShoveGestureDetector detector, float velocityX, float velocityY) { + cameraChangeDispatcher.onCameraIdle(); + + // re-enabling move gesture + gesturesManager.getMoveGestureDetector().setEnabled(true); + + notifyOnShoveEndListeners(detector); + } + } + + private final class TapGestureListener implements MultiFingerTapGestureDetector.OnMultiFingerTapGestureListener { + @Override + public boolean onMultiFingerTap(MultiFingerTapGestureDetector detector, int pointersCount) { + if (!uiSettings.isZoomGesturesEnabled() || pointersCount != 2) { + return false; } - // rotation constitutes translation of anything except the center of - // rotation, so cancel both location and bearing tracking if required - trackingSettings.resetTrackingModesIfRequired(true, true, false); + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - // Calculate map bearing value - double bearing = transform.getRawBearing() + angle; + sendTelemetryEvent(Telemetry.TWO_FINGER_TAP, detector.getFocalPoint()); - // Rotate the map + PointF zoomFocalPoint; + // Single finger double tap if (focalPoint != null) { // User provided focal point - transform.setBearing(bearing, focalPoint.x, focalPoint.y); + zoomFocalPoint = focalPoint; } else { - // around gesture - transform.setBearing(bearing, detector.getFocusX(), detector.getFocusY()); + // Zoom in on gesture + zoomFocalPoint = detector.getFocalPoint(); } + + zoomOutAnimated(zoomFocalPoint, false); + return true; } + } - // Called when the fingers leave the screen - @Override - public void onRotateEnd(RotateGestureDetector detector) { - long interval = detector.getEventTime() - beginTime; - if ((!started && (interval <= ViewConfiguration.getTapTimeout())) || scaleAnimating || interval > 500) { - reset(); - return; + private Animator createScaleAnimator(double currentZoom, double zoomAddition, final PointF animationFocalPoint, + long animationTime) { + ValueAnimator animator = ValueAnimator.ofFloat((float) currentZoom, (float) (currentZoom + zoomAddition)); + animator.setDuration(animationTime); + animator.setInterpolator(new DecelerateInterpolator()); + animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { + + @Override + public void onAnimationUpdate(ValueAnimator animation) { + transform.setZoom((Float) animation.getAnimatedValue(), animationFocalPoint); } + }); + + animator.addListener(new AnimatorListenerAdapter() { - double angularVelocity = calculateVelocityVector(detector); - if (Math.abs(angularVelocity) > 0.001 && rotateGestureOccurred && !rotateAnimating) { - animateRotateVelocity(); - } else if (!rotateAnimating) { - reset(); + @Override + public void onAnimationStart(Animator animation) { + transform.cancelTransitions(); + cameraChangeDispatcher.onCameraMoveStarted(REASON_API_ANIMATION); } - } - private void reset() { - beginTime = 0; - started = false; - rotateAnimating = false; - rotateGestureOccurred = false; + @Override + public void onAnimationCancel(Animator animation) { + transform.cancelTransitions(); + } - if (!twoTap) { + @Override + public void onAnimationEnd(Animator animation) { cameraChangeDispatcher.onCameraIdle(); } + }); + return animator; + } + + /** + * Zoom in by 1. + * + * @param zoomFocalPoint focal point of zoom animation + * @param runImmediately if true, animation will be started right away, otherwise it will wait until + * {@link MotionEvent#ACTION_UP} is registered. + */ + void zoomInAnimated(PointF zoomFocalPoint, boolean runImmediately) { + zoomAnimated(true, zoomFocalPoint, runImmediately); + } + + /** + * Zoom out by 1. + * + * @param zoomFocalPoint focal point of zoom animation + * @param runImmediately if true, animation will be started right away, otherwise it will wait until + * {@link MotionEvent#ACTION_UP} is registered. + */ + void zoomOutAnimated(PointF zoomFocalPoint, boolean runImmediately) { + zoomAnimated(false, zoomFocalPoint, runImmediately); + } + + private void zoomAnimated(boolean zoomIn, PointF zoomFocalPoint, boolean runImmediately) { + //canceling here as well, because when using a button it will not be canceled automatically by onDown() + cancelAnimator(scaleAnimator); + + double currentZoom = transform.getRawZoom(); + scaleAnimator = createScaleAnimator( + currentZoom, + zoomIn ? 1 : -1, + zoomFocalPoint, + MapboxConstants.ANIMATION_DURATION); + if (runImmediately) { + scaleAnimator.start(); + } else { + scheduleAnimator(scaleAnimator); } + } - private void animateRotateVelocity() { - rotateAnimating = true; - double currentRotation = transform.getRawBearing(); - double rotateAdditionDegrees = calculateVelocityInDegrees(); - createAnimator(currentRotation, rotateAdditionDegrees).start(); + private void sendTelemetryEvent(String eventType, PointF focalPoint) { + if (isZoomValid(transform)) { + MapEventFactory mapEventFactory = new MapEventFactory(); + LatLng latLng = projection.fromScreenLocation(focalPoint); + MapState state = new MapState(latLng.getLatitude(), latLng.getLongitude(), transform.getZoom()); + state.setGesture(eventType); + Telemetry.obtainTelemetry().push(mapEventFactory.createMapGestureEvent(Event.Type.MAP_CLICK, state)); } + } - private double calculateVelocityVector(RotateGestureDetector detector) { - return ((detector.getFocusX() * velocityTracker.getYVelocity()) - + (detector.getFocusY() * velocityTracker.getXVelocity())) - / (Math.pow(detector.getFocusX(), 2) + Math.pow(detector.getFocusY(), 2)); + private boolean isZoomValid(Transform transform) { + if (transform == null) { + return false; } + double mapZoom = transform.getZoom(); + return mapZoom >= MapboxConstants.MINIMUM_ZOOM && mapZoom <= MapboxConstants.MAXIMUM_ZOOM; + } - private double calculateVelocityInDegrees() { - double angleRadians = Math.atan2(velocityTracker.getXVelocity(), velocityTracker.getYVelocity()); - double angle = angleRadians / (Math.PI / 180); - if (angle <= 0) { - angle += 360; - } + void notifyOnMapClickListeners(PointF tapPoint) { + // deprecated API + if (onMapClickListener != null) { + onMapClickListener.onMapClick(projection.fromScreenLocation(tapPoint)); + } - // limit the angle - angle = angle / ROTATE_LIMITATION_ANGLE; + // new API + for (MapboxMap.OnMapClickListener listener : onMapClickListenerList) { + listener.onMapClick(projection.fromScreenLocation(tapPoint)); + } + } - // correct direction - if (!wasClockwiseRotating) { - angle = -angle; - } + void notifyOnMapLongClickListeners(PointF longClickPoint) { + // deprecated API + if (onMapLongClickListener != null) { + onMapLongClickListener.onMapLongClick(projection.fromScreenLocation(longClickPoint)); + } - return angle; + // new API + for (MapboxMap.OnMapLongClickListener listener : onMapLongClickListenerList) { + listener.onMapLongClick(projection.fromScreenLocation(longClickPoint)); } + } - private Animator createAnimator(double currentRotation, double rotateAdditionDegrees) { - ValueAnimator animator = ValueAnimator.ofFloat( - (float) currentRotation, - (float) (currentRotation + rotateAdditionDegrees) - ); - animator.setDuration((long) (Math.abs(rotateAdditionDegrees) * ROTATE_LIMITATION_DURATION)); - animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(ValueAnimator animation) { - transform.setBearing((Float) animation.getAnimatedValue()); - } - }); - animator.addListener(new AnimatorListenerAdapter() { + void notifyOnFlingListeners() { + // deprecated API + if (onFlingListener != null) { + onFlingListener.onFling(); + } - @Override - public void onAnimationStart(Animator animation) { - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_ANIMATION); - } + // new API + for (MapboxMap.OnFlingListener listener : onFlingListenerList) { + listener.onFling(); + } + } - @Override - public void onAnimationCancel(Animator animation) { - reset(); - } + void notifyOnScrollListeners() { + //deprecated API + if (onScrollListener != null) { + onScrollListener.onScroll(); + } - @Override - public void onAnimationEnd(Animator animation) { - reset(); - } - }); - return animator; + // new API + for (MapboxMap.OnScrollListener listener : onScrollListenerList) { + listener.onScroll(); } } - /** - * Responsible for handling 2 finger shove gestures. - */ - private class ShoveGestureListener implements ShoveGestureDetector.OnShoveGestureListener { + void notifyOnMoveBeginListeners(MoveGestureDetector detector) { + for (MapboxMap.OnMoveListener listener : onMoveListenerList) { + listener.onMoveBegin(detector); + } + } - private long beginTime = 0; - private float totalDelta = 0.0f; + void notifyOnMoveListeners(MoveGestureDetector detector) { + for (MapboxMap.OnMoveListener listener : onMoveListenerList) { + listener.onMove(detector); + } + } - @Override - public boolean onShoveBegin(ShoveGestureDetector detector) { - if (!uiSettings.isTiltGesturesEnabled()) { - return false; - } + void notifyOnMoveEndListeners(MoveGestureDetector detector) { + for (MapboxMap.OnMoveListener listener : onMoveListenerList) { + listener.onMoveEnd(detector); + } + } - // notify camera change listener - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - return true; + void notifyOnRotateBeginListeners(RotateGestureDetector detector) { + for (MapboxMap.OnRotateListener listener : onRotateListenerList) { + listener.onRotateBegin(detector); } + } - @Override - public void onShoveEnd(ShoveGestureDetector detector) { - beginTime = 0; - totalDelta = 0.0f; - tiltGestureOccurred = false; + void notifyOnRotateListeners(RotateGestureDetector detector) { + for (MapboxMap.OnRotateListener listener : onRotateListenerList) { + listener.onRotate(detector); } + } - @Override - public boolean onShove(ShoveGestureDetector detector) { - if (!uiSettings.isTiltGesturesEnabled()) { - return false; - } + void notifyOnRotateEndListeners(RotateGestureDetector detector) { + for (MapboxMap.OnRotateListener listener : onRotateListenerList) { + listener.onRotateEnd(detector); + } + } - // Ignore short touches in case it is a tap - // Also ignore small tilt - long time = detector.getEventTime(); - long interval = time - beginTime; - if (!tiltGestureOccurred && (interval <= ViewConfiguration.getTapTimeout())) { - return false; - } + void notifyOnScaleBeginListeners(StandardScaleGestureDetector detector) { + for (MapboxMap.OnScaleListener listener : onScaleListenerList) { + listener.onScaleBegin(detector); + } + } - // If tilt is large enough ignore a tap - // Also if zoom already started, don't tilt - totalDelta += detector.getShovePixelsDelta(); - if (!tiltGestureOccurred && ((totalDelta > 10.0f) || (totalDelta < -10.0f))) { - tiltGestureOccurred = true; - beginTime = detector.getEventTime(); - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapClickEvent( - getLocationFromGesture(detector.getFocusX(), detector.getFocusY()), - MapboxEvent.GESTURE_PITCH_START, transform)); - } + void notifyOnScaleListeners(StandardScaleGestureDetector detector) { + for (MapboxMap.OnScaleListener listener : onScaleListenerList) { + listener.onScale(detector); + } + } - if (!tiltGestureOccurred) { - return false; - } + void notifyOnScaleEndListeners(StandardScaleGestureDetector detector) { + for (MapboxMap.OnScaleListener listener : onScaleListenerList) { + listener.onScaleEnd(detector); + } + } - // Get tilt value (scale and clamp) - double pitch = transform.getTilt(); - pitch -= 0.1 * detector.getShovePixelsDelta(); - pitch = Math.max(MapboxConstants.MINIMUM_TILT, Math.min(MapboxConstants.MAXIMUM_TILT, pitch)); + void notifyOnShoveBeginListeners(ShoveGestureDetector detector) { + for (MapboxMap.OnShoveListener listener : onShoveListenerList) { + listener.onShoveBegin(detector); + } + } - // Tilt the map - transform.setTilt(pitch); - return true; + void notifyOnShoveListeners(ShoveGestureDetector detector) { + for (MapboxMap.OnShoveListener listener : onShoveListenerList) { + listener.onShove(detector); + } + } + + void notifyOnShoveEndListeners(ShoveGestureDetector detector) { + for (MapboxMap.OnShoveListener listener : onShoveListenerList) { + listener.onShoveEnd(detector); } } @@ -963,4 +1069,46 @@ final class MapGestureDetector { void removeOnScrollListener(MapboxMap.OnScrollListener onScrollListener) { onScrollListenerList.remove(onScrollListener); } -} + + void addOnMoveListener(MapboxMap.OnMoveListener listener) { + onMoveListenerList.add(listener); + } + + void removeOnMoveListener(MapboxMap.OnMoveListener listener) { + onMoveListenerList.remove(listener); + } + + void addOnRotateListener(MapboxMap.OnRotateListener listener) { + onRotateListenerList.add(listener); + } + + void removeOnRotateListener(MapboxMap.OnRotateListener listener) { + onRotateListenerList.remove(listener); + } + + void addOnScaleListener(MapboxMap.OnScaleListener listener) { + onScaleListenerList.add(listener); + } + + void removeOnScaleListener(MapboxMap.OnScaleListener listener) { + onScaleListenerList.remove(listener); + } + + void addShoveListener(MapboxMap.OnShoveListener listener) { + onShoveListenerList.add(listener); + } + + void removeShoveListener(MapboxMap.OnShoveListener listener) { + onShoveListenerList.remove(listener); + } + + AndroidGesturesManager getGesturesManager() { + return gesturesManager; + } + + void setGesturesManager(Context context, AndroidGesturesManager gesturesManager, boolean attachDefaultListeners, + boolean setDefaultMutuallyExclusives) { + initializeGesturesManager(gesturesManager, setDefaultMutuallyExclusives); + initializeGestureListeners(context, attachDefaultListeners); + } +}
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapKeyListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapKeyListener.java index d1f01a30f7..08110ff326 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapKeyListener.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapKeyListener.java @@ -13,24 +13,22 @@ import android.view.ViewConfiguration; * <p> * <ul> * <li> Uses {@link Transform} to change the map state</li> - * <li> Uses {@link TrackingSettings} to verify validity of the current tracking mode.</li> * <li> Uses {@link UiSettings} to verify validity of user restricted movement.</li> * </ul> * <p> */ final class MapKeyListener { - private final TrackingSettings trackingSettings; private final Transform transform; private final UiSettings uiSettings; + private final MapGestureDetector mapGestureDetector; private TrackballLongPressTimeOut currentTrackballLongPressTimeOut; - MapKeyListener(@NonNull Transform transform, @NonNull TrackingSettings trackingSettings, - @NonNull UiSettings uiSettings) { + MapKeyListener(Transform transform, UiSettings uiSettings, MapGestureDetector mapGestureDetector) { this.transform = transform; - this.trackingSettings = trackingSettings; this.uiSettings = uiSettings; + this.mapGestureDetector = mapGestureDetector; } /** @@ -55,7 +53,7 @@ final class MapKeyListener { return true; case KeyEvent.KEYCODE_DPAD_LEFT: - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } @@ -67,7 +65,7 @@ final class MapKeyListener { return true; case KeyEvent.KEYCODE_DPAD_RIGHT: - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } @@ -79,7 +77,7 @@ final class MapKeyListener { return true; case KeyEvent.KEYCODE_DPAD_UP: - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } @@ -91,7 +89,7 @@ final class MapKeyListener { return true; case KeyEvent.KEYCODE_DPAD_DOWN: - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } @@ -128,7 +126,7 @@ final class MapKeyListener { // Zoom out PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - transform.zoom(false, focalPoint); + mapGestureDetector.zoomOutAnimated(focalPoint, true); return true; default: @@ -164,7 +162,7 @@ final class MapKeyListener { // Zoom in PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - transform.zoom(true, focalPoint); + mapGestureDetector.zoomInAnimated(focalPoint, true); return true; } @@ -183,7 +181,7 @@ final class MapKeyListener { switch (event.getActionMasked()) { // The trackball was rotated case MotionEvent.ACTION_MOVE: - if (!trackingSettings.isScrollGestureCurrentlyEnabled()) { + if (!uiSettings.isScrollGesturesEnabled()) { return false; } @@ -219,7 +217,7 @@ final class MapKeyListener { if (currentTrackballLongPressTimeOut != null) { // Zoom in PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - transform.zoom(true, focalPoint); + mapGestureDetector.zoomInAnimated(focalPoint, true); } return true; @@ -261,7 +259,7 @@ final class MapKeyListener { if (!cancelled) { // Zoom out PointF pointF = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - transform.zoom(false, pointF); + mapGestureDetector.zoomOutAnimated(pointF, true); // Ensure the up action is not run currentTrackballLongPressTimeOut = null; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapView.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapView.java index 3c5b82c3b0..22d5dd8f19 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapView.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapView.java @@ -23,6 +23,12 @@ import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ZoomButtonsController; +import com.mapbox.android.gestures.AndroidGesturesManager; +import com.mapbox.android.telemetry.AppUserTurnstile; +import com.mapbox.android.telemetry.Event; +import com.mapbox.android.telemetry.MapEventFactory; +import com.mapbox.android.telemetry.MapboxTelemetry; +import com.mapbox.mapboxsdk.BuildConfig; import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.annotations.Annotation; import com.mapbox.mapboxsdk.annotations.MarkerViewManager; @@ -32,11 +38,8 @@ import com.mapbox.mapboxsdk.maps.renderer.MapRenderer; import com.mapbox.mapboxsdk.maps.renderer.glsurfaceview.GLSurfaceViewMapRenderer; import com.mapbox.mapboxsdk.maps.renderer.textureview.TextureViewMapRenderer; import com.mapbox.mapboxsdk.maps.widgets.CompassView; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationView; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationViewSettings; import com.mapbox.mapboxsdk.net.ConnectivityReceiver; import com.mapbox.mapboxsdk.storage.FileSource; -import com.mapbox.services.android.telemetry.MapboxTelemetry; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -78,7 +81,6 @@ public class MapView extends FrameLayout { private boolean destroyed; private boolean hasSurface; - private MyLocationView myLocationView; private CompassView compassView; private PointF focalPoint; private ImageView attrView; @@ -126,7 +128,6 @@ public class MapView extends FrameLayout { // inflate view View view = LayoutInflater.from(context).inflate(R.layout.mapbox_mapview_internal, this); compassView = (CompassView) view.findViewById(R.id.compassView); - myLocationView = (MyLocationView) view.findViewById(R.id.userLocationView); attrView = (ImageView) view.findViewById(R.id.attributionView); logoView = (ImageView) view.findViewById(R.id.logoView); @@ -146,10 +147,7 @@ public class MapView extends FrameLayout { focalPointInvalidator.addListener(createFocalPointChangeListener()); // callback for registering touch listeners - RegisterTouchListener registerTouchListener = new RegisterTouchListener(); - - // callback for zooming in the camera - CameraZoomInvalidator zoomInvalidator = new CameraZoomInvalidator(); + GesturesManagerInteractionListener registerTouchListener = new GesturesManagerInteractionListener(); // callback for camera change events final CameraChangeDispatcher cameraChangeDispatcher = new CameraChangeDispatcher(); @@ -157,10 +155,6 @@ public class MapView extends FrameLayout { // setup components for MapboxMap creation Projection proj = new Projection(nativeMapView); UiSettings uiSettings = new UiSettings(proj, focalPointInvalidator, compassView, attrView, logoView); - TrackingSettings trackingSettings = new TrackingSettings(myLocationView, uiSettings, focalPointInvalidator, - zoomInvalidator); - MyLocationViewSettings myLocationViewSettings = new MyLocationViewSettings(myLocationView, proj, - focalPointInvalidator); LongSparseArray<Annotation> annotationsArray = new LongSparseArray<>(); MarkerViewManager markerViewManager = new MarkerViewManager((ViewGroup) findViewById(R.id.markerViewContainer)); IconManager iconManager = new IconManager(nativeMapView); @@ -171,31 +165,29 @@ public class MapView extends FrameLayout { ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(nativeMapView, annotationsArray); AnnotationManager annotationManager = new AnnotationManager(nativeMapView, this, annotationsArray, markerViewManager, iconManager, annotations, markers, polygons, polylines, shapeAnnotations); - Transform transform = new Transform(nativeMapView, annotationManager.getMarkerViewManager(), trackingSettings, + Transform transform = new Transform(nativeMapView, annotationManager.getMarkerViewManager(), cameraChangeDispatcher); - mapboxMap = new MapboxMap(nativeMapView, transform, uiSettings, trackingSettings, myLocationViewSettings, proj, - registerTouchListener, annotationManager, cameraChangeDispatcher); - focalPointInvalidator.addListener(mapboxMap.createFocalPointChangeListener()); + mapboxMap = new MapboxMap(nativeMapView, transform, uiSettings, proj, registerTouchListener, + annotationManager, cameraChangeDispatcher); mapCallback.attachMapboxMap(mapboxMap); // user input - mapGestureDetector = new MapGestureDetector(context, transform, proj, uiSettings, trackingSettings, + mapGestureDetector = new MapGestureDetector(context, transform, proj, uiSettings, annotationManager, cameraChangeDispatcher); - mapKeyListener = new MapKeyListener(transform, trackingSettings, uiSettings); + mapKeyListener = new MapKeyListener(transform, uiSettings, mapGestureDetector); // overlain zoom buttons mapZoomButtonController = new MapZoomButtonController(new ZoomButtonsController(this)); - MapZoomControllerListener zoomListener = new MapZoomControllerListener(mapGestureDetector, uiSettings, transform, - cameraChangeDispatcher, getWidth(), getHeight()); + MapZoomControllerListener zoomListener = new MapZoomControllerListener( + mapGestureDetector, cameraChangeDispatcher, getWidth(), getHeight()); mapZoomButtonController.bind(uiSettings, zoomListener); compassView.injectCompassAnimationListener(createCompassAnimationListener(cameraChangeDispatcher)); compassView.setOnClickListener(createCompassClickListener(cameraChangeDispatcher)); // inject widgets with MapboxMap - myLocationView.setMapboxMap(mapboxMap); - attrView.setOnClickListener(new AttributionDialogManager(context, mapboxMap)); + attrView.setOnClickListener(new AttributionClickListener(context, mapboxMap)); // Ensure this view is interactable setClickable(true); @@ -265,7 +257,7 @@ public class MapView extends FrameLayout { /** * <p> * You must call this method from the parent's Activity#onCreate(Bundle)} or - * Fragment#onCreate(Bundle). + * Fragment#onViewCreated(View, Bundle). * </p> * You must set a valid access token with {@link com.mapbox.mapboxsdk.Mapbox#getInstance(Context, String)} * before you call this method or an exception will be thrown. @@ -276,7 +268,12 @@ public class MapView extends FrameLayout { @UiThread public void onCreate(@Nullable Bundle savedInstanceState) { if (savedInstanceState == null) { - MapboxTelemetry.getInstance().pushEvent(MapboxEventWrapper.buildMapLoadEvent()); + MapboxTelemetry telemetry = Telemetry.obtainTelemetry(); + AppUserTurnstile turnstileEvent = new AppUserTurnstile(BuildConfig.MAPBOX_SDK_IDENTIFIER, + BuildConfig.MAPBOX_SDK_VERSION); + telemetry.push(turnstileEvent); + MapEventFactory mapEventFactory = new MapEventFactory(); + telemetry.push(mapEventFactory.createMapLoadEvent(Event.Type.MAP_LOAD)); } else if (savedInstanceState.getBoolean(MapboxConstants.STATE_HAS_SAVED_STATE)) { this.savedInstanceState = savedInstanceState; } @@ -285,10 +282,12 @@ public class MapView extends FrameLayout { private void initialiseDrawingSurface(MapboxMapOptions options) { if (options.getTextureMode()) { TextureView textureView = new TextureView(getContext()); - mapRenderer = new TextureViewMapRenderer(getContext(), textureView, options.getLocalIdeographFontFamily()) { + String localFontFamily = options.getLocalIdeographFontFamily(); + boolean translucentSurface = options.getTranslucentTextureSurface(); + mapRenderer = new TextureViewMapRenderer(getContext(), textureView, localFontFamily, translucentSurface) { @Override protected void onSurfaceCreated(GL10 gl, EGLConfig config) { - initRenderSurface(); + MapView.this.onSurfaceCreated(); super.onSurfaceCreated(gl, config); } }; @@ -300,7 +299,7 @@ public class MapView extends FrameLayout { mapRenderer = new GLSurfaceViewMapRenderer(getContext(), glSurfaceView, options.getLocalIdeographFontFamily()) { @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { - initRenderSurface(); + MapView.this.onSurfaceCreated(); super.onSurfaceCreated(gl, config); } }; @@ -312,14 +311,14 @@ public class MapView extends FrameLayout { nativeMapView.resizeView(getMeasuredWidth(), getMeasuredHeight()); } - private void initRenderSurface() { + private void onSurfaceCreated() { hasSurface = true; post(new Runnable() { @Override public void run() { // Initialise only when not destroyed and only once if (!destroyed && mapboxMap == null) { - initialiseMap(); + MapView.this.initialiseMap(); mapboxMap.onStart(); } } @@ -383,6 +382,7 @@ public class MapView extends FrameLayout { public void onStop() { if (mapboxMap != null) { // map was destroyed before it was started + mapGestureDetector.cancelAnimators(); mapboxMap.onStop(); } @@ -916,7 +916,7 @@ public class MapView extends FrameLayout { } } - private class RegisterTouchListener implements MapboxMap.OnRegisterTouchListener { + private class GesturesManagerInteractionListener implements MapboxMap.OnGesturesManagerInteractionListener { @Override public void onSetMapClickListener(MapboxMap.OnMapClickListener listener) { @@ -977,22 +977,75 @@ public class MapView extends FrameLayout { public void onRemoveFlingListener(MapboxMap.OnFlingListener listener) { mapGestureDetector.removeOnFlingListener(listener); } + + @Override + public void onAddMoveListener(MapboxMap.OnMoveListener listener) { + mapGestureDetector.addOnMoveListener(listener); + } + + @Override + public void onRemoveMoveListener(MapboxMap.OnMoveListener listener) { + mapGestureDetector.removeOnMoveListener(listener); + } + + @Override + public void onAddRotateListener(MapboxMap.OnRotateListener listener) { + mapGestureDetector.addOnRotateListener(listener); + } + + @Override + public void onRemoveRotateListener(MapboxMap.OnRotateListener listener) { + mapGestureDetector.removeOnRotateListener(listener); + } + + @Override + public void onAddScaleListener(MapboxMap.OnScaleListener listener) { + mapGestureDetector.addOnScaleListener(listener); + } + + @Override + public void onRemoveScaleListener(MapboxMap.OnScaleListener listener) { + mapGestureDetector.removeOnScaleListener(listener); + } + + @Override + public void onAddShoveListener(MapboxMap.OnShoveListener listener) { + mapGestureDetector.addShoveListener(listener); + } + + @Override + public void onRemoveShoveListener(MapboxMap.OnShoveListener listener) { + mapGestureDetector.removeShoveListener(listener); + } + + @Override + public AndroidGesturesManager getGesturesManager() { + return mapGestureDetector.getGesturesManager(); + } + + @Override + public void setGesturesManager(AndroidGesturesManager gesturesManager, boolean attachDefaultListeners, + boolean setDefaultMutuallyExclusives) { + mapGestureDetector.setGesturesManager( + getContext(), gesturesManager, attachDefaultListeners, setDefaultMutuallyExclusives); + } + + @Override + public void cancelAllVelocityAnimations() { + mapGestureDetector.cancelAnimators(); + } } private static class MapZoomControllerListener implements ZoomButtonsController.OnZoomListener { private final MapGestureDetector mapGestureDetector; - private final UiSettings uiSettings; - private final Transform transform; private final CameraChangeDispatcher cameraChangeDispatcher; private final float mapWidth; private final float mapHeight; - MapZoomControllerListener(MapGestureDetector detector, UiSettings uiSettings, Transform transform, - CameraChangeDispatcher dispatcher, float mapWidth, float mapHeight) { + MapZoomControllerListener(MapGestureDetector detector, CameraChangeDispatcher dispatcher, + float mapWidth, float mapHeight) { this.mapGestureDetector = detector; - this.uiSettings = uiSettings; - this.transform = transform; this.cameraChangeDispatcher = dispatcher; this.mapWidth = mapWidth; this.mapHeight = mapHeight; @@ -1012,32 +1065,13 @@ public class MapView extends FrameLayout { } private void onZoom(boolean zoomIn, @Nullable PointF focalPoint) { - if (focalPoint != null) { - transform.zoom(zoomIn, focalPoint); - } else { - PointF centerPoint = new PointF(mapWidth / 2, mapHeight / 2); - transform.zoom(zoomIn, centerPoint); - } - } - } - - private class CameraZoomInvalidator implements TrackingSettings.CameraZoomInvalidator { - - @Override - public void zoomTo(double zoomLevel) { - Transform transform = mapboxMap.getTransform(); - double currentZoomLevel = transform.getCameraPosition().zoom; - if (currentZoomLevel < zoomLevel) { - setZoom(zoomLevel, mapGestureDetector.getFocalPoint(), transform); + if (focalPoint == null) { + focalPoint = new PointF(mapWidth / 2, mapHeight / 2); } - } - - private void setZoom(double zoomLevel, @Nullable PointF focalPoint, @NonNull Transform transform) { - if (focalPoint != null) { - transform.setZoom(zoomLevel, focalPoint); + if (zoomIn) { + mapGestureDetector.zoomInAnimated(focalPoint, true); } else { - PointF centerPoint = new PointF(getMeasuredWidth() / 2, getMeasuredHeight() / 2); - transform.setZoom(zoomLevel, centerPoint); + mapGestureDetector.zoomOutAnimated(focalPoint, true); } } } @@ -1090,4 +1124,28 @@ public class MapView extends FrameLayout { onMapReadyCallbackList.clear(); } } + + /** + * Click event hook for providing a custom attribution dialog manager. + */ + private static class AttributionClickListener implements OnClickListener { + + private final AttributionDialogManager defaultDialogManager; + private UiSettings uiSettings; + + private AttributionClickListener(Context context, MapboxMap mapboxMap) { + this.defaultDialogManager = new AttributionDialogManager(context, mapboxMap); + this.uiSettings = mapboxMap.getUiSettings(); + } + + @Override + public void onClick(View v) { + AttributionDialogManager customDialogManager = uiSettings.getAttributionDialogManager(); + if (customDialogManager != null) { + uiSettings.getAttributionDialogManager().onClick(v); + } else { + defaultDialogManager.onClick(v); + } + } + } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxEventWrapper.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxEventWrapper.java deleted file mode 100644 index 6730278d79..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxEventWrapper.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.location.Location; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.services.android.telemetry.MapboxEvent; - -import java.util.Hashtable; - -/** - * Wrapper class for MapboxEvent - * <p> - * Provides facility methods to use Transform and handle the case that the zoom, required for a telemetry event, - * isn't available yet. - * </p> - */ -class MapboxEventWrapper { - - @Nullable - static Hashtable<String, Object> buildMapClickEvent( - @NonNull Location location, @NonNull String gestureId, Transform transform) { - try { - double mapZoom = transform.getZoom(); - if (mapZoom >= MapboxConstants.MINIMUM_ZOOM && mapZoom <= MapboxConstants.MAXIMUM_ZOOM) { - // validate zoom #8057 - return MapboxEvent.buildMapClickEvent(location, gestureId, transform.getZoom()); - } - } catch (NullPointerException exception) { - // Map/Transform is not ready yet #8650 - // returning null is valid, event is ignored. - } - return null; - } - - @Nullable - static Hashtable<String, Object> buildMapDragEndEvent( - @NonNull Location location, Transform transform) { - try { - double mapZoom = transform.getZoom(); - if (mapZoom >= MapboxConstants.MINIMUM_ZOOM && mapZoom <= MapboxConstants.MAXIMUM_ZOOM) { - // validate zoom #8057 - return MapboxEvent.buildMapDragEndEvent(location, transform.getZoom()); - } - } catch (NullPointerException exception) { - // Map/Transform is not ready yet #8650 - // returning null is valid, event is ignored. - } - return null; - } - - @Nullable - static Hashtable<String, Object> buildMapLoadEvent() { - return MapboxEvent.buildMapLoadEvent(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMap.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMap.java index a6da4c57fb..cfa7143671 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMap.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMap.java @@ -4,7 +4,6 @@ import android.content.Context; import android.graphics.Bitmap; import android.graphics.PointF; import android.graphics.RectF; -import android.location.Location; import android.os.Bundle; import android.support.annotation.FloatRange; import android.support.annotation.IntRange; @@ -16,6 +15,13 @@ import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; +import com.mapbox.android.gestures.AndroidGesturesManager; +import com.mapbox.android.gestures.MoveGestureDetector; +import com.mapbox.android.gestures.RotateGestureDetector; +import com.mapbox.android.gestures.ShoveGestureDetector; +import com.mapbox.android.gestures.StandardScaleGestureDetector; +import com.mapbox.geojson.Feature; +import com.mapbox.geojson.Geometry; import com.mapbox.mapboxsdk.annotations.Annotation; import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; import com.mapbox.mapboxsdk.annotations.BaseMarkerViewOptions; @@ -31,19 +37,13 @@ import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.camera.CameraUpdate; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.constants.MyBearingTracking; -import com.mapbox.mapboxsdk.constants.MyLocationTracking; import com.mapbox.mapboxsdk.constants.Style; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.geometry.LatLngBounds; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationViewSettings; -import com.mapbox.mapboxsdk.style.layers.Filter; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.Layer; import com.mapbox.mapboxsdk.style.light.Light; import com.mapbox.mapboxsdk.style.sources.Source; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.commons.geojson.Feature; -import com.mapbox.services.commons.geojson.Geometry; import java.lang.reflect.ParameterizedType; import java.util.HashMap; @@ -66,37 +66,30 @@ public final class MapboxMap { private final NativeMapView nativeMapView; private final UiSettings uiSettings; - private final TrackingSettings trackingSettings; private final Projection projection; private final Transform transform; private final AnnotationManager annotationManager; - private final MyLocationViewSettings myLocationViewSettings; private final CameraChangeDispatcher cameraChangeDispatcher; - private final OnRegisterTouchListener onRegisterTouchListener; + private final OnGesturesManagerInteractionListener onGesturesManagerInteractionListener; private MapboxMap.OnFpsChangedListener onFpsChangedListener; - private PointF focalPoint; - MapboxMap(NativeMapView map, Transform transform, UiSettings ui, TrackingSettings tracking, - MyLocationViewSettings myLocationView, Projection projection, OnRegisterTouchListener listener, - AnnotationManager annotations, CameraChangeDispatcher cameraChangeDispatcher) { + MapboxMap(NativeMapView map, Transform transform, UiSettings ui, Projection projection, + OnGesturesManagerInteractionListener listener, AnnotationManager annotations, + CameraChangeDispatcher cameraChangeDispatcher) { this.nativeMapView = map; this.uiSettings = ui; - this.trackingSettings = tracking; this.projection = projection; - this.myLocationViewSettings = myLocationView; this.annotationManager = annotations.bind(this); this.transform = transform; - this.onRegisterTouchListener = listener; + this.onGesturesManagerInteractionListener = listener; this.cameraChangeDispatcher = cameraChangeDispatcher; } void initialise(@NonNull Context context, @NonNull MapboxMapOptions options) { transform.initialise(this, options); uiSettings.initialise(context, options); - myLocationViewSettings.initialise(options); - trackingSettings.initialise(options); // Map configuration setDebugActive(options.getDebugActive()); @@ -110,7 +103,6 @@ public final class MapboxMap { */ void onStart() { nativeMapView.update(); - trackingSettings.onStart(); if (TextUtils.isEmpty(nativeMapView.getStyleUrl()) && TextUtils.isEmpty(nativeMapView.getStyleJson())) { // if user hasn't loaded a Style yet nativeMapView.setStyleUrl(Style.MAPBOX_STREETS); @@ -121,7 +113,6 @@ public final class MapboxMap { * Called when the hosting Activity/Fragment onStop() method is called. */ void onStop() { - trackingSettings.onStop(); } /** @@ -133,9 +124,7 @@ public final class MapboxMap { outState.putParcelable(MapboxConstants.STATE_CAMERA_POSITION, transform.getCameraPosition()); outState.putBoolean(MapboxConstants.STATE_DEBUG_ACTIVE, nativeMapView.getDebug()); outState.putString(MapboxConstants.STATE_STYLE_URL, nativeMapView.getStyleUrl()); - trackingSettings.onSaveInstanceState(outState); uiSettings.onSaveInstanceState(outState); - myLocationViewSettings.onSaveInstanceState(outState); } /** @@ -146,9 +135,7 @@ public final class MapboxMap { void onRestoreInstanceState(Bundle savedInstanceState) { final CameraPosition cameraPosition = savedInstanceState.getParcelable(MapboxConstants.STATE_CAMERA_POSITION); - myLocationViewSettings.onRestoreInstanceState(savedInstanceState); uiSettings.onRestoreInstanceState(savedInstanceState); - trackingSettings.onRestoreInstanceState(savedInstanceState); if (cameraPosition != null) { moveCamera(CameraUpdateFactory.newCameraPosition( @@ -188,7 +175,6 @@ public final class MapboxMap { * Called when the region is changing or has changed. */ void onUpdateRegionChange() { - trackingSettings.update(); annotationManager.update(); } @@ -556,38 +542,6 @@ public final class MapboxMap { } // - // TrackingSettings - // - - /** - * Gets the tracking interface settings for the map. - * - * @return the TrackingSettings asssociated with this map - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public TrackingSettings getTrackingSettings() { - return trackingSettings; - } - - // - // MyLocationViewSettings - // - - /** - * Gets the settings of the user location for the map. - * - * @return the MyLocationViewSettings associated with this map - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public MyLocationViewSettings getMyLocationViewSettings() { - return myLocationViewSettings; - } - - // // Projection // @@ -602,7 +556,7 @@ public final class MapboxMap { } // - // + // Light // /** @@ -620,47 +574,6 @@ public final class MapboxMap { // /** - * Moves the center of the screen to a latitude and longitude specified by a LatLng object. This centers the - * camera on the LatLng object. - * - * @param latLng Target location to change to - */ - public void setLatLng(@NonNull LatLng latLng) { - nativeMapView.setLatLng(latLng); - } - - /** - * Moves the camera viewpoint to a particular zoom level. - * - * @param zoom Zoom level to change to - */ - public void setZoom(@FloatRange(from = MapboxConstants.MINIMUM_ZOOM, to = MapboxConstants.MAXIMUM_ZOOM) double zoom) { - if (focalPoint == null) { - focalPoint = new PointF(nativeMapView.getWidth() / 2, nativeMapView.getHeight() / 2); - } - nativeMapView.setZoom(zoom, focalPoint, 0); - } - - /** - * Moves the camera viewpoint angle to a particular angle in degrees. - * - * @param tilt Tilt angle to change to - */ - public void setTilt(@FloatRange(from = MapboxConstants.MINIMUM_TILT, to = MapboxConstants.MAXIMUM_TILT) double tilt) { - nativeMapView.setPitch(tilt, 0); - } - - /** - * Moves the camera viewpoint direction to a particular angle in degrees. - * - * @param bearing Direction angle to change to - */ - public void setBearing(@FloatRange(from = MapboxConstants.MINIMUM_DIRECTION, to = MapboxConstants.MAXIMUM_DIRECTION) - double bearing) { - nativeMapView.setBearing(bearing); - } - - /** * Cancels ongoing animations. * <p> * This invokes the {@link CancelableCallback} for ongoing camera updates. @@ -787,11 +700,6 @@ public final class MapboxMap { * unless specified within {@link CameraUpdate}. A callback can be used to be notified when * easing the camera stops. If {@link #getCameraPosition()} is called during the animation, it * will return the current location of the camera in flight. - * <p> - * Note that this will cancel location tracking mode if enabled. You can change this behaviour by calling - * {@link com.mapbox.mapboxsdk.maps.TrackingSettings#setDismissLocationTrackingOnGesture(boolean)} with false before - * invoking this method and calling it with true in the {@link CancelableCallback#onFinish()}. - * </p> * * @param update The change that should be applied to the camera. * @param durationMs The duration of the animation in milliseconds. This must be strictly @@ -813,11 +721,6 @@ public final class MapboxMap { * unless specified within {@link CameraUpdate}. A callback can be used to be notified when * easing the camera stops. If {@link #getCameraPosition()} is called during the animation, it * will return the current location of the camera in flight. - * <p> - * Note that this will cancel location tracking mode if enabled. You can change this behaviour by calling - * {@link com.mapbox.mapboxsdk.maps.TrackingSettings#setDismissLocationTrackingOnGesture(boolean)} with false before - * invoking this method and calling it with true in the {@link CancelableCallback#onFinish()}. - * </p> * * @param update The change that should be applied to the camera. * @param durationMs The duration of the animation in milliseconds. This must be strictly @@ -1647,20 +1550,9 @@ public final class MapboxMap { * @param padding the padding to apply to the bounds * @return the camera position that fits the bounds and padding */ - public CameraPosition getCameraForLatLngBounds(@Nullable LatLngBounds latLngBounds, int[] padding) { - // calculate and set additional bounds padding - int[] mapPadding = getPadding(); - for (int i = 0; i < padding.length; i++) { - padding[i] = mapPadding[i] + padding[i]; - } - projection.setContentPadding(padding, myLocationViewSettings.getPadding()); - + public CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds latLngBounds, int[] padding) { // get padded camera position from LatLngBounds - CameraPosition cameraPosition = nativeMapView.getCameraForLatLngBounds(latLngBounds); - - // reset map padding - setPadding(mapPadding); - return cameraPosition; + return nativeMapView.getCameraForLatLngBounds(latLngBounds, padding); } /** @@ -1672,19 +1564,8 @@ public final class MapboxMap { * @return the camera position that fits the bounds and padding */ public CameraPosition getCameraForGeometry(Geometry geometry, double bearing, int[] padding) { - // calculate and set additional bounds padding - int[] mapPadding = getPadding(); - for (int i = 0; i < padding.length; i++) { - padding[i] = mapPadding[i] + padding[i]; - } - projection.setContentPadding(padding, myLocationViewSettings.getPadding()); - - // get padded camera position from LatLngBounds - CameraPosition cameraPosition = nativeMapView.getCameraForGeometry(geometry, bearing); - - // reset map padding - setPadding(mapPadding); - return cameraPosition; + // get padded camera position from Geometry + return nativeMapView.getCameraForGeometry(geometry, bearing, padding); } // @@ -1693,13 +1574,13 @@ public final class MapboxMap { /** * <p> - * Sets the distance from the edges of the map view’s frame to the edges of the map - * view’s logical viewport. + * Sets the distance from the edges of the map view's frame to the edges of the map + * view's logical viewport. * </p> * <p> * When the value of this property is equal to {0,0,0,0}, viewport - * properties such as `centerCoordinate` assume a viewport that matches the map - * view’s frame. Otherwise, those properties are inset, excluding part of the + * properties such as 'centerCoordinate' assume a viewport that matches the map + * view's frame. Otherwise, those properties are inset, excluding part of the * frame from the viewport. For instance, if the only the top edge is inset, the * map center is effectively shifted downward. * </p> @@ -1714,7 +1595,7 @@ public final class MapboxMap { } private void setPadding(int[] padding) { - projection.setContentPadding(padding, myLocationViewSettings.getPadding()); + projection.setContentPadding(padding); uiSettings.invalidate(); } @@ -1759,7 +1640,7 @@ public final class MapboxMap { * * @param listener the listener to notify */ - public void addOnCameraIdleListener(@Nullable OnCameraIdleListener listener) { + public void addOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { cameraChangeDispatcher.addOnCameraIdleListener(listener); } @@ -1768,7 +1649,7 @@ public final class MapboxMap { * * @param listener the listener to remove */ - public void removeOnCameraIdleListener(@Nullable OnCameraIdleListener listener) { + public void removeOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { cameraChangeDispatcher.removeOnCameraIdleListener(listener); } @@ -1789,7 +1670,7 @@ public final class MapboxMap { * * @param listener the listener to notify */ - public void addOnCameraMoveCancelListener(@Nullable OnCameraMoveCanceledListener listener) { + public void addOnCameraMoveCancelListener(@NonNull OnCameraMoveCanceledListener listener) { cameraChangeDispatcher.addOnCameraMoveCancelListener(listener); } @@ -1798,7 +1679,7 @@ public final class MapboxMap { * * @param listener the listener to remove */ - public void removeOnCameraMoveCancelListener(@Nullable OnCameraMoveCanceledListener listener) { + public void removeOnCameraMoveCancelListener(@NonNull OnCameraMoveCanceledListener listener) { cameraChangeDispatcher.removeOnCameraMoveCancelListener(listener); } @@ -1819,7 +1700,7 @@ public final class MapboxMap { * * @param listener the listener to notify */ - public void addOnCameraMoveStartedListener(@Nullable OnCameraMoveStartedListener listener) { + public void addOnCameraMoveStartedListener(@NonNull OnCameraMoveStartedListener listener) { cameraChangeDispatcher.addOnCameraMoveStartedListener(listener); } @@ -1828,7 +1709,7 @@ public final class MapboxMap { * * @param listener the listener to remove */ - public void removeOnCameraMoveStartedListener(@Nullable OnCameraMoveStartedListener listener) { + public void removeOnCameraMoveStartedListener(@NonNull OnCameraMoveStartedListener listener) { cameraChangeDispatcher.removeOnCameraMoveStartedListener(listener); } @@ -1849,7 +1730,7 @@ public final class MapboxMap { * * @param listener the listener to notify */ - public void addOnCameraMoveListener(@Nullable OnCameraMoveListener listener) { + public void addOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { cameraChangeDispatcher.addOnCameraMoveListener(listener); } @@ -1858,7 +1739,7 @@ public final class MapboxMap { * * @param listener the listener to remove */ - public void removeOnCameraMoveListener(@Nullable OnCameraMoveListener listener) { + public void removeOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { cameraChangeDispatcher.removeOnCameraMoveListener(listener); } @@ -1887,27 +1768,25 @@ public final class MapboxMap { */ @Deprecated public void setOnScrollListener(@Nullable OnScrollListener listener) { - onRegisterTouchListener.onSetScrollListener(listener); + onGesturesManagerInteractionListener.onSetScrollListener(listener); } /** * Adds a callback that's invoked when the map is scrolled. * * @param listener The callback that's invoked when the map is scrolled. - * To unset the callback, use null. */ - public void addOnScrollListener(@Nullable OnScrollListener listener) { - onRegisterTouchListener.onAddScrollListener(listener); + public void addOnScrollListener(@NonNull OnScrollListener listener) { + onGesturesManagerInteractionListener.onAddScrollListener(listener); } /** * Removes a callback that's invoked when the map is scrolled. * * @param listener The callback that's invoked when the map is scrolled. - * To unset the callback, use null. */ - public void removeOnScrollListener(@Nullable OnScrollListener listener) { - onRegisterTouchListener.onRemoveScrollListener(listener); + public void removeOnScrollListener(@NonNull OnScrollListener listener) { + onGesturesManagerInteractionListener.onRemoveScrollListener(listener); } /** @@ -1919,27 +1798,131 @@ public final class MapboxMap { */ @Deprecated public void setOnFlingListener(@Nullable OnFlingListener listener) { - onRegisterTouchListener.onSetFlingListener(listener); + onGesturesManagerInteractionListener.onSetFlingListener(listener); } /** * Adds a callback that's invoked when the map is flinged. * * @param listener The callback that's invoked when the map is flinged. - * To unset the callback, use null. */ - public void addOnFlingListener(@Nullable OnFlingListener listener) { - onRegisterTouchListener.onAddFlingListener(listener); + public void addOnFlingListener(@NonNull OnFlingListener listener) { + onGesturesManagerInteractionListener.onAddFlingListener(listener); } /** * Removes a callback that's invoked when the map is flinged. * * @param listener The callback that's invoked when the map is flinged. - * To unset the callback, use null. */ - public void removeOnFlingListener(@Nullable OnFlingListener listener) { - onRegisterTouchListener.onRemoveFlingListener(listener); + public void removeOnFlingListener(@NonNull OnFlingListener listener) { + onGesturesManagerInteractionListener.onRemoveFlingListener(listener); + } + + /** + * Adds a callback that's invoked when the map is moved. + * + * @param listener The callback that's invoked when the map is moved. + */ + public void addOnMoveListener(@NonNull OnMoveListener listener) { + onGesturesManagerInteractionListener.onAddMoveListener(listener); + } + + /** + * Removes a callback that's invoked when the map is moved. + * + * @param listener The callback that's invoked when the map is moved. + */ + public void removeOnMoveListener(@NonNull OnMoveListener listener) { + onGesturesManagerInteractionListener.onRemoveMoveListener(listener); + } + + /** + * Adds a callback that's invoked when the map is rotated. + * + * @param listener The callback that's invoked when the map is rotated. + */ + public void addOnRotateListener(@NonNull OnRotateListener listener) { + onGesturesManagerInteractionListener.onAddRotateListener(listener); + } + + /** + * Removes a callback that's invoked when the map is rotated. + * + * @param listener The callback that's invoked when the map is rotated. + */ + public void removeOnRotateListener(@NonNull OnRotateListener listener) { + onGesturesManagerInteractionListener.onRemoveRotateListener(listener); + } + + /** + * Adds a callback that's invoked when the map is scaled. + * + * @param listener The callback that's invoked when the map is scaled. + */ + public void addOnScaleListener(@NonNull OnScaleListener listener) { + onGesturesManagerInteractionListener.onAddScaleListener(listener); + } + + /** + * Removes a callback that's invoked when the map is scaled. + * + * @param listener The callback that's invoked when the map is scaled. + */ + public void removeOnScaleListener(@NonNull OnScaleListener listener) { + onGesturesManagerInteractionListener.onRemoveScaleListener(listener); + } + + /** + * Adds a callback that's invoked when the map is tilted. + * + * @param listener The callback that's invoked when the map is tilted. + */ + public void addOnShoveListener(@NonNull OnShoveListener listener) { + onGesturesManagerInteractionListener.onAddShoveListener(listener); + } + + /** + * Remove a callback that's invoked when the map is tilted. + * + * @param listener The callback that's invoked when the map is tilted. + */ + public void removeOnShoveListener(@NonNull OnShoveListener listener) { + onGesturesManagerInteractionListener.onRemoveShoveListener(listener); + } + + /** + * Sets a custom {@link AndroidGesturesManager} to handle {@link android.view.MotionEvent}s + * registered by the {@link MapView}. + * + * @param androidGesturesManager Gestures manager that interprets gestures based on the motion events. + * @param attachDefaultListeners If true, pre-defined listeners will be attach + * to change map based on {@link AndroidGesturesManager} callbacks. + * @param setDefaultMutuallyExclusives If true, pre-defined mutually exclusive gesture sets + * will be added to the passed gestures manager. + * @see <a href="https://github.com/mapbox/mapbox-gestures-android">mapbox-gestures-android library</a> + */ + public void setGesturesManager(AndroidGesturesManager androidGesturesManager, boolean attachDefaultListeners, + boolean setDefaultMutuallyExclusives) { + onGesturesManagerInteractionListener.setGesturesManager( + androidGesturesManager, attachDefaultListeners, setDefaultMutuallyExclusives); + } + + /** + * Get current {@link AndroidGesturesManager} that handles {@link android.view.MotionEvent}s + * registered by the {@link MapView} + * + * @return Current gestures manager. + */ + public AndroidGesturesManager getGesturesManager() { + return onGesturesManagerInteractionListener.getGesturesManager(); + } + + /** + * Interrupts any ongoing gesture velocity animations. + */ + public void cancelAllVelocityAnimations() { + onGesturesManagerInteractionListener.cancelAllVelocityAnimations(); } /** @@ -1951,27 +1934,25 @@ public final class MapboxMap { */ @Deprecated public void setOnMapClickListener(@Nullable OnMapClickListener listener) { - onRegisterTouchListener.onSetMapClickListener(listener); + onGesturesManagerInteractionListener.onSetMapClickListener(listener); } /** * Adds a callback that's invoked when the user clicks on the map view. * * @param listener The callback that's invoked when the user clicks on the map view. - * To unset the callback, use null. */ - public void addOnMapClickListener(@Nullable OnMapClickListener listener) { - onRegisterTouchListener.onAddMapClickListener(listener); + public void addOnMapClickListener(@NonNull OnMapClickListener listener) { + onGesturesManagerInteractionListener.onAddMapClickListener(listener); } /** * Removes a callback that's invoked when the user clicks on the map view. * * @param listener The callback that's invoked when the user clicks on the map view. - * To unset the callback, use null. */ - public void removeOnMapClickListener(@Nullable OnMapClickListener listener) { - onRegisterTouchListener.onRemoveMapClickListener(listener); + public void removeOnMapClickListener(@NonNull OnMapClickListener listener) { + onGesturesManagerInteractionListener.onRemoveMapClickListener(listener); } /** @@ -1983,27 +1964,25 @@ public final class MapboxMap { */ @Deprecated public void setOnMapLongClickListener(@Nullable OnMapLongClickListener listener) { - onRegisterTouchListener.onSetMapLongClickListener(listener); + onGesturesManagerInteractionListener.onSetMapLongClickListener(listener); } /** * Adds a callback that's invoked when the user long clicks on the map view. * * @param listener The callback that's invoked when the user long clicks on the map view. - * To unset the callback, use null. */ - public void addOnMapLongClickListener(@Nullable OnMapLongClickListener listener) { - onRegisterTouchListener.onAddMapLongClickListener(listener); + public void addOnMapLongClickListener(@NonNull OnMapLongClickListener listener) { + onGesturesManagerInteractionListener.onAddMapLongClickListener(listener); } /** * Removes a callback that's invoked when the user long clicks on the map view. * * @param listener The callback that's invoked when the user long clicks on the map view. - * To unset the callback, use null. */ - public void removeOnMapLongClickListener(@Nullable OnMapLongClickListener listener) { - onRegisterTouchListener.onRemoveMapLongClickListener(listener); + public void removeOnMapLongClickListener(@NonNull OnMapLongClickListener listener) { + onGesturesManagerInteractionListener.onRemoveMapLongClickListener(listener); } /** @@ -2064,107 +2043,6 @@ public final class MapboxMap { } // - // User location - // - - /** - * Returns the status of the my-location layer. - * - * @return True if the my-location layer is enabled, false otherwise. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public boolean isMyLocationEnabled() { - return trackingSettings.isMyLocationEnabled(); - } - - /** - * <p> - * Enables or disables the my-location layer. - * While enabled, the my-location layer continuously draws an indication of a user's current - * location and bearing. - * </p> - * In order to use the my-location layer feature you need to request permission for either - * android.Manifest.permission#ACCESS_COARSE_LOCATION or android.Manifest.permission#ACCESS_FINE_LOCATION. - * - * @param enabled True to enable; false to disable. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public void setMyLocationEnabled(boolean enabled) { - trackingSettings.setMyLocationEnabled(enabled); - } - - /** - * Returns the currently displayed user location, or null if there is no location data available. - * - * @return The currently displayed user location. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Nullable - @Deprecated - public Location getMyLocation() { - return trackingSettings.getMyLocation(); - } - - /** - * Sets a callback that's invoked when the the My Location view - * (which signifies the user's location) changes location. - * - * @param listener The callback that's invoked when the user clicks on a marker. - * To unset the callback, use null. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public void setOnMyLocationChangeListener(@Nullable MapboxMap.OnMyLocationChangeListener - listener) { - trackingSettings.setOnMyLocationChangeListener(listener); - } - - /** - * Replaces the location source of the my-location layer. - * - * @param locationSource A {@link LocationEngine} location source to use in the my-location layer. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public void setLocationSource(@Nullable LocationEngine locationSource) { - trackingSettings.setLocationSource(locationSource); - } - - /** - * Sets a callback that's invoked when the location tracking mode changes. - * - * @param listener The callback that's invoked when the location tracking mode changes. - * To unset the callback, use null. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public void setOnMyLocationTrackingModeChangeListener( - @Nullable MapboxMap.OnMyLocationTrackingModeChangeListener listener) { - trackingSettings.setOnMyLocationTrackingModeChangeListener(listener); - } - - /** - * Sets a callback that's invoked when the bearing tracking mode changes. - * - * @param listener The callback that's invoked when the bearing tracking mode changes. - * To unset the callback, use null. - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ - @Deprecated - public void setOnMyBearingTrackingModeChangeListener(@Nullable OnMyBearingTrackingModeChangeListener listener) { - trackingSettings.setOnMyBearingTrackingModeChangeListener(listener); - } - - // // Invalidate // @@ -2194,13 +2072,13 @@ public final class MapboxMap { * Queries the map for rendered features * * @param coordinates the point to query - * @param filter filters the returned features + * @param filter filters the returned features with an expression * @param layerIds optionally - only query these layers * @return the list of feature */ @NonNull public List<Feature> queryRenderedFeatures(@NonNull PointF coordinates, - @Nullable Filter.Statement filter, + @Nullable Expression filter, @Nullable String... layerIds) { return nativeMapView.queryRenderedFeatures(coordinates, layerIds, filter); } @@ -2222,26 +2100,17 @@ public final class MapboxMap { * Queries the map for rendered features * * @param coordinates the box to query - * @param filter filters the returned features + * @param filter filters the returned features with an expression * @param layerIds optionally - only query these layers * @return the list of feature */ @NonNull public List<Feature> queryRenderedFeatures(@NonNull RectF coordinates, - @Nullable Filter.Statement filter, + @Nullable Expression filter, @Nullable String... layerIds) { return nativeMapView.queryRenderedFeatures(coordinates, layerIds, filter); } - FocalPointChangeListener createFocalPointChangeListener() { - return new FocalPointChangeListener() { - @Override - public void onFocalPointChanged(PointF pointF) { - focalPoint = pointF; - } - }; - } - // // Interfaces // @@ -2262,7 +2131,9 @@ public final class MapboxMap { * Interface definition for a callback to be invoked when the map is scrolled. * * @see MapboxMap#setOnScrollListener(OnScrollListener) + * @deprecated Use {@link OnMoveListener} instead. */ + @Deprecated public interface OnScrollListener { /** * Called when the map is scrolled. @@ -2271,6 +2142,58 @@ public final class MapboxMap { } /** + * Interface definition for a callback to be invoked when the map is moved. + * + * @see MapboxMap#addOnMoveListener(OnMoveListener) + */ + public interface OnMoveListener { + void onMoveBegin(MoveGestureDetector detector); + + void onMove(MoveGestureDetector detector); + + void onMoveEnd(MoveGestureDetector detector); + } + + /** + * Interface definition for a callback to be invoked when the map is rotated. + * + * @see MapboxMap#addOnRotateListener(OnRotateListener) + */ + public interface OnRotateListener { + void onRotateBegin(RotateGestureDetector detector); + + void onRotate(RotateGestureDetector detector); + + void onRotateEnd(RotateGestureDetector detector); + } + + /** + * Interface definition for a callback to be invoked when the map is scaled. + * + * @see MapboxMap#addOnScaleListener(OnScaleListener) + */ + public interface OnScaleListener { + void onScaleBegin(StandardScaleGestureDetector detector); + + void onScale(StandardScaleGestureDetector detector); + + void onScaleEnd(StandardScaleGestureDetector detector); + } + + /** + * Interface definition for a callback to be invoked when the map is tilted. + * + * @see MapboxMap#addOnShoveListener(OnShoveListener) + */ + public interface OnShoveListener { + void onShoveBegin(ShoveGestureDetector detector); + + void onShove(ShoveGestureDetector detector); + + void onShoveEnd(ShoveGestureDetector detector); + } + + /** * Interface definition for a callback to be invoked when the camera changes position. * * @deprecated Replaced by {@link MapboxMap.OnCameraMoveStartedListener}, {@link MapboxMap.OnCameraMoveListener} and @@ -2372,7 +2295,7 @@ public final class MapboxMap { * Interface definition for a callback to be invoked when a user registers an listener that is * related to touch and click events. */ - interface OnRegisterTouchListener { + interface OnGesturesManagerInteractionListener { void onSetMapClickListener(OnMapClickListener listener); void onAddMapClickListener(OnMapClickListener listener); @@ -2396,6 +2319,29 @@ public final class MapboxMap { void onAddFlingListener(OnFlingListener listener); void onRemoveFlingListener(OnFlingListener listener); + + void onAddMoveListener(OnMoveListener listener); + + void onRemoveMoveListener(OnMoveListener listener); + + void onAddRotateListener(OnRotateListener listener); + + void onRemoveRotateListener(OnRotateListener listener); + + void onAddScaleListener(OnScaleListener listener); + + void onRemoveScaleListener(OnScaleListener listener); + + void onAddShoveListener(OnShoveListener listener); + + void onRemoveShoveListener(OnShoveListener listener); + + AndroidGesturesManager getGesturesManager(); + + void setGesturesManager(AndroidGesturesManager gesturesManager, boolean attachDefaultListeners, + boolean setDefaultMutuallyExclusives); + + void cancelAllVelocityAnimations(); } /** @@ -2668,51 +2614,6 @@ public final class MapboxMap { } /** - * Interface definition for a callback to be invoked when the the My Location view changes location. - * - * @see MapboxMap#setOnMyLocationChangeListener(OnMyLocationChangeListener) - */ - public interface OnMyLocationChangeListener { - /** - * Called when the location of the My Location view has changed - * (be it latitude/longitude, bearing or accuracy). - * - * @param location The current location of the My Location view The type of map change event. - */ - void onMyLocationChange(@Nullable Location location); - } - - /** - * Interface definition for a callback to be invoked when the the My Location tracking mode changes. - * - * @see TrackingSettings#setMyLocationTrackingMode(int) - */ - public interface OnMyLocationTrackingModeChangeListener { - - /** - * Called when the tracking mode of My Location tracking has changed - * - * @param myLocationTrackingMode the current active location tracking mode - */ - void onMyLocationTrackingModeChange(@MyLocationTracking.Mode int myLocationTrackingMode); - } - - /** - * Interface definition for a callback to be invoked when the the My Location tracking mode changes. - * - * @see TrackingSettings#setMyLocationTrackingMode(int) - */ - public interface OnMyBearingTrackingModeChangeListener { - - /** - * Called when the tracking mode of My Bearing tracking has changed - * - * @param myBearingTrackingMode the current active bearing tracking mode - */ - void onMyBearingTrackingModeChange(@MyBearingTracking.Mode int myBearingTrackingMode); - } - - /** * Interface definition for a callback to be invoked when a task is complete or cancelled. */ public interface CancelableCallback { diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java index 46dba28b98..bb4e2f9212 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java @@ -8,10 +8,8 @@ import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.ColorInt; -import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; -import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.util.AttributeSet; import android.view.Gravity; @@ -20,7 +18,6 @@ import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.utils.BitmapUtils; -import com.mapbox.mapboxsdk.utils.ColorUtils; import java.util.Arrays; @@ -68,18 +65,6 @@ public class MapboxMapOptions implements Parcelable { private boolean zoomControlsEnabled = false; private boolean doubleTapGesturesEnabled = true; - private boolean myLocationEnabled; - private Drawable myLocationForegroundDrawable; - private Drawable myLocationForegroundBearingDrawable; - private Drawable myLocationBackgroundDrawable; - @ColorInt - private int myLocationForegroundTintColor = UNDEFINED_COLOR; - @ColorInt - private int myLocationBackgroundTintColor = UNDEFINED_COLOR; - private int[] myLocationBackgroundPadding; - private int myLocationAccuracyTintColor; - private int myLocationAccuracyAlpha; - private float myLocationAccuracyThreshold; private boolean prefetchesTiles = true; private boolean zMediaOverlay = false; private String localIdeographFontFamily; @@ -87,6 +72,7 @@ public class MapboxMapOptions implements Parcelable { private String apiBaseUrl; private boolean textureMode; + private boolean translucentTextureSurface; private String style; @@ -129,33 +115,10 @@ public class MapboxMapOptions implements Parcelable { zoomGesturesEnabled = in.readByte() != 0; doubleTapGesturesEnabled = in.readByte() != 0; - myLocationEnabled = in.readByte() != 0; - - Bitmap foregroundBitmap = in.readParcelable(getClass().getClassLoader()); - if (foregroundBitmap != null) { - myLocationForegroundDrawable = new BitmapDrawable(foregroundBitmap); - } - - Bitmap foregroundBearingBitmap = in.readParcelable(getClass().getClassLoader()); - if (foregroundBearingBitmap != null) { - myLocationForegroundBearingDrawable = new BitmapDrawable(foregroundBearingBitmap); - } - - Bitmap backgroundBitmap = in.readParcelable(getClass().getClassLoader()); - if (backgroundBitmap != null) { - myLocationBackgroundDrawable = new BitmapDrawable(backgroundBitmap); - } - - myLocationForegroundTintColor = in.readInt(); - myLocationBackgroundTintColor = in.readInt(); - myLocationBackgroundPadding = in.createIntArray(); - myLocationAccuracyAlpha = in.readInt(); - myLocationAccuracyTintColor = in.readInt(); - myLocationAccuracyThreshold = in.readFloat(); - style = in.readString(); apiBaseUrl = in.readString(); textureMode = in.readByte() != 0; + translucentTextureSurface = in.readByte() != 0; prefetchesTiles = in.readByte() != 0; zMediaOverlay = in.readByte() != 0; localIdeographFontFamily = in.readString(); @@ -245,50 +208,10 @@ public class MapboxMapOptions implements Parcelable { (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiAttributionMarginBottom, FOUR_DP * pxlRatio))}); - mapboxMapOptions.locationEnabled(typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_myLocation, false)); - mapboxMapOptions.myLocationForegroundTintColor( - typedArray.getColor(R.styleable.mapbox_MapView_mapbox_myLocationTintColor, UNDEFINED_COLOR)); - mapboxMapOptions.myLocationBackgroundTintColor( - typedArray.getColor(R.styleable.mapbox_MapView_mapbox_myLocationBackgroundTintColor, UNDEFINED_COLOR)); - - Drawable foregroundDrawable = typedArray.getDrawable(R.styleable.mapbox_MapView_mapbox_myLocationDrawable); - if (foregroundDrawable == null) { - foregroundDrawable = ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_icon_default); - } - - Drawable foregroundBearingDrawable = typedArray.getDrawable( - R.styleable.mapbox_MapView_mapbox_myLocationBearingDrawable); - if (foregroundBearingDrawable == null) { - foregroundBearingDrawable = ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_icon_bearing); - } - - Drawable backgroundDrawable = typedArray.getDrawable( - R.styleable.mapbox_MapView_mapbox_myLocationBackgroundDrawable); - if (backgroundDrawable == null) { - backgroundDrawable = ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_bg_shape); - } - - mapboxMapOptions.myLocationForegroundDrawables(foregroundDrawable, foregroundBearingDrawable); - mapboxMapOptions.myLocationBackgroundDrawable(backgroundDrawable); - mapboxMapOptions.myLocationBackgroundPadding(new int[] { - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_myLocationBackgroundMarginLeft, - 0) * pxlRatio), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_myLocationBackgroundMarginTop, - 0) * pxlRatio), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_myLocationBackgroundMarginRight, - 0) * pxlRatio), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_myLocationBackgroundMarginBottom, - 0) * pxlRatio) - }); - mapboxMapOptions.myLocationAccuracyAlpha( - typedArray.getInt(R.styleable.mapbox_MapView_mapbox_myLocationAccuracyAlpha, 100)); - mapboxMapOptions.myLocationAccuracyTint( - typedArray.getColor(R.styleable.mapbox_MapView_mapbox_myLocationAccuracyTintColor, - ColorUtils.getPrimaryColor(context))); - mapboxMapOptions.myLocationAccuracyThreshold( - typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_myLocationAccuracyThreshold, 0)); mapboxMapOptions.textureMode( typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_renderTextureMode, false)); + mapboxMapOptions.translucentTextureSurface( + typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_renderTextureTranslucentSurface, false)); mapboxMapOptions.setPrefetchesTiles( typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_enableTilePrefetch, true)); mapboxMapOptions.renderSurfaceOnTop( @@ -572,128 +495,6 @@ public class MapboxMapOptions implements Parcelable { } /** - * Specifies if the user location view is enabled for a map view. - * - * @param locationEnabled True and gesture will be enabled - * @return This - */ - public MapboxMapOptions locationEnabled(boolean locationEnabled) { - this.myLocationEnabled = locationEnabled; - return this; - } - - /** - * Set the foreground drawables of the MyLocationView. - * - * @param myLocationForegroundDrawable the drawable to show as foreground without bearing - * @param myLocationBearingDrawable the drawable to show as foreground when bearing is disabled - * @return This - */ - public MapboxMapOptions myLocationForegroundDrawables(Drawable myLocationForegroundDrawable, - Drawable myLocationBearingDrawable) { - this.myLocationForegroundDrawable = myLocationForegroundDrawable; - this.myLocationForegroundBearingDrawable = myLocationBearingDrawable; - return this; - } - - /** - * Set the foreground drawable of the MyLocationView. - * <p> - * The same drawable will be used for both bearing as non bearing modes. - * </p> - * - * @param myLocationForegroundDrawable the drawable to show as foreground - * @return This - */ - public MapboxMapOptions myLocationForegroundDrawable(Drawable myLocationForegroundDrawable) { - this.myLocationForegroundDrawable = myLocationForegroundDrawable; - return this; - } - - /** - * Set the background drawable of MyLocationView. - * <p> - * Padding can be added to provide an offset to the background. - * </p> - * - * @param myLocationBackgroundDrawable the drawable to show as background - * @return This - */ - public MapboxMapOptions myLocationBackgroundDrawable(Drawable myLocationBackgroundDrawable) { - this.myLocationBackgroundDrawable = myLocationBackgroundDrawable; - return this; - } - - /** - * Set the foreground tint color of MyLocationView. - * <p> - * The color will tint both the foreground and the bearing foreground drawable. - * </p> - * - * @param myLocationForegroundTintColor the color to tint the foreground drawable - * @return This - */ - public MapboxMapOptions myLocationForegroundTintColor(@ColorInt int myLocationForegroundTintColor) { - this.myLocationForegroundTintColor = myLocationForegroundTintColor; - return this; - } - - /** - * Set the background tint color of MyLocationView. - * - * @param myLocationBackgroundTintColor the color to tint the background drawable - * @return This - */ - public MapboxMapOptions myLocationBackgroundTintColor(@ColorInt int myLocationBackgroundTintColor) { - this.myLocationBackgroundTintColor = myLocationBackgroundTintColor; - return this; - } - - /** - * Set the MyLocationView padding. - * - * @param myLocationBackgroundPadding the color to tint the background - * @return This - */ - public MapboxMapOptions myLocationBackgroundPadding(int[] myLocationBackgroundPadding) { - this.myLocationBackgroundPadding = myLocationBackgroundPadding; - return this; - } - - /** - * Set the MyLocationView accuracy circle tint color. - * - * @param myLocationAccuracyTintColor the color to tint the accuracy circle - * @return This - */ - public MapboxMapOptions myLocationAccuracyTint(@ColorInt int myLocationAccuracyTintColor) { - this.myLocationAccuracyTintColor = myLocationAccuracyTintColor; - return this; - } - - /** - * Set the MyLocationView accuracy alpha value. - * - * @param alpha the alpha value - * @return This - */ - public MapboxMapOptions myLocationAccuracyAlpha(@IntRange(from = 0, to = 255) int alpha) { - this.myLocationAccuracyAlpha = alpha; - return this; - } - - /** - * Set accuracy circle threshold. Circle won't be displayed if accuracy is below set value. - * - * @param myLocationAccuracyThreshold Value of accuracy (in meters), below which circle won't be displayed - * @return This - */ - public MapboxMapOptions myLocationAccuracyThreshold(float myLocationAccuracyThreshold) { - this.myLocationAccuracyThreshold = myLocationAccuracyThreshold; - return this; - } - - /** * Enable {@link android.view.TextureView} as rendered surface. * <p> * Since the 5.2.0 release we replaced our TextureView with an {@link android.opengl.GLSurfaceView} @@ -711,6 +512,11 @@ public class MapboxMapOptions implements Parcelable { return this; } + public MapboxMapOptions translucentTextureSurface(boolean translucentTextureSurface) { + this.translucentTextureSurface = translucentTextureSurface; + return this; + } + /** * Enable tile pre-fetching. Loads tiles at a lower zoom-level to pre-render * a low resolution preview while more detailed tiles are loaded. @@ -725,11 +531,11 @@ public class MapboxMapOptions implements Parcelable { } /** - * Set the font family for generating glyphs locally for ideographs in the ‘CJK Unified Ideographs’ - * and ‘Hangul Syllables’ ranges. - * + * 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 system fonts are defined in '/system/etc/fonts.xml' * * @param fontFamily font family for local ideograph generation. * @return This @@ -976,98 +782,6 @@ public class MapboxMapOptions implements Parcelable { } /** - * Get the current configured user location view state for a map view. - * - * @return True and user location will be shown - */ - public boolean getLocationEnabled() { - return myLocationEnabled; - } - - /** - * Get the current configured MyLocationView foreground drawable. - * - * @return the drawable used as foreground - */ - public Drawable getMyLocationForegroundDrawable() { - return myLocationForegroundDrawable; - } - - /** - * Get the current configured MyLocationView foreground bearing drawable. - * - * @return the drawable used as foreground when bearing is enabled - */ - public Drawable getMyLocationForegroundBearingDrawable() { - return myLocationForegroundBearingDrawable; - } - - /** - * Get the current configured MyLocationView background drawable. - * - * @return the drawable used as background - */ - public Drawable getMyLocationBackgroundDrawable() { - return myLocationBackgroundDrawable; - } - - /** - * Get the current configured MyLocationView foreground tint color. - * - * @return the tint color - */ - @ColorInt - public int getMyLocationForegroundTintColor() { - return myLocationForegroundTintColor; - } - - /** - * Get the current configured MyLocationView background tint color. - * - * @return the tint color - */ - @ColorInt - public int getMyLocationBackgroundTintColor() { - return myLocationBackgroundTintColor; - } - - /** - * Get the current configured MyLocationView background padding. - * - * @return an array describing the padding in a LTRB manner - */ - public int[] getMyLocationBackgroundPadding() { - return myLocationBackgroundPadding; - } - - /** - * Get the current configured MyLocationView accuracy circle color tint value. - * - * @return the tint color - */ - public int getMyLocationAccuracyTintColor() { - return myLocationAccuracyTintColor; - } - - /** - * Get the current configured MyLocationView accuracy circle alpha value. - * - * @return the alpha value - */ - public int getMyLocationAccuracyAlpha() { - return myLocationAccuracyAlpha; - } - - /** - * Returns current accuracy threshold value (in meters). - * - * @return Value of accuracy threshold (in meters), below which circle won't be displayed - */ - public float getMyLocationAccuracyThreshold() { - return myLocationAccuracyThreshold; - } - - /** * Get the current configured debug state for a map view. * * @return True indicates debug is enabled. @@ -1085,9 +799,13 @@ public class MapboxMapOptions implements Parcelable { return textureMode; } + public boolean getTranslucentTextureSurface() { + return translucentTextureSurface; + } + /** * Returns the font-family for locally overriding generation of glyphs in the - * ‘CJK Unified Ideographs’ and ‘Hangul Syllables’ ranges. + * 'CJK Unified Ideographs' and 'Hangul Syllables' ranges. * * @return Local ideograph font family name. */ @@ -1141,24 +859,10 @@ public class MapboxMapOptions implements Parcelable { dest.writeByte((byte) (zoomGesturesEnabled ? 1 : 0)); dest.writeByte((byte) (doubleTapGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (myLocationEnabled ? 1 : 0)); - - dest.writeParcelable(myLocationForegroundDrawable != null - ? BitmapUtils.getBitmapFromDrawable(myLocationForegroundDrawable) : null, flags); - dest.writeParcelable(myLocationForegroundBearingDrawable != null - ? BitmapUtils.getBitmapFromDrawable(myLocationForegroundBearingDrawable) : null, flags); - dest.writeParcelable(myLocationBackgroundDrawable != null - ? BitmapUtils.getBitmapFromDrawable(myLocationBackgroundDrawable) : null, flags); - dest.writeInt(myLocationForegroundTintColor); - dest.writeInt(myLocationBackgroundTintColor); - dest.writeIntArray(myLocationBackgroundPadding); - dest.writeInt(myLocationAccuracyAlpha); - dest.writeInt(myLocationAccuracyTintColor); - dest.writeFloat(myLocationAccuracyThreshold); - dest.writeString(style); dest.writeString(apiBaseUrl); dest.writeByte((byte) (textureMode ? 1 : 0)); + dest.writeByte((byte) (translucentTextureSurface ? 1 : 0)); dest.writeByte((byte) (prefetchesTiles ? 1 : 0)); dest.writeByte((byte) (zMediaOverlay ? 1 : 0)); dest.writeString(localIdeographFontFamily); @@ -1231,24 +935,6 @@ public class MapboxMapOptions implements Parcelable { if (doubleTapGesturesEnabled != options.doubleTapGesturesEnabled) { return false; } - if (myLocationEnabled != options.myLocationEnabled) { - return false; - } - if (myLocationForegroundTintColor != options.myLocationForegroundTintColor) { - return false; - } - if (myLocationBackgroundTintColor != options.myLocationBackgroundTintColor) { - return false; - } - if (myLocationAccuracyTintColor != options.myLocationAccuracyTintColor) { - return false; - } - if (myLocationAccuracyAlpha != options.myLocationAccuracyAlpha) { - return false; - } - if (myLocationAccuracyThreshold != options.myLocationAccuracyThreshold) { - return false; - } if (cameraPosition != null ? !cameraPosition.equals(options.cameraPosition) : options.cameraPosition != null) { return false; } @@ -1261,24 +947,6 @@ public class MapboxMapOptions implements Parcelable { if (!Arrays.equals(attributionMargins, options.attributionMargins)) { return false; } - if (myLocationForegroundDrawable != null - ? !myLocationForegroundDrawable.equals(options.myLocationForegroundDrawable) - : options.myLocationForegroundDrawable != null) { - return false; - } - if (myLocationForegroundBearingDrawable != null - ? !myLocationForegroundBearingDrawable.equals(options.myLocationForegroundBearingDrawable) - : options.myLocationForegroundBearingDrawable != null) { - return false; - } - if (myLocationBackgroundDrawable != null - ? !myLocationBackgroundDrawable.equals(options.myLocationBackgroundDrawable) - : options.myLocationBackgroundDrawable != null) { - return false; - } - if (!Arrays.equals(myLocationBackgroundPadding, options.myLocationBackgroundPadding)) { - return false; - } if (style != null ? !style.equals(options.style) : options.style != null) { return false; } @@ -1326,20 +994,9 @@ public class MapboxMapOptions implements Parcelable { result = 31 * result + (zoomGesturesEnabled ? 1 : 0); result = 31 * result + (zoomControlsEnabled ? 1 : 0); result = 31 * result + (doubleTapGesturesEnabled ? 1 : 0); - result = 31 * result + (myLocationEnabled ? 1 : 0); - result = 31 * result + (myLocationForegroundDrawable != null ? myLocationForegroundDrawable.hashCode() : 0); - result = 31 * result + (myLocationForegroundBearingDrawable != null - ? myLocationForegroundBearingDrawable.hashCode() : 0); - result = 31 * result + (myLocationBackgroundDrawable != null ? myLocationBackgroundDrawable.hashCode() : 0); - result = 31 * result + myLocationForegroundTintColor; - result = 31 * result + myLocationBackgroundTintColor; - result = 31 * result + Arrays.hashCode(myLocationBackgroundPadding); - result = 31 * result + myLocationAccuracyTintColor; - result = 31 * result + myLocationAccuracyAlpha; - result = 31 * result + (myLocationAccuracyThreshold != +0.0f - ? Float.floatToIntBits(myLocationAccuracyThreshold) : 0); result = 31 * result + (apiBaseUrl != null ? apiBaseUrl.hashCode() : 0); result = 31 * result + (textureMode ? 1 : 0); + result = 31 * result + (translucentTextureSurface ? 1 : 0); result = 31 * result + (style != null ? style.hashCode() : 0); result = 31 * result + (prefetchesTiles ? 1 : 0); result = 31 * result + (zMediaOverlay ? 1 : 0); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java index e8eb7e8718..0e77910c3d 100755 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java @@ -11,6 +11,8 @@ import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.DisplayMetrics; +import com.mapbox.geojson.Feature; +import com.mapbox.geojson.Geometry; import com.mapbox.mapboxsdk.LibraryLoader; import com.mapbox.mapboxsdk.annotations.Icon; import com.mapbox.mapboxsdk.annotations.Marker; @@ -22,15 +24,13 @@ import com.mapbox.mapboxsdk.geometry.LatLngBounds; import com.mapbox.mapboxsdk.geometry.ProjectedMeters; import com.mapbox.mapboxsdk.maps.renderer.MapRenderer; import com.mapbox.mapboxsdk.storage.FileSource; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.CannotAddLayerException; -import com.mapbox.mapboxsdk.style.layers.Filter; import com.mapbox.mapboxsdk.style.layers.Layer; import com.mapbox.mapboxsdk.style.light.Light; import com.mapbox.mapboxsdk.style.sources.CannotAddSourceException; import com.mapbox.mapboxsdk.style.sources.Source; import com.mapbox.mapboxsdk.utils.BitmapUtils; -import com.mapbox.services.commons.geojson.Feature; -import com.mapbox.services.commons.geojson.Geometry; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -229,18 +229,28 @@ final class NativeMapView { return nativeGetLatLng().wrap(); } - public CameraPosition getCameraForLatLngBounds(LatLngBounds latLngBounds) { + public CameraPosition getCameraForLatLngBounds(LatLngBounds latLngBounds, int[] padding) { if (isDestroyedOn("getCameraForLatLngBounds")) { return null; } - return nativeGetCameraForLatLngBounds(latLngBounds); + return nativeGetCameraForLatLngBounds( + latLngBounds, + padding[1] / pixelRatio, + padding[0] / pixelRatio, + padding[3] / pixelRatio, + padding[2] / pixelRatio); } - public CameraPosition getCameraForGeometry(Geometry geometry, double bearing) { + public CameraPosition getCameraForGeometry(Geometry geometry, double bearing, int[] padding) { if (isDestroyedOn("getCameraForGeometry")) { return null; } - return nativeGetCameraForGeometry(geometry, bearing); + return nativeGetCameraForGeometry( + geometry, bearing, + padding[1] / pixelRatio, + padding[0] / pixelRatio, + padding[3] / pixelRatio, + padding[2] / pixelRatio); } public void resetPosition() { @@ -733,7 +743,7 @@ final class NativeMapView { if (isDestroyedOn("addSource")) { return; } - nativeAddSource(source.getNativePtr()); + nativeAddSource(source, source.getNativePtr()); } @Nullable @@ -741,14 +751,19 @@ final class NativeMapView { if (isDestroyedOn("removeSource")) { return null; } - return nativeRemoveSourceById(sourceId); + Source source = getSource(sourceId); + if (source != null) { + return removeSource(source); + } + return null; } + @Nullable public Source removeSource(@NonNull Source source) { if (isDestroyedOn("removeSource")) { return null; } - nativeRemoveSource(source.getNativePtr()); + nativeRemoveSource(source, source.getNativePtr()); return source; } @@ -757,20 +772,8 @@ final class NativeMapView { return; } - // Check/correct config - if (image.getConfig() != Bitmap.Config.ARGB_8888) { - image = image.copy(Bitmap.Config.ARGB_8888, false); - } - - // Get pixels - ByteBuffer buffer = ByteBuffer.allocate(image.getByteCount()); - image.copyPixelsToBuffer(buffer); - // Determine pixel ratio - float density = image.getDensity() == Bitmap.DENSITY_NONE ? Bitmap.DENSITY_NONE : image.getDensity(); - float pixelRatio = density / DisplayMetrics.DENSITY_DEFAULT; - - nativeAddImage(name, image.getWidth(), image.getHeight(), pixelRatio, buffer.array()); + nativeAddImage(name, image, image.getDensity() / DisplayMetrics.DENSITY_DEFAULT); } public void addImages(@NonNull HashMap<String, Bitmap> bitmapHashMap) { @@ -800,7 +803,7 @@ final class NativeMapView { @NonNull public List<Feature> queryRenderedFeatures(@NonNull PointF coordinates, @Nullable String[] layerIds, - @Nullable Filter.Statement filter) { + @Nullable Expression filter) { if (isDestroyedOn("queryRenderedFeatures")) { return new ArrayList<>(); } @@ -812,7 +815,7 @@ final class NativeMapView { @NonNull public List<Feature> queryRenderedFeatures(@NonNull RectF coordinates, @Nullable String[] layerIds, - @Nullable Filter.Statement filter) { + @Nullable Expression filter) { if (isDestroyedOn("queryRenderedFeatures")) { return new ArrayList<>(); } @@ -907,9 +910,11 @@ final class NativeMapView { private native LatLng nativeGetLatLng(); - private native CameraPosition nativeGetCameraForLatLngBounds(LatLngBounds latLngBounds); + private native CameraPosition nativeGetCameraForLatLngBounds( + LatLngBounds latLngBounds, double top, double left, double bottom, double right); - private native CameraPosition nativeGetCameraForGeometry(Geometry geometry, double bearing); + private native CameraPosition nativeGetCameraForGeometry( + Geometry geometry, double bearing, double top, double left, double bottom, double right); private native void nativeResetPosition(); @@ -1027,14 +1032,11 @@ final class NativeMapView { private native Source nativeGetSource(String sourceId); - private native void nativeAddSource(long nativeSourcePtr) throws CannotAddSourceException; - - private native Source nativeRemoveSourceById(String sourceId); + private native void nativeAddSource(Source source, long sourcePtr) throws CannotAddSourceException; - private native void nativeRemoveSource(long sourcePtr); + private native void nativeRemoveSource(Source source, long sourcePtr); - private native void nativeAddImage(String name, int width, int height, float pixelRatio, - byte[] array); + private native void nativeAddImage(String name, Bitmap bitmap, float pixelRatio); private native void nativeAddImages(Image[] images); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Projection.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Projection.java index ae559189ad..f35355533d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Projection.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Projection.java @@ -9,6 +9,9 @@ import com.mapbox.mapboxsdk.geometry.LatLngBounds; import com.mapbox.mapboxsdk.geometry.ProjectedMeters; import com.mapbox.mapboxsdk.geometry.VisibleRegion; +import java.util.ArrayList; +import java.util.List; + /** * A projection is used to translate between on screen location and geographic coordinates on * the surface of the Earth. Screen location is in screen pixels (not display pixels) @@ -24,25 +27,17 @@ public class Projection { this.contentPadding = new int[] {0, 0, 0, 0}; } - void setContentPadding(int[] contentPadding, int[] userLocationViewPadding) { + void setContentPadding(int[] contentPadding) { this.contentPadding = contentPadding; - - int[] padding = new int[] { - contentPadding[0] + userLocationViewPadding[0], - contentPadding[1] + userLocationViewPadding[1], - contentPadding[2] + userLocationViewPadding[2], - contentPadding[3] + userLocationViewPadding[3] - }; - - nativeMapView.setContentPadding(padding); + nativeMapView.setContentPadding(contentPadding); } int[] getContentPadding() { return contentPadding; } - public void invalidateContentPadding(int[] userLocationViewPadding) { - setContentPadding(contentPadding, userLocationViewPadding); + public void invalidateContentPadding() { + setContentPadding(contentPadding); } /** @@ -103,14 +98,49 @@ public class Projection { LatLng bottomRight = fromScreenLocation(new PointF(right, bottom)); LatLng bottomLeft = fromScreenLocation(new PointF(left, bottom)); - return new VisibleRegion(topLeft, topRight, bottomLeft, bottomRight, - new LatLngBounds.Builder() - .include(topRight) - .include(bottomLeft) - .include(bottomRight) - .include(topLeft) - .build() - ); + // Map can be rotated, find correct LatLngBounds that encompasses the visible region (that might be rotated) + List<LatLng> boundsPoints = new ArrayList<>(); + boundsPoints.add(topLeft); + boundsPoints.add(topRight); + boundsPoints.add(bottomRight); + boundsPoints.add(bottomLeft); + + // order so that two most northern point are put first + while ((boundsPoints.get(0).getLatitude() < boundsPoints.get(3).getLatitude()) + || (boundsPoints.get(1).getLatitude() < boundsPoints.get(2).getLatitude())) { + LatLng first = boundsPoints.remove(0); + boundsPoints.add(first); + } + + double north = boundsPoints.get(0).getLatitude(); + if (north < boundsPoints.get(1).getLatitude()) { + north = boundsPoints.get(1).getLatitude(); + } + + double south = boundsPoints.get(2).getLatitude(); + if (south > boundsPoints.get(3).getLatitude()) { + south = boundsPoints.get(3).getLatitude(); + } + + double firstLon = boundsPoints.get(0).getLongitude(); + double secondLon = boundsPoints.get(1).getLongitude(); + double thridLon = boundsPoints.get(2).getLongitude(); + double fourthLon = boundsPoints.get(3).getLongitude(); + + // if it does not go over the date line + if (secondLon > fourthLon && firstLon < thridLon) { + return new VisibleRegion(topLeft, topRight, bottomLeft, bottomRight, + LatLngBounds.from(north, + secondLon > thridLon ? secondLon : thridLon, + south, + firstLon < fourthLon ? firstLon : fourthLon)); + } else { + return new VisibleRegion(topLeft, topRight, bottomLeft, bottomRight, + LatLngBounds.from(north, + secondLon < thridLon ? secondLon : thridLon, + south, + firstLon > fourthLon ? firstLon : fourthLon)); + } } /** diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Telemetry.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Telemetry.java new file mode 100644 index 0000000000..e6b93e4b91 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Telemetry.java @@ -0,0 +1,48 @@ +package com.mapbox.mapboxsdk.maps; + + +import com.mapbox.android.telemetry.MapboxTelemetry; +import com.mapbox.android.telemetry.SessionInterval; +import com.mapbox.android.telemetry.TelemetryEnabler; +import com.mapbox.mapboxsdk.BuildConfig; +import com.mapbox.mapboxsdk.Mapbox; + +public class Telemetry { + static final String TWO_FINGER_TAP = "TwoFingerTap"; + static final String DOUBLE_TAP = "DoubleTap"; + static final String SINGLE_TAP = "SingleTap"; + static final String PAN = "Pan"; + static final String PINCH = "Pinch"; + static final String ROTATION = "Rotation"; + static final String PITCH = "Pitch"; + private MapboxTelemetry telemetry; + + private Telemetry() { + telemetry = new MapboxTelemetry(Mapbox.getApplicationContext(), Mapbox.getAccessToken(), + BuildConfig.MAPBOX_EVENTS_USER_AGENT); + TelemetryEnabler.State telemetryState = TelemetryEnabler.retrieveTelemetryStateFromPreferences(); + if (TelemetryEnabler.State.ENABLED.equals(telemetryState)) { + telemetry.enable(); + } + } + + public static void initialize() { + obtainTelemetry(); + } + + public static void updateDebugLoggingEnabled(boolean debugLoggingEnabled) { + TelemetryHolder.INSTANCE.telemetry.updateDebugLoggingEnabled(debugLoggingEnabled); + } + + public static boolean updateSessionIdRotationInterval(SessionInterval interval) { + return TelemetryHolder.INSTANCE.telemetry.updateSessionIdRotationInterval(interval); + } + + private static class TelemetryHolder { + private static final Telemetry INSTANCE = new Telemetry(); + } + + static MapboxTelemetry obtainTelemetry() { + return TelemetryHolder.INSTANCE.telemetry; + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/TrackingSettings.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/TrackingSettings.java deleted file mode 100644 index 81fd091c90..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/TrackingSettings.java +++ /dev/null @@ -1,419 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.location.Location; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.UiThread; - -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.constants.MyBearingTracking; -import com.mapbox.mapboxsdk.constants.MyLocationTracking; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationView; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.android.telemetry.location.LocationEngineListener; -import com.mapbox.services.android.telemetry.permissions.PermissionsManager; - -import timber.log.Timber; - -/** - * Settings for the user location and bearing tracking of a MapboxMap. - * - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ -@Deprecated -public final class TrackingSettings { - - private final MyLocationView myLocationView; - private final UiSettings uiSettings; - private final FocalPointChangeListener focalPointChangedListener; - private final CameraZoomInvalidator zoomInvalidator; - private LocationEngine locationSource; - private LocationEngineListener myLocationListener; - private boolean locationChangeAnimationEnabled = true; - private boolean isCustomLocationSource; - - private boolean myLocationEnabled; - private boolean dismissLocationTrackingOnGesture = true; - private boolean dismissBearingTrackingOnGesture = true; - - private MapboxMap.OnMyLocationTrackingModeChangeListener onMyLocationTrackingModeChangeListener; - private MapboxMap.OnMyBearingTrackingModeChangeListener onMyBearingTrackingModeChangeListener; - - TrackingSettings(@NonNull MyLocationView myLocationView, UiSettings uiSettings, - FocalPointChangeListener focalPointChangedListener, CameraZoomInvalidator zoomInvalidator) { - this.myLocationView = myLocationView; - this.focalPointChangedListener = focalPointChangedListener; - this.uiSettings = uiSettings; - this.zoomInvalidator = zoomInvalidator; - } - - void initialise(MapboxMapOptions options) { - locationSource = Mapbox.getLocationEngine(); - setMyLocationEnabled(options.getLocationEnabled()); - } - - void onSaveInstanceState(Bundle outState) { - outState.putInt(MapboxConstants.STATE_MY_LOCATION_TRACKING_MODE, getMyLocationTrackingMode()); - outState.putInt(MapboxConstants.STATE_MY_BEARING_TRACKING_MODE, getMyBearingTrackingMode()); - outState.putBoolean(MapboxConstants.STATE_MY_LOCATION_TRACKING_DISMISS, isDismissLocationTrackingOnGesture()); - outState.putBoolean(MapboxConstants.STATE_MY_BEARING_TRACKING_DISMISS, isDismissBearingTrackingOnGesture()); - outState.putBoolean(MapboxConstants.STATE_MY_LOCATION_ENABLED, isMyLocationEnabled()); - outState.putBoolean(MapboxConstants.STATE_LOCATION_CHANGE_ANIMATION_ENABLED, isLocationChangeAnimationEnabled()); - outState.putBoolean(MapboxConstants.STATE_USING_CUSTOM_LOCATION_SOURCE, isCustomLocationSource()); - } - - void onRestoreInstanceState(Bundle savedInstanceState) { - try { - setMyLocationEnabled( - savedInstanceState.getBoolean(MapboxConstants.STATE_MY_LOCATION_ENABLED), - savedInstanceState.getBoolean(MapboxConstants.STATE_USING_CUSTOM_LOCATION_SOURCE) - ); - } catch (SecurityException ignore) { - // User did not accept location permissions - } - // noinspection ResourceType - setMyLocationTrackingMode(savedInstanceState.getInt( - MapboxConstants.STATE_MY_LOCATION_TRACKING_MODE, MyLocationTracking.TRACKING_NONE)); - // noinspection ResourceType - setMyBearingTrackingMode(savedInstanceState.getInt( - MapboxConstants.STATE_MY_BEARING_TRACKING_MODE, MyBearingTracking.NONE)); - setDismissLocationTrackingOnGesture(savedInstanceState.getBoolean( - MapboxConstants.STATE_MY_LOCATION_TRACKING_DISMISS, true)); - setDismissBearingTrackingOnGesture(savedInstanceState.getBoolean( - MapboxConstants.STATE_MY_BEARING_TRACKING_DISMISS, true)); - setLocationChangeAnimationEnabled(savedInstanceState.getBoolean( - MapboxConstants.STATE_LOCATION_CHANGE_ANIMATION_ENABLED, true)); - } - - /** - * <p> - * Set the current my location tracking mode. - * </p> - * <p> - * Will enable my location if not active. - * </p> - * See {@link MyLocationTracking} for different values. - * - * @param myLocationTrackingMode The location tracking mode to be used. - * @throws SecurityException if no suitable permission is present - * @see MyLocationTracking - */ - @UiThread - public void setMyLocationTrackingMode(@MyLocationTracking.Mode int myLocationTrackingMode) { - myLocationView.setLocationChangeAnimationEnabled(isLocationChangeAnimationEnabled()); - myLocationView.setMyLocationTrackingMode(myLocationTrackingMode); - - if (myLocationTrackingMode == MyLocationTracking.TRACKING_FOLLOW) { - zoomInvalidator.zoomTo(2.0); - focalPointChangedListener.onFocalPointChanged(myLocationView.getCenter()); - } else { - focalPointChangedListener.onFocalPointChanged(null); - } - - if (onMyLocationTrackingModeChangeListener != null) { - onMyLocationTrackingModeChangeListener.onMyLocationTrackingModeChange(myLocationTrackingMode); - } - } - - /** - * Returns the current user location tracking mode. - * - * @return The current user location tracking mode. - * One of the values from {@link MyLocationTracking.Mode}. - * @see MyLocationTracking.Mode - */ - @UiThread - @MyLocationTracking.Mode - public int getMyLocationTrackingMode() { - return myLocationView.getMyLocationTrackingMode(); - } - - /** - * <p> - * Set the current my bearing tracking mode. - * </p> - * Shows the direction the user is heading. - * <p> - * When location tracking is disabled the direction of {@link MyLocationView} is rotated. When - * location tracking is enabled the {@link MapView} is rotated based on the bearing value. - * </p> - * See {@link MyBearingTracking} for different values. - * - * @param myBearingTrackingMode The bearing tracking mode to be used. - * @throws SecurityException if no suitable permission is present - * @see MyBearingTracking - */ - @UiThread - public void setMyBearingTrackingMode(@MyBearingTracking.Mode int myBearingTrackingMode) { - myLocationView.setMyBearingTrackingMode(myBearingTrackingMode); - if (onMyBearingTrackingModeChangeListener != null) { - onMyBearingTrackingModeChangeListener.onMyBearingTrackingModeChange(myBearingTrackingMode); - } - } - - /** - * Returns the current user bearing tracking mode. - * See {@link MyBearingTracking} for possible return values. - * - * @return the current user bearing tracking mode. - * @see MyBearingTracking - */ - @UiThread - @MyBearingTracking.Mode - public int getMyBearingTrackingMode() { - return myLocationView.getMyBearingTrackingMode(); - } - - /** - * Returns if all tracking modes will be dismissed when a gesture occurs. - * - * @return True to indicate that location and bearing tracking will be dismissed. - */ - public boolean isAllDismissTrackingOnGesture() { - return dismissLocationTrackingOnGesture && dismissBearingTrackingOnGesture; - } - - /** - * Set the dismissal of the tracking modes if a gesture occurs. - * - * @param dismissTrackingOnGesture True to dismiss all the tracking modes. - */ - public void setDismissAllTrackingOnGesture(boolean dismissTrackingOnGesture) { - dismissLocationTrackingOnGesture = dismissTrackingOnGesture; - dismissBearingTrackingOnGesture = dismissTrackingOnGesture; - } - - /** - * Set the dismissal of the tracking modes if a gesture occurs. - * - * @param dismissLocationTrackingOnGesture True to dismiss the location tracking mode. - */ - public void setDismissLocationTrackingOnGesture(boolean dismissLocationTrackingOnGesture) { - this.dismissLocationTrackingOnGesture = dismissLocationTrackingOnGesture; - } - - /** - * Returns if the location tracking will be disabled when a gesture occurs - * - * @return True if location tracking will be disabled. - */ - public boolean isDismissLocationTrackingOnGesture() { - return dismissLocationTrackingOnGesture; - } - - /** - * Set the dismissal of the bearing tracking modes if a gesture occurs. - * - * @param dismissBearingTrackingOnGesture True to dimsiss the bearinf tracking mode - */ - public void setDismissBearingTrackingOnGesture(boolean dismissBearingTrackingOnGesture) { - this.dismissBearingTrackingOnGesture = dismissBearingTrackingOnGesture; - } - - /** - * Returns if bearing will disabled when a gesture occurs - * - * @return True if bearing tracking will be disabled - */ - public boolean isDismissBearingTrackingOnGesture() { - return dismissBearingTrackingOnGesture; - } - - /** - * Returns if location tracking is disabled - * - * @return True if location tracking is disabled. - */ - public boolean isLocationTrackingDisabled() { - return myLocationView.getMyLocationTrackingMode() == MyLocationTracking.TRACKING_NONE; - } - - /** - * Returns if bearing tracking disabled - * - * @return True if bearing tracking is disabled. - */ - public boolean isBearingTrackingDisabled() { - return myLocationView.getMyBearingTrackingMode() == MyBearingTracking.NONE; - } - - /** - * Returns if rotate gesture are currently enabled. - * - * @return True if rotate gestures are currently enabled. - */ - public boolean isRotateGestureCurrentlyEnabled() { - // rotate gestures are recognised if: - // The user settings are enabled AND; - // EITHER bearing tracking is dismissed on gesture OR there is no bearing tracking - return uiSettings.isRotateGesturesEnabled() - && (dismissBearingTrackingOnGesture - || myLocationView.getMyBearingTrackingMode() == MyBearingTracking.NONE - || myLocationView.getMyLocationTrackingMode() == MyLocationTracking.TRACKING_NONE); - } - - /** - * Returns if scroll gesture are currently enabled. - * - * @return True if scroll gestures are currently enabled. - */ - public boolean isScrollGestureCurrentlyEnabled() { - return uiSettings.isScrollGesturesEnabled() - && (dismissLocationTrackingOnGesture - || myLocationView.getMyLocationTrackingMode() == MyLocationTracking.TRACKING_NONE); - } - - /** - * Returns whether location change animation is applied for {@link MyLocationTracking#TRACKING_FOLLOW}. - * - * @return True if animation is applied, false otherwise. - */ - public boolean isLocationChangeAnimationEnabled() { - return locationChangeAnimationEnabled; - } - - /** - * Set whether location change animation should be applied for {@link MyLocationTracking#TRACKING_FOLLOW}. - * - * @param locationChangeAnimationEnabled True if animation should be applied, false otherwise. - */ - public void setLocationChangeAnimationEnabled(boolean locationChangeAnimationEnabled) { - this.locationChangeAnimationEnabled = locationChangeAnimationEnabled; - - myLocationView.setLocationChangeAnimationEnabled(locationChangeAnimationEnabled); - } - - /** - * Reset the tracking modes as necessary. Location tracking is reset if the map center is changed and not from - * location, bearing tracking if there is a rotation. - * - * @param translate true if translation - * @param rotate true if rotation - * @param isFromLocation true if from location - */ - void resetTrackingModesIfRequired(boolean translate, boolean rotate, boolean isFromLocation) { - // if tracking is on, and we should dismiss tracking with gestures, and this is a scroll action, turn tracking off - if (translate && !isLocationTrackingDisabled() && isDismissLocationTrackingOnGesture() && !isFromLocation) { - setMyLocationTrackingMode(MyLocationTracking.TRACKING_NONE); - } - - // reset bearing tracking only on rotate - if (rotate && !isBearingTrackingDisabled() && isDismissBearingTrackingOnGesture()) { - setMyBearingTrackingMode(MyBearingTracking.NONE); - } - } - - /** - * Reset the tracking modes as necessary. Animated camera position changes can reset the underlying tracking modes. - * - * @param currentCameraPosition the current camera position - * @param targetCameraPosition the changed camera position - * @param isFromLocation true if from location - */ - void resetTrackingModesIfRequired(CameraPosition currentCameraPosition, CameraPosition targetCameraPosition, - boolean isFromLocation) { - if (currentCameraPosition.target != null) { - resetTrackingModesIfRequired(!currentCameraPosition.target.equals(targetCameraPosition.target), false, - isFromLocation); - } - } - - Location getMyLocation() { - return myLocationView.getLocation(); - } - - void setOnMyLocationChangeListener(@Nullable final MapboxMap.OnMyLocationChangeListener listener) { - if (listener != null) { - myLocationListener = new LocationEngineListener() { - @Override - public void onConnected() { - // Nothing - } - - @Override - public void onLocationChanged(Location location) { - if (listener != null) { - listener.onMyLocationChange(location); - } - } - }; - locationSource.addLocationEngineListener(myLocationListener); - } else { - locationSource.removeLocationEngineListener(myLocationListener); - myLocationListener = null; - } - } - - public boolean isCustomLocationSource() { - return isCustomLocationSource; - } - - void setOnMyLocationTrackingModeChangeListener(MapboxMap.OnMyLocationTrackingModeChangeListener listener) { - this.onMyLocationTrackingModeChangeListener = listener; - } - - void setOnMyBearingTrackingModeChangeListener(MapboxMap.OnMyBearingTrackingModeChangeListener listener) { - this.onMyBearingTrackingModeChangeListener = listener; - } - - MyLocationView getMyLocationView() { - return myLocationView; - } - - - boolean isMyLocationEnabled() { - return myLocationEnabled; - } - - void setMyLocationEnabled(boolean locationEnabled) { - setMyLocationEnabled(locationEnabled, isCustomLocationSource()); - } - - private void setMyLocationEnabled(boolean locationEnabled, boolean isCustomLocationSource) { - if (locationEnabled && !PermissionsManager.areLocationPermissionsGranted(myLocationView.getContext())) { - Timber.e("Could not activate user location tracking: " - + "user did not accept the permission or permissions were not requested."); - return; - } - myLocationEnabled = locationEnabled; - this.isCustomLocationSource = isCustomLocationSource; - myLocationView.setEnabled(locationEnabled, isCustomLocationSource); - } - - void setLocationSource(LocationEngine locationSource) { - if (this.locationSource != null && this.locationSource.equals(locationSource)) { - // this source is already active - return; - } - - this.isCustomLocationSource = locationSource != null; - if (locationSource == null) { - locationSource = Mapbox.getLocationEngine(); - } - this.locationSource = locationSource; - myLocationView.setLocationSource(locationSource); - } - - void update() { - if (!myLocationView.isEnabled()) { - return; - } - myLocationView.update(); - } - - void onStart() { - myLocationView.onStart(); - } - - void onStop() { - myLocationView.onStop(); - } - - interface CameraZoomInvalidator { - void zoomTo(double zoomLevel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Transform.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Transform.java index 84a601039f..f76e54984b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Transform.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Transform.java @@ -12,7 +12,6 @@ import com.mapbox.mapboxsdk.camera.CameraUpdate; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.widgets.MyLocationView; import timber.log.Timber; @@ -30,8 +29,6 @@ final class Transform implements MapView.OnMapChangedListener { private final NativeMapView mapView; private final MarkerViewManager markerViewManager; - private final TrackingSettings trackingSettings; - private final MyLocationView myLocationView; private final Handler handler = new Handler(); private CameraPosition cameraPosition; @@ -41,12 +38,10 @@ final class Transform implements MapView.OnMapChangedListener { private CameraChangeDispatcher cameraChangeDispatcher; - Transform(NativeMapView mapView, MarkerViewManager markerViewManager, TrackingSettings trackingSettings, + Transform(NativeMapView mapView, MarkerViewManager markerViewManager, CameraChangeDispatcher cameraChangeDispatcher) { this.mapView = mapView; this.markerViewManager = markerViewManager; - this.trackingSettings = trackingSettings; - this.myLocationView = trackingSettings.getMyLocationView(); this.cameraChangeDispatcher = cameraChangeDispatcher; } @@ -73,9 +68,6 @@ final class Transform implements MapView.OnMapChangedListener { @UiThread void updateCameraPosition(@NonNull CameraPosition position) { - if (myLocationView != null) { - myLocationView.setCameraPosition(position); - } markerViewManager.setTilt((float) position.tilt); } @@ -103,7 +95,6 @@ final class Transform implements MapView.OnMapChangedListener { final void moveCamera(MapboxMap mapboxMap, CameraUpdate update, final MapboxMap.CancelableCallback callback) { CameraPosition cameraPosition = update.getCameraPosition(mapboxMap); if (isValidCameraPosition(cameraPosition)) { - trackingSettings.resetTrackingModesIfRequired(this.cameraPosition, cameraPosition, false); cancelTransitions(); cameraChangeDispatcher.onCameraMoveStarted(OnCameraMoveStartedListener.REASON_API_ANIMATION); mapView.jumpTo(cameraPosition.bearing, cameraPosition.target, cameraPosition.tilt, cameraPosition.zoom); @@ -125,7 +116,6 @@ final class Transform implements MapView.OnMapChangedListener { final MapboxMap.CancelableCallback callback, boolean isDismissable) { CameraPosition cameraPosition = update.getCameraPosition(mapboxMap); if (isValidCameraPosition(cameraPosition)) { - trackingSettings.resetTrackingModesIfRequired(this.cameraPosition, cameraPosition, isDismissable); cancelTransitions(); cameraChangeDispatcher.onCameraMoveStarted(OnCameraMoveStartedListener.REASON_API_ANIMATION); @@ -143,7 +133,6 @@ final class Transform implements MapView.OnMapChangedListener { final MapboxMap.CancelableCallback callback) { CameraPosition cameraPosition = update.getCameraPosition(mapboxMap); if (isValidCameraPosition(cameraPosition)) { - trackingSettings.resetTrackingModesIfRequired(this.cameraPosition, cameraPosition, false); cancelTransitions(); cameraChangeDispatcher.onCameraMoveStarted(OnCameraMoveStartedListener.REASON_API_ANIMATION); @@ -205,6 +194,8 @@ final class Transform implements MapView.OnMapChangedListener { // cancel ongoing transitions mapView.cancelTransitions(); + + cameraChangeDispatcher.onCameraIdle(); } @UiThread @@ -235,39 +226,21 @@ final class Transform implements MapView.OnMapChangedListener { return mapView.getZoom(); } - void zoom(boolean zoomIn, @NonNull PointF focalPoint) { - CameraPosition cameraPosition = invalidateCameraPosition(); - if (cameraPosition != null) { - int newZoom = (int) Math.round(cameraPosition.zoom + (zoomIn ? 1 : -1)); - setZoom(newZoom, focalPoint, MapboxConstants.ANIMATION_DURATION, false); - } else { - // we are not transforming, notify about being idle - cameraChangeDispatcher.onCameraIdle(); - } - } - - void zoom(double zoomAddition, @NonNull PointF focalPoint, long duration) { - CameraPosition cameraPosition = invalidateCameraPosition(); - if (cameraPosition != null) { - int newZoom = (int) Math.round(cameraPosition.zoom + zoomAddition); - setZoom(newZoom, focalPoint, duration, false); - } else { - // we are not transforming, notify about being idle - cameraChangeDispatcher.onCameraIdle(); - } + void zoomBy(double zoomAddition, @NonNull PointF focalPoint) { + setZoom(mapView.getZoom() + zoomAddition, focalPoint); } void setZoom(double zoom, @NonNull PointF focalPoint) { - setZoom(zoom, focalPoint, 0, false); + setZoom(zoom, focalPoint, 0); } - void setZoom(double zoom, @NonNull PointF focalPoint, long duration, final boolean isAnimator) { + void setZoom(double zoom, @NonNull PointF focalPoint, final long duration) { if (mapView != null) { mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() { @Override public void onMapChanged(int change) { if (change == MapView.REGION_DID_CHANGE_ANIMATED) { - if (!isAnimator) { + if (duration > 0) { cameraChangeDispatcher.onCameraIdle(); } mapView.removeOnMapChangedListener(this); @@ -297,23 +270,14 @@ final class Transform implements MapView.OnMapChangedListener { } void setBearing(double bearing) { - if (myLocationView != null) { - myLocationView.setBearing(bearing); - } mapView.setBearing(bearing); } void setBearing(double bearing, float focalX, float focalY) { - if (myLocationView != null) { - myLocationView.setBearing(bearing); - } mapView.setBearing(bearing, focalX, focalY); } void setBearing(double bearing, float focalX, float focalY, long duration) { - if (myLocationView != null) { - myLocationView.setBearing(bearing); - } mapView.setBearing(bearing, focalX, focalY, duration); } @@ -335,9 +299,6 @@ final class Transform implements MapView.OnMapChangedListener { } void setTilt(Double pitch) { - if (myLocationView != null) { - myLocationView.setTilt(pitch); - } markerViewManager.setTilt(pitch.floatValue()); mapView.setPitch(pitch, 0); } @@ -361,10 +322,6 @@ final class Transform implements MapView.OnMapChangedListener { } } - void zoomBy(double z, float x, float y) { - mapView.setZoom(mapView.getZoom() + z, new PointF(x, y), 0); - } - void moveBy(double offsetX, double offsetY, long duration) { if (duration > 0) { mapView.addOnMapChangedListener(new MapView.OnMapChangedListener() { diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/UiSettings.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/UiSettings.java index 44f106bdd5..c1daebbe52 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/UiSettings.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/UiSettings.java @@ -37,6 +37,7 @@ public final class UiSettings { private final ImageView attributionsView; private final int[] attributionsMargins = new int[4]; + private AttributionDialogManager attributionDialogManager; private final View logoView; private final int[] logoMargins = new int[4]; @@ -44,21 +45,23 @@ public final class UiSettings { private float pixelRatio; private boolean rotateGesturesEnabled = true; - private boolean rotateGestureChangeAllowed = true; private boolean tiltGesturesEnabled = true; - private boolean tiltGestureChangeAllowed = true; private boolean zoomGesturesEnabled = true; - private boolean zoomGestureChangeAllowed = true; private boolean scrollGesturesEnabled = true; - private boolean scrollGestureChangeAllowed = true; private boolean zoomControlsEnabled; private boolean doubleTapGesturesEnabled = true; - private boolean doubleTapGestureChangeAllowed = true; + + private boolean scaleVelocityAnimationEnabled = true; + private boolean rotateVelocityAnimationEnabled = true; + private boolean flingVelocityAnimationEnabled = true; + + private boolean increaseRotateThresholdWhenScaling = true; + private boolean increaseScaleThresholdWhenRotating = true; private boolean deselectMarkersOnTap = true; @@ -107,42 +110,39 @@ public final class UiSettings { private void initialiseGestures(MapboxMapOptions options) { setZoomGesturesEnabled(options.getZoomGesturesEnabled()); - setZoomGestureChangeAllowed(options.getZoomGesturesEnabled()); setScrollGesturesEnabled(options.getScrollGesturesEnabled()); - setScrollGestureChangeAllowed(options.getScrollGesturesEnabled()); setRotateGesturesEnabled(options.getRotateGesturesEnabled()); - setRotateGestureChangeAllowed(options.getRotateGesturesEnabled()); setTiltGesturesEnabled(options.getTiltGesturesEnabled()); - setTiltGestureChangeAllowed(options.getTiltGesturesEnabled()); setZoomControlsEnabled(options.getZoomControlsEnabled()); setDoubleTapGesturesEnabled(options.getDoubleTapGesturesEnabled()); - setDoubleTapGestureChangeAllowed(options.getDoubleTapGesturesEnabled()); } private void saveGestures(Bundle outState) { outState.putBoolean(MapboxConstants.STATE_ZOOM_ENABLED, isZoomGesturesEnabled()); - outState.putBoolean(MapboxConstants.STATE_ZOOM_ENABLED_CHANGE, isZoomGestureChangeAllowed()); outState.putBoolean(MapboxConstants.STATE_SCROLL_ENABLED, isScrollGesturesEnabled()); - outState.putBoolean(MapboxConstants.STATE_SCROLL_ENABLED_CHANGE, isScrollGestureChangeAllowed()); outState.putBoolean(MapboxConstants.STATE_ROTATE_ENABLED, isRotateGesturesEnabled()); - outState.putBoolean(MapboxConstants.STATE_ROTATE_ENABLED_CHANGE, isRotateGestureChangeAllowed()); outState.putBoolean(MapboxConstants.STATE_TILT_ENABLED, isTiltGesturesEnabled()); - outState.putBoolean(MapboxConstants.STATE_TILT_ENABLED_CHANGE, isTiltGestureChangeAllowed()); outState.putBoolean(MapboxConstants.STATE_DOUBLE_TAP_ENABLED, isDoubleTapGesturesEnabled()); - outState.putBoolean(MapboxConstants.STATE_DOUBLE_TAP_ENABLED_CHANGE, isDoubleTapGestureChangeAllowed()); + outState.putBoolean(MapboxConstants.STATE_SCALE_ANIMATION_ENABLED, isScaleVelocityAnimationEnabled()); + outState.putBoolean(MapboxConstants.STATE_ROTATE_ANIMATION_ENABLED, isRotateVelocityAnimationEnabled()); + outState.putBoolean(MapboxConstants.STATE_FLING_ANIMATION_ENABLED, isFlingVelocityAnimationEnabled()); + outState.putBoolean(MapboxConstants.STATE_INCREASE_ROTATE_THRESHOLD, isIncreaseRotateThresholdWhenScaling()); + outState.putBoolean(MapboxConstants.STATE_INCREASE_SCALE_THRESHOLD, isIncreaseScaleThresholdWhenRotating()); } private void restoreGestures(Bundle savedInstanceState) { setZoomGesturesEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_ZOOM_ENABLED)); - setZoomGestureChangeAllowed(savedInstanceState.getBoolean(MapboxConstants.STATE_ZOOM_ENABLED_CHANGE)); setScrollGesturesEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_SCROLL_ENABLED)); - setScrollGestureChangeAllowed(savedInstanceState.getBoolean(MapboxConstants.STATE_SCROLL_ENABLED_CHANGE)); setRotateGesturesEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_ROTATE_ENABLED)); - setRotateGestureChangeAllowed(savedInstanceState.getBoolean(MapboxConstants.STATE_ROTATE_ENABLED_CHANGE)); setTiltGesturesEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_TILT_ENABLED)); - setTiltGestureChangeAllowed(savedInstanceState.getBoolean(MapboxConstants.STATE_TILT_ENABLED_CHANGE)); setDoubleTapGesturesEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_DOUBLE_TAP_ENABLED)); - setDoubleTapGestureChangeAllowed(savedInstanceState.getBoolean(MapboxConstants.STATE_DOUBLE_TAP_ENABLED_CHANGE)); + setScaleVelocityAnimationEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_SCALE_ANIMATION_ENABLED)); + setRotateVelocityAnimationEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_ROTATE_ANIMATION_ENABLED)); + setFlingVelocityAnimationEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_FLING_ANIMATION_ENABLED)); + setIncreaseRotateThresholdWhenScaling( + savedInstanceState.getBoolean(MapboxConstants.STATE_INCREASE_ROTATE_THRESHOLD)); + setIncreaseScaleThresholdWhenRotating( + savedInstanceState.getBoolean(MapboxConstants.STATE_INCREASE_SCALE_THRESHOLD)); } private void initialiseCompass(MapboxMapOptions options, Resources resources) { @@ -535,6 +535,28 @@ public final class UiSettings { return attributionsView.getVisibility() == View.VISIBLE; } + + /** + * Set a custom attribution dialog manager. + * <p> + * Set to null to reset to default behaviour. + * </p> + * + * @param attributionDialogManager the manager class used for showing attribution + */ + public void setAttributionDialogManager(AttributionDialogManager attributionDialogManager) { + this.attributionDialogManager = attributionDialogManager; + } + + /** + * Get the custom attribution dialog manager. + * + * @return the active manager class used for showing attribution + */ + public AttributionDialogManager getAttributionDialogManager() { + return attributionDialogManager; + } + /** * <p> * Sets the gravity of the attribution. @@ -635,9 +657,7 @@ public final class UiSettings { * @param rotateGesturesEnabled If true, rotating is enabled. */ public void setRotateGesturesEnabled(boolean rotateGesturesEnabled) { - if (rotateGestureChangeAllowed) { - this.rotateGesturesEnabled = rotateGesturesEnabled; - } + this.rotateGesturesEnabled = rotateGesturesEnabled; } /** @@ -649,14 +669,6 @@ public final class UiSettings { return rotateGesturesEnabled; } - void setRotateGestureChangeAllowed(boolean rotateGestureChangeAllowed) { - this.rotateGestureChangeAllowed = rotateGestureChangeAllowed; - } - - boolean isRotateGestureChangeAllowed() { - return rotateGestureChangeAllowed; - } - /** * <p> * Changes whether the user may tilt the map. @@ -670,9 +682,8 @@ public final class UiSettings { * @param tiltGesturesEnabled If true, tilting is enabled. */ public void setTiltGesturesEnabled(boolean tiltGesturesEnabled) { - if (tiltGestureChangeAllowed) { - this.tiltGesturesEnabled = tiltGesturesEnabled; - } + this.tiltGesturesEnabled = tiltGesturesEnabled; + } /** @@ -684,14 +695,6 @@ public final class UiSettings { return tiltGesturesEnabled; } - void setTiltGestureChangeAllowed(boolean tiltGestureChangeAllowed) { - this.tiltGestureChangeAllowed = tiltGestureChangeAllowed; - } - - boolean isTiltGestureChangeAllowed() { - return tiltGestureChangeAllowed; - } - /** * <p> * Changes whether the user may zoom the map. @@ -705,9 +708,7 @@ public final class UiSettings { * @param zoomGesturesEnabled If true, zooming is enabled. */ public void setZoomGesturesEnabled(boolean zoomGesturesEnabled) { - if (zoomGestureChangeAllowed) { - this.zoomGesturesEnabled = zoomGesturesEnabled; - } + this.zoomGesturesEnabled = zoomGesturesEnabled; } /** @@ -719,14 +720,6 @@ public final class UiSettings { return zoomGesturesEnabled; } - void setZoomGestureChangeAllowed(boolean zoomGestureChangeAllowed) { - this.zoomGestureChangeAllowed = zoomGestureChangeAllowed; - } - - boolean isZoomGestureChangeAllowed() { - return zoomGestureChangeAllowed; - } - /** * <p> * Sets whether the zoom controls are enabled. @@ -765,9 +758,7 @@ public final class UiSettings { * @param doubleTapGesturesEnabled If true, zooming with a double tap is enabled. */ public void setDoubleTapGesturesEnabled(boolean doubleTapGesturesEnabled) { - if (doubleTapGestureChangeAllowed) { - this.doubleTapGesturesEnabled = doubleTapGesturesEnabled; - } + this.doubleTapGesturesEnabled = doubleTapGesturesEnabled; } /** @@ -779,14 +770,6 @@ public final class UiSettings { return doubleTapGesturesEnabled; } - void setDoubleTapGestureChangeAllowed(boolean doubleTapGestureChangeAllowed) { - this.doubleTapGestureChangeAllowed = doubleTapGestureChangeAllowed; - } - - boolean isDoubleTapGestureChangeAllowed() { - return doubleTapGestureChangeAllowed; - } - private void restoreDeselectMarkersOnTap(Bundle savedInstanceState) { setDeselectMarkersOnTap(savedInstanceState.getBoolean(MapboxConstants.STATE_DESELECT_MARKER_ON_TAP)); } @@ -828,9 +811,7 @@ public final class UiSettings { * @param scrollGesturesEnabled If true, scrolling is enabled. */ public void setScrollGesturesEnabled(boolean scrollGesturesEnabled) { - if (scrollGestureChangeAllowed) { - this.scrollGesturesEnabled = scrollGesturesEnabled; - } + this.scrollGesturesEnabled = scrollGesturesEnabled; } /** @@ -842,12 +823,105 @@ public final class UiSettings { return scrollGesturesEnabled; } - void setScrollGestureChangeAllowed(boolean scrollGestureChangeAllowed) { - this.scrollGestureChangeAllowed = scrollGestureChangeAllowed; + /** + * Returns whether scale velocity animation should execute after users finishes a gesture. + * + * @return If true, scale velocity animation is enabled. + */ + public boolean isScaleVelocityAnimationEnabled() { + return scaleVelocityAnimationEnabled; + } + + /** + * Set whether scale velocity animation should execute after users finishes a gesture. True by default. + * + * @param scaleVelocityAnimationEnabled If true, scale velocity animation will be enabled. + */ + public void setScaleVelocityAnimationEnabled(boolean scaleVelocityAnimationEnabled) { + this.scaleVelocityAnimationEnabled = scaleVelocityAnimationEnabled; + } + + /** + * Returns whether rotate velocity animation should execute after users finishes a gesture. + * + * @return If true, rotate velocity animation is enabled. + */ + public boolean isRotateVelocityAnimationEnabled() { + return rotateVelocityAnimationEnabled; + } + + /** + * Set whether rotate velocity animation should execute after users finishes a gesture. True by default. + * + * @param rotateVelocityAnimationEnabled If true, rotate velocity animation will be enabled. + */ + public void setRotateVelocityAnimationEnabled(boolean rotateVelocityAnimationEnabled) { + this.rotateVelocityAnimationEnabled = rotateVelocityAnimationEnabled; + } + + /** + * Returns whether fling velocity animation should execute after users finishes a gesture. + * + * @return If true, fling velocity animation is enabled. + */ + public boolean isFlingVelocityAnimationEnabled() { + return flingVelocityAnimationEnabled; + } + + /** + * Set whether fling velocity animation should execute after users finishes a gesture. True by default. + * + * @param flingVelocityAnimationEnabled If true, fling velocity animation will be enabled. + */ + public void setFlingVelocityAnimationEnabled(boolean flingVelocityAnimationEnabled) { + this.flingVelocityAnimationEnabled = flingVelocityAnimationEnabled; + } + + /** + * Set whether all velocity animations should execute after users finishes a gesture. + * + * @param allVelocityAnimationsEnabled If true, all velocity animations will be enabled. + */ + public void setAllVelocityAnimationsEnabled(boolean allVelocityAnimationsEnabled) { + setScaleVelocityAnimationEnabled(allVelocityAnimationsEnabled); + setRotateVelocityAnimationEnabled(allVelocityAnimationsEnabled); + setFlingVelocityAnimationEnabled(allVelocityAnimationsEnabled); + } + + /** + * Returns whether rotation threshold should be increase whenever scale is detected. + * + * @return If true, rotation threshold will be increased. + */ + public boolean isIncreaseRotateThresholdWhenScaling() { + return increaseRotateThresholdWhenScaling; + } + + /** + * Set whether rotation threshold should be increase whenever scale is detected. + * + * @param increaseRotateThresholdWhenScaling If true, rotation threshold will be increased. + */ + public void setIncreaseRotateThresholdWhenScaling(boolean increaseRotateThresholdWhenScaling) { + this.increaseRotateThresholdWhenScaling = increaseRotateThresholdWhenScaling; } - boolean isScrollGestureChangeAllowed() { - return scrollGestureChangeAllowed; + /** + * Returns whether scale threshold should be increase whenever rotation is detected. + * + * @return If true, scale threshold will be increased. + */ + public boolean isIncreaseScaleThresholdWhenRotating() { + return increaseScaleThresholdWhenRotating; + } + + /** + * set whether scale threshold should be increase whenever rotation is detected. + * + * @param increaseScaleThresholdWhenRotating If true, scale threshold will be increased. + */ + public void setIncreaseScaleThresholdWhenRotating(boolean increaseScaleThresholdWhenRotating) { + this.increaseScaleThresholdWhenRotating = increaseScaleThresholdWhenRotating; } /** diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/EGLConfigChooser.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/EGLConfigChooser.java index 247ffea906..46238ee789 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/EGLConfigChooser.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/EGLConfigChooser.java @@ -54,6 +54,17 @@ public class EGLConfigChooser implements GLSurfaceView.EGLConfigChooser { @SuppressWarnings("JavadocReference") private static final int EGL_OPENGL_ES2_BIT = 0x0004; + private boolean translucentSurface; + + public EGLConfigChooser() { + this(false); + } + + public EGLConfigChooser(boolean translucentSurface) { + super(); + this.translucentSurface = translucentSurface; + } + @Override public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) { int[] configAttribs = getConfigAttributes(); @@ -274,7 +285,7 @@ public class EGLConfigChooser implements GLSurfaceView.EGLConfigChooser { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, - EGL_ALPHA_SIZE, 0, + EGL_ALPHA_SIZE, translucentSurface ? 8 : 0, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 8, (emulator ? EGL_NONE : EGL_CONFORMANT), EGL_OPENGL_ES2_BIT, diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/package-info.java new file mode 100644 index 0000000000..b14b302652 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/egl/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android EGL API classes. + */ +package com.mapbox.mapboxsdk.maps.renderer.egl; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/glsurfaceview/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/glsurfaceview/package-info.java new file mode 100644 index 0000000000..aefcffef42 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/glsurfaceview/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android GLSurfaceView API classes. + */ +package com.mapbox.mapboxsdk.maps.renderer.glsurfaceview; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/package-info.java new file mode 100644 index 0000000000..f5d8021ea1 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android Renderer API classes. + */ +package com.mapbox.mapboxsdk.maps.renderer; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewMapRenderer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewMapRenderer.java index dcc95217ff..ad25dea0d3 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewMapRenderer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewMapRenderer.java @@ -17,17 +17,22 @@ import javax.microedition.khronos.opengles.GL10; */ public class TextureViewMapRenderer extends MapRenderer { private TextureViewRenderThread renderThread; + private boolean translucentSurface; /** * Create a {@link MapRenderer} for the given {@link TextureView} * - * @param context the current Context - * @param textureView the TextureView + * @param context the current Context + * @param textureView the TextureView + * @param localIdeographFontFamily the local font family + * @param translucentSurface the translucency flag */ public TextureViewMapRenderer(@NonNull Context context, @NonNull TextureView textureView, - String localIdeographFontFamily) { + String localIdeographFontFamily, + boolean translucentSurface) { super(context, localIdeographFontFamily); + this.translucentSurface = translucentSurface; renderThread = new TextureViewRenderThread(textureView, this); renderThread.start(); } @@ -95,4 +100,8 @@ public class TextureViewMapRenderer extends MapRenderer { public void onDestroy() { renderThread.onDestroy(); } + + public boolean isTranslucentSurface() { + return translucentSurface; + } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewRenderThread.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewRenderThread.java index 1e76ffe3fb..4bba160993 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewRenderThread.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/TextureViewRenderThread.java @@ -53,9 +53,10 @@ class TextureViewRenderThread extends Thread implements TextureView.SurfaceTextu */ @UiThread TextureViewRenderThread(@NonNull TextureView textureView, @NonNull TextureViewMapRenderer mapRenderer) { + textureView.setOpaque(!mapRenderer.isTranslucentSurface()); textureView.setSurfaceTextureListener(this); this.mapRenderer = mapRenderer; - this.eglHolder = new EGLHolder(new WeakReference<>(textureView)); + this.eglHolder = new EGLHolder(new WeakReference<>(textureView), mapRenderer.isTranslucentSurface()); } // SurfaceTextureListener methods @@ -324,6 +325,7 @@ class TextureViewRenderThread extends Thread implements TextureView.SurfaceTextu private static class EGLHolder { private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098; private final WeakReference<TextureView> textureViewWeakRef; + private boolean translucentSurface; private EGL10 egl; private EGLConfig eglConfig; @@ -331,8 +333,9 @@ class TextureViewRenderThread extends Thread implements TextureView.SurfaceTextu private EGLContext eglContext = EGL10.EGL_NO_CONTEXT; private EGLSurface eglSurface = EGL10.EGL_NO_SURFACE; - EGLHolder(WeakReference<TextureView> textureViewWeakRef) { + EGLHolder(WeakReference<TextureView> textureViewWeakRef, boolean translucentSurface) { this.textureViewWeakRef = textureViewWeakRef; + this.translucentSurface = translucentSurface; } void prepare() { @@ -357,7 +360,7 @@ class TextureViewRenderThread extends Thread implements TextureView.SurfaceTextu eglConfig = null; eglContext = EGL10.EGL_NO_CONTEXT; } else if (eglContext == EGL10.EGL_NO_CONTEXT) { - eglConfig = new EGLConfigChooser().chooseConfig(egl, eglDisplay); + eglConfig = new EGLConfigChooser(translucentSurface).chooseConfig(egl, eglDisplay); int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE}; eglContext = egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list); } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/package-info.java new file mode 100644 index 0000000000..d3585d41f9 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/renderer/textureview/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android TextureView API classes. + */ +package com.mapbox.mapboxsdk.maps.renderer.textureview; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/CompassView.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/CompassView.java index 1e604c9bef..fb2c70cb73 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/CompassView.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/CompassView.java @@ -1,5 +1,6 @@ package com.mapbox.mapboxsdk.maps.widgets; +import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; @@ -22,6 +23,7 @@ import com.mapbox.mapboxsdk.maps.MapboxMap; * use {@link com.mapbox.mapboxsdk.maps.UiSettings}. * </p> */ +@SuppressLint("AppCompatCustomView") public final class CompassView extends ImageView implements Runnable { public static final long TIME_WAIT_IDLE = 500; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationView.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationView.java deleted file mode 100644 index 1cdd91028d..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationView.java +++ /dev/null @@ -1,1104 +0,0 @@ -package com.mapbox.mapboxsdk.maps.widgets; - -import android.animation.ValueAnimator; -import android.annotation.SuppressLint; -import android.content.Context; -import android.graphics.Camera; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.PointF; -import android.graphics.PorterDuff; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Bundle; -import android.os.Parcelable; -import android.os.SystemClock; -import android.support.annotation.ColorInt; -import android.support.annotation.FloatRange; -import android.support.annotation.IntRange; -import android.support.annotation.NonNull; -import android.util.AttributeSet; -import android.view.View; -import android.view.ViewGroup; - -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; -import com.mapbox.mapboxsdk.constants.MyBearingTracking; -import com.mapbox.mapboxsdk.constants.MyLocationTracking; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; -import com.mapbox.services.android.telemetry.location.LocationEngine; -import com.mapbox.services.android.telemetry.location.LocationEngineListener; -import com.mapbox.services.android.telemetry.location.LocationEnginePriority; - -import java.lang.ref.WeakReference; - -import timber.log.Timber; - -/** - * UI element overlaid on a map to show the user's location. - * <p> - * Use {@link MyLocationViewSettings} to manipulate the state of this view. - * </p> - * - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ -@Deprecated -public class MyLocationView extends View { - - private static final int UNDEFINED_TINT_COLOR = -1; - private MyLocationBehavior myLocationBehavior; - private MapboxMap mapboxMap; - - private Projection projection; - private float[] projectedCoordinate = new float[2]; - private float projectedX; - private float projectedY; - - private float contentPaddingX; - private float contentPaddingY; - - private LatLng latLng; - private Location location; - private LocationEngine locationEngine; - private long locationUpdateTimestamp; - private float previousDirection; - - private float accuracy; - private Paint accuracyPaint; - private float accuracyThreshold; - - private ValueAnimator locationChangeAnimator; - private ValueAnimator accuracyAnimator; - private ValueAnimator directionAnimator; - private boolean locationChangeAnimationEnabled = true; - - private ValueAnimator.AnimatorUpdateListener invalidateSelfOnUpdateListener = - new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(ValueAnimator animation) { - invalidate(); - } - }; - - private Drawable foregroundDrawable; - private Drawable foregroundBearingDrawable; - private Drawable backgroundDrawable; - - private Rect foregroundBounds; - private Rect backgroundBounds; - - private int backgroundOffsetLeft; - private int backgroundOffsetTop; - private int backgroundOffsetRight; - private int backgroundOffsetBottom; - - private Matrix matrix; - private Camera camera; - private PointF screenLocation; - - // camera vars - private double tilt; - private double bearing; - private float magneticHeading; - - // Controls the compass update rate in milliseconds - private static final int COMPASS_UPDATE_RATE_MS = 500; - - @MyLocationTracking.Mode - private int myLocationTrackingMode; - - @MyBearingTracking.Mode - private int myBearingTrackingMode; - - private GpsLocationListener userLocationListener; - private CompassListener compassListener; - - public MyLocationView(Context context) { - super(context); - init(context); - } - - public MyLocationView(Context context, AttributeSet attrs) { - super(context, attrs); - init(context); - } - - public MyLocationView(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - init(context); - } - - private void init(Context context) { - if (isInEditMode()) { - return; - } - - setEnabled(false); - - // setup LayoutParams - ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT); - setLayoutParams(lp); - - matrix = new Matrix(); - camera = new Camera(); - camera.setLocation(0, 0, -1000); - accuracyPaint = new Paint(); - - myLocationBehavior = new MyLocationBehaviorFactory().getBehavioralModel(MyLocationTracking.TRACKING_NONE); - compassListener = new CompassListener(context); - } - - @Deprecated - public void init(LocationEngine locationSource) { - this.locationEngine = locationSource; - } - - /** - * Set the foreground drawable, for internal use only. - * - * @param defaultDrawable The drawable shown when showing this view - * @param bearingDrawable The drawable shown when tracking of bearing is enabled - */ - public final void setForegroundDrawables(Drawable defaultDrawable, Drawable bearingDrawable) { - if (defaultDrawable == null) { - return; - } - - if (bearingDrawable == null) { - // if user only provided one resource - // use same for bearing mode - bearingDrawable = defaultDrawable.getConstantState().newDrawable(); - } - - if (backgroundDrawable == null) { - // if the user didn't provide a background resource we will use the foreground resource instead, - // we need to create a new drawable to handle tinting correctly - backgroundDrawable = defaultDrawable.getConstantState().newDrawable(); - } - - if (defaultDrawable.getIntrinsicWidth() != bearingDrawable.getIntrinsicWidth() - || defaultDrawable.getIntrinsicHeight() != bearingDrawable.getIntrinsicHeight()) { - throw new RuntimeException("The dimensions from location and bearing drawables should be match"); - } - - foregroundDrawable = defaultDrawable; - foregroundBearingDrawable = bearingDrawable; - - invalidateBounds(); - } - - /** - * Set the foreground drawable tint, for internal use only. - * - * @param color The color to tint the drawable with - */ - public final void setForegroundDrawableTint(@ColorInt int color) { - applyDrawableTint(foregroundDrawable, color); - applyDrawableTint(foregroundBearingDrawable, color); - invalidate(); - } - - /** - * Set the shadow drawable, for internal use only. - * - * @param drawable The drawable shown as shadow - */ - public final void setShadowDrawable(Drawable drawable) { - setShadowDrawable(drawable, 0, 0, 0, 0); - } - - /** - * Set the shadow drawable with some additional offset. - * - * @param drawable The drawable shown as shadow - * @param left The left offset margin - * @param top The top offset margin - * @param right The right offset margin - * @param bottom The bottom offset margin - */ - public final void setShadowDrawable(Drawable drawable, int left, int top, int right, int bottom) { - if (drawable != null) { - backgroundDrawable = drawable; - } - - backgroundOffsetLeft = left; - backgroundOffsetTop = top; - backgroundOffsetRight = right; - backgroundOffsetBottom = bottom; - - invalidateBounds(); - } - - /** - * Set the shadow drawable tint color, for internal use only. - * - * @param color The tint color to apply - */ - public final void setShadowDrawableTint(@ColorInt int color) { - if (backgroundDrawable == null) { - return; - } - applyDrawableTint(backgroundDrawable, color); - invalidate(); - } - - /** - * Set the accuracy tint color, for internal use only. - * - * @param color The tint color to apply - */ - public final void setAccuracyTint(@ColorInt int color) { - int alpha = accuracyPaint.getAlpha(); - accuracyPaint.setColor(color); - accuracyPaint.setAlpha(alpha); - invalidate(); - } - - /** - * Set the accuracy alpha value, for internal use only. - * - * @param alpha The alpha accuracy value to apply - */ - public final void setAccuracyAlpha(@IntRange(from = 0, to = 255) int alpha) { - accuracyPaint.setAlpha(alpha); - invalidate(); - } - - private void invalidateBounds() { - if (backgroundDrawable == null || foregroundDrawable == null || foregroundBearingDrawable == null) { - return; - } - - int backgroundWidth = backgroundDrawable.getIntrinsicWidth(); - int backgroundHeight = backgroundDrawable.getIntrinsicHeight(); - int horizontalOffset = backgroundOffsetLeft - backgroundOffsetRight; - int verticalOffset = backgroundOffsetTop - backgroundOffsetBottom; - backgroundBounds = new Rect(-backgroundWidth / 2 + horizontalOffset, - -backgroundHeight / 2 + verticalOffset, backgroundWidth / 2 + horizontalOffset, backgroundHeight / 2 - + verticalOffset); - backgroundDrawable.setBounds(backgroundBounds); - - int foregroundWidth = foregroundDrawable.getIntrinsicWidth(); - int foregroundHeight = foregroundDrawable.getIntrinsicHeight(); - foregroundBounds = new Rect(-foregroundWidth / 2, -foregroundHeight / 2, foregroundWidth / 2, foregroundHeight / 2); - foregroundDrawable.setBounds(foregroundBounds); - foregroundBearingDrawable.setBounds(foregroundBounds); - - // invoke a new draw - invalidate(); - } - - @Override - protected void onDraw(Canvas canvas) { - super.onDraw(canvas); - - if (location == null || foregroundBounds == null || backgroundBounds == null || accuracyAnimator == null - || screenLocation == null) { - // Not ready yet - return; - } - - final PointF pointF = screenLocation; - float metersPerPixel = (float) projection.getMetersPerPixelAtLatitude(location.getLatitude()); - float accuracyPixels = (Float) accuracyAnimator.getAnimatedValue() / metersPerPixel; - - // reset - matrix.reset(); - projectedCoordinate[0] = 0; - projectedCoordinate[1] = 0; - - // put camera in position - camera.save(); - camera.rotate((float) tilt, 0, 0); - camera.getMatrix(matrix); - - if (myBearingTrackingMode != MyBearingTracking.NONE && directionAnimator != null) { - matrix.preRotate((Float) directionAnimator.getAnimatedValue()); - } - - matrix.preTranslate(0, contentPaddingY); - matrix.postTranslate(pointF.x, pointF.y - contentPaddingY); - - // concat our matrix on canvas - canvas.concat(matrix); - - // calculate focal point - matrix.mapPoints(projectedCoordinate); - projectedX = pointF.x - projectedCoordinate[0]; - projectedY = pointF.y - projectedCoordinate[1]; - - // restore orientation from camera - camera.restore(); - - // draw circle - canvas.drawCircle(0, 0, accuracyPixels, accuracyPaint); - - // draw shadow - if (backgroundDrawable != null) { - backgroundDrawable.draw(canvas); - } - - // draw foreground - if (myBearingTrackingMode == MyBearingTracking.NONE) { - if (foregroundDrawable != null) { - foregroundDrawable.draw(canvas); - } - } else if (foregroundBearingDrawable != null && foregroundBounds != null) { - if (myBearingTrackingMode == MyBearingTracking.GPS - || myBearingTrackingMode == MyBearingTracking.GPS_NORTH_FACING - || compassListener.isSensorAvailable()) { - foregroundBearingDrawable.draw(canvas); - } else { - // We are tracking MyBearingTracking.COMPASS, but sensor is not available. - foregroundDrawable.draw(canvas); - } - } - } - - /** - * Set the tilt value, for internal use only. - * - * @param tilt The tilt to apply - */ - public void setTilt(@FloatRange(from = 0, to = 60.0f) double tilt) { - this.tilt = tilt; - invalidate(); - } - - /** - * Set the bearing value, for internal use only. - * - * @param bearing The bearing to apply - */ - public void setBearing(double bearing) { - this.bearing = bearing; - if (myLocationTrackingMode == MyLocationTracking.TRACKING_NONE) { - if (myBearingTrackingMode == MyBearingTracking.GPS - || myBearingTrackingMode == MyBearingTracking.GPS_NORTH_FACING) { - if (location != null) { - setCompass(location.getBearing() - bearing); - } - } else if (myBearingTrackingMode == MyBearingTracking.COMPASS && compassListener.isSensorAvailable()) { - setCompass(magneticHeading - bearing); - } - } - } - - /** - * Set the bearing and tilt from a camera position, for internal use only. - * - * @param position The camera position to extract bearing and tilt from - */ - public void setCameraPosition(CameraPosition position) { - if (position != null) { - setBearing(position.bearing); - setTilt(position.tilt); - } - } - - /** - * Called when the hosting activity is starting, for internal use only. - */ - public void onStart() { - if (myBearingTrackingMode == MyBearingTracking.COMPASS && compassListener.isSensorAvailable()) { - compassListener.onResume(); - } - if (isEnabled()) { - toggleGps(true); - } - } - - /** - * Called when the hosting activity is stopping, for internal use only. - */ - public void onStop() { - compassListener.onPause(); - toggleGps(false); - } - - @Override - protected void onDetachedFromWindow() { - super.onDetachedFromWindow(); - // cleanup to prevent memory leaks - if (locationChangeAnimator != null) { - locationChangeAnimator.cancel(); - locationChangeAnimator = null; - } - - if (accuracyAnimator != null) { - accuracyAnimator.cancel(); - accuracyAnimator = null; - } - - if (directionAnimator != null) { - directionAnimator.cancel(); - directionAnimator = null; - } - - if (userLocationListener != null) { - locationEngine.removeLocationEngineListener(userLocationListener); - locationEngine = null; - userLocationListener = null; - } - } - - /** - * Update current locationstate. - */ - public void update() { - if (isEnabled()) { - myLocationBehavior.invalidate(); - } else { - setVisibility(View.INVISIBLE); - } - } - - // TODO refactor MapboxMap out - public void setMapboxMap(MapboxMap mapboxMap) { - this.mapboxMap = mapboxMap; - this.projection = mapboxMap.getProjection(); - } - - /** - * Set the enabled state, for internal use only. - * - * @param enabled The value to set the state to - */ - @Override - public void setEnabled(boolean enabled) { - setEnabled(enabled, false); - } - - /** - * Set the enabled state, for internal use only. - * - * @param enabled The value to set the state to - * @param isCustomLocationEngine Flag handling for handling user provided custom location engine - */ - public void setEnabled(boolean enabled, boolean isCustomLocationEngine) { - super.setEnabled(enabled); - setVisibility(enabled ? View.VISIBLE : View.INVISIBLE); - toggleGps(enabled, isCustomLocationEngine); - } - - /** - * Save the view instance state, for internal use only. - * - * @return the marshaled representation of the view state - */ - @Override - protected Parcelable onSaveInstanceState() { - Bundle bundle = new Bundle(); - bundle.putParcelable("superState", super.onSaveInstanceState()); - bundle.putDouble("tilt", tilt); - return bundle; - } - - /** - * Restore the view instance state, for internal use only. - * - * @param state the marshalled representation of the state to restore - */ - @Override - public void onRestoreInstanceState(Parcelable state) { - if (state instanceof Bundle) { - Bundle bundle = (Bundle) state; - tilt = bundle.getDouble("tilt"); - state = bundle.getParcelable("superState"); - } - super.onRestoreInstanceState(state); - } - - private void toggleGps(boolean enableGps) { - toggleGps(enableGps, mapboxMap != null - && mapboxMap.getTrackingSettings().isCustomLocationSource()); - } - - /** - * Enabled / Disable GPS location updates along with updating the UI, for internal use only. - * - * @param enableGps true if GPS is to be enabled, false if GPS is to be disabled - */ - private void toggleGps(boolean enableGps, boolean isCustomLocationEngine) { - if (enableGps) { - if (locationEngine == null) { - if (!isCustomLocationEngine) { - locationEngine = Mapbox.getLocationEngine(); - } else { - return; - } - } - - if (userLocationListener == null) { - userLocationListener = new GpsLocationListener(this, locationEngine); - } - - locationEngine.addLocationEngineListener(userLocationListener); - locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY); - locationEngine.activate(); - } else { - if (locationEngine == null) { - return; - } - // Disable location and user dot - location = null; - locationEngine.removeLocationEngineListener(userLocationListener); - locationEngine.removeLocationUpdates(); - locationEngine.deactivate(); - restoreLocationEngine(); - } - } - - /** - * Get the current location. - * - * @return the current location - */ - public Location getLocation() { - return location; - } - - /** - * Set the current location, for internal use only. - * - * @param location The current location - */ - public void setLocation(Location location) { - if (location == null) { - this.location = null; - return; - } - - this.location = location; - myLocationBehavior.updateLatLng(location); - - if (mapboxMap != null && (myBearingTrackingMode == MyBearingTracking.GPS - || myBearingTrackingMode == MyBearingTracking.GPS_NORTH_FACING) - && myLocationTrackingMode == MyLocationTracking.TRACKING_NONE) { - setBearing(mapboxMap.getCameraPosition().bearing); - } - } - - /** - * Set location change animation enabled, for internal use only. - * - * @param locationChangeAnimationEnabled True if location changes are animated - */ - public void setLocationChangeAnimationEnabled(boolean locationChangeAnimationEnabled) { - this.locationChangeAnimationEnabled = locationChangeAnimationEnabled; - } - - /** - * Set accuracy circle threshold. Circle won't be displayed if accuracy is below set value. - * For internal use only. - * - * @param accuracyThreshold Value below which circle won't be displayed - */ - public void setAccuracyThreshold(float accuracyThreshold) { - this.accuracyThreshold = accuracyThreshold; - } - - /** - * Set the bearing tracking mode, for internal use only. - * - * @param myBearingTrackingMode The bearing tracking mode - */ - public void setMyBearingTrackingMode(@MyBearingTracking.Mode int myBearingTrackingMode) { - this.myBearingTrackingMode = myBearingTrackingMode; - if (myBearingTrackingMode == MyBearingTracking.COMPASS && compassListener.isSensorAvailable()) { - compassListener.onResume(); - } else { - compassListener.onPause(); - if (myLocationTrackingMode == MyLocationTracking.TRACKING_FOLLOW - && myBearingTrackingMode == MyBearingTracking.GPS) { - // always face north - setCompass(0); - } else { - myLocationBehavior.invalidate(); - } - } - invalidate(); - } - - /** - * Set the location tracking mode, for internla use only. - * - * @param myLocationTrackingMode The location tracking mode - */ - public void setMyLocationTrackingMode(@MyLocationTracking.Mode int myLocationTrackingMode) { - MyLocationBehaviorFactory factory = new MyLocationBehaviorFactory(); - myLocationBehavior = factory.getBehavioralModel(myLocationTrackingMode); - - if (location != null) { - if (myLocationTrackingMode == MyLocationTracking.TRACKING_FOLLOW) { - // center map directly - mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location))); - } else { - // do not use interpolated location from tracking mode - latLng = null; - } - myLocationBehavior.updateLatLng(location); - } - - this.myLocationTrackingMode = myLocationTrackingMode; - invalidate(); - } - - /** - * Get the location tracking mode, for internal use only. - * - * @return The location tracking mode - */ - @MyLocationTracking.Mode - public int getMyLocationTrackingMode() { - return myLocationTrackingMode; - } - - - /** - * Get the bearing tracking mode, for internal use only. - * - * @return the bearing tracking mode - */ - @MyBearingTracking.Mode - public int getMyBearingTrackingMode() { - return myBearingTrackingMode; - } - - /** - * Set the compass bearing value, for internal use only. - * - * @param bearing The compas bearing value - */ - private void setCompass(double bearing) { - setCompass(bearing, 0 /* no animation */); - } - - private void setCompass(double bearing, long duration) { - float oldDir = previousDirection; - if (directionAnimator != null) { - oldDir = (Float) directionAnimator.getAnimatedValue(); - directionAnimator.end(); - directionAnimator = null; - } - - float newDir = (float) bearing; - float diff = oldDir - newDir; - if (diff > 180.0f) { - newDir += 360.0f; - } else if (diff < -180.0f) { - newDir -= 360.f; - } - previousDirection = newDir; - - directionAnimator = ValueAnimator.ofFloat(oldDir, newDir); - directionAnimator.setDuration(duration); - directionAnimator.addUpdateListener(invalidateSelfOnUpdateListener); - directionAnimator.start(); - } - - /** - * Get the center of this view in screen coordinates. - * - * @return the center of the view - */ - public PointF getCenter() { - return new PointF(getCenterX(), getCenterY()); - } - - /** - * Get the x value of the center of this view. - * - * @return the x value of the center of the view - */ - private float getCenterX() { - return (getX() + getMeasuredWidth()) / 2 + contentPaddingX - projectedX; - } - - /** - * Get the y value of the center of this view. - * - * @return the y value of the center of the view - */ - private float getCenterY() { - return (getY() + getMeasuredHeight()) / 2 + contentPaddingY - projectedY; - } - - public void setContentPadding(int[] padding) { - contentPaddingX = (padding[0] - padding[2]) / 2; - contentPaddingY = (padding[1] - padding[3]) / 2; - } - - /** - * Set the location source from which location updates are received, for internal use only. - * - * @param locationEngine The location engine to receive updates from - */ - public void setLocationSource(LocationEngine locationEngine) { - toggleGps(false); - this.locationEngine = locationEngine; - this.userLocationListener = null; - setEnabled(isEnabled(), locationEngine != null); - } - - private void applyDrawableTint(Drawable drawable, @ColorInt int color) { - if (color == UNDEFINED_TINT_COLOR) { - removeTintColorFilter(drawable); - } else { - applyTintColorFilter(drawable, color); - } - } - - private void removeTintColorFilter(Drawable drawable) { - if (drawable != null) { - drawable.mutate().setColorFilter(null); - } - } - - private void applyTintColorFilter(Drawable drawable, @ColorInt int color) { - if (drawable != null) { - drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN); - } - } - - private void restoreLocationEngine() { - locationEngine.setPriority(LocationEnginePriority.LOW_POWER); - locationEngine.activate(); - } - - private static class GpsLocationListener implements LocationEngineListener { - - private WeakReference<MyLocationView> userLocationView; - private WeakReference<LocationEngine> locationSource; - - GpsLocationListener(MyLocationView myLocationView, LocationEngine locationEngine) { - userLocationView = new WeakReference<>(myLocationView); - locationSource = new WeakReference<>(locationEngine); - } - - @SuppressLint("MissingPermission") - @Override - public void onConnected() { - MyLocationView locationView = userLocationView.get(); - LocationEngine locationEngine = locationSource.get(); - if (locationView != null && locationEngine != null) { - Location lastKnownLocation = locationEngine.getLastLocation(); - if (lastKnownLocation != null) { - locationView.setLocation(lastKnownLocation); - } - locationEngine.requestLocationUpdates(); - } - } - - /** - * Callback method for receiving location updates from LocationServices. - * - * @param location The new Location data - */ - @Override - public void onLocationChanged(Location location) { - MyLocationView locationView = userLocationView.get(); - if (locationView != null) { - locationView.setLocation(location); - } - } - } - - private class CompassListener implements SensorEventListener { - - private final SensorManager sensorManager; - - private Sensor rotationVectorSensor; - private float[] matrix = new float[9]; - private float[] rotationVectorValue; - private float[] truncatedRotationVectorValue = new float[4]; - - private float[] orientation = new float[3]; - private boolean reportMissingSensor = true; - // Compass data - private long compassUpdateNextTimestamp = 0; - - CompassListener(Context context) { - sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - rotationVectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); - } - - public void onResume() { - sensorManager.registerListener(this, rotationVectorSensor, SensorManager.SENSOR_DELAY_GAME); - } - - public void onPause() { - sensorManager.unregisterListener(this, rotationVectorSensor); - } - - public boolean isSensorAvailable() { - if (rotationVectorSensor == null && reportMissingSensor) { - reportMissingSensor = false; - Timber.e("Sensor.TYPE_ROTATION_VECTOR is missing from this device. Unable to use MyBearingTracking.COMPASS."); - } - return rotationVectorSensor != null; - } - - @Override - public void onSensorChanged(SensorEvent event) { - - // check when the last time the compass was updated, return if too soon. - long currentTime = SystemClock.elapsedRealtime(); - if (currentTime < compassUpdateNextTimestamp) { - return; - } - - if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) { - rotationVectorValue = getRotationVectorFromSensorEvent(event); - SensorManager.getRotationMatrixFromVector(matrix, rotationVectorValue); - SensorManager.getOrientation(matrix, orientation); - - magneticHeading = (float) Math.toDegrees(SensorManager.getOrientation(matrix, orientation)[0]); - if (myLocationTrackingMode == MyLocationTracking.TRACKING_FOLLOW) { - // Change the user location view orientation to reflect the device orientation - rotateCamera(magneticHeading); - setCompass(0, COMPASS_UPDATE_RATE_MS); - } else { - // Change compass direction - setCompass(magneticHeading - bearing, COMPASS_UPDATE_RATE_MS); - } - - compassUpdateNextTimestamp = currentTime + COMPASS_UPDATE_RATE_MS; - } - } - - /** - * Pulls out the rotation vector from a SensorEvent, with a maximum length - * vector of four elements to avoid potential compatibility issues. - * - * @param event the sensor event - * @return the events rotation vector, potentially truncated - */ - @NonNull - float[] getRotationVectorFromSensorEvent(@NonNull SensorEvent event) { - if (event.values.length > 4) { - // On some Samsung devices SensorManager.getRotationMatrixFromVector - // appears to throw an exception if rotation vector has length > 4. - // For the purposes of this class the first 4 values of the - // rotation vector are sufficient (see crbug.com/335298 for details). - // Only affects Android 4.3 - System.arraycopy(event.values, 0, truncatedRotationVectorValue, 0, 4); - return truncatedRotationVectorValue; - } else { - return event.values; - } - } - - private void rotateCamera(float rotation) { - CameraPosition.Builder builder = new CameraPosition.Builder(); - builder.bearing(rotation); - mapboxMap.easeCamera(CameraUpdateFactory.newCameraPosition(builder.build()), COMPASS_UPDATE_RATE_MS, - false /*linear interpolator*/, null); - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - } - - } - - private class MarkerCoordinateAnimatorListener implements ValueAnimator.AnimatorUpdateListener { - - private MyLocationBehavior behavior; - private double fromLat; - private double fromLng; - private double toLat; - private double toLng; - - private MarkerCoordinateAnimatorListener(MyLocationBehavior myLocationBehavior, LatLng from, LatLng to) { - behavior = myLocationBehavior; - fromLat = from.getLatitude(); - fromLng = from.getLongitude(); - toLat = to.getLatitude(); - toLng = to.getLongitude(); - } - - @Override - public void onAnimationUpdate(ValueAnimator animation) { - float frac = animation.getAnimatedFraction(); - double latitude = fromLat + (toLat - fromLat) * frac; - double longitude = fromLng + (toLng - fromLng) * frac; - behavior.updateLatLng(latitude, longitude); - update(); - } - } - - private class MyLocationBehaviorFactory { - - MyLocationBehavior getBehavioralModel(@MyLocationTracking.Mode int mode) { - if (mode == MyLocationTracking.TRACKING_NONE) { - return new MyLocationShowBehavior(); - } else { - return new MyLocationTrackingBehavior(); - } - } - } - - private abstract class MyLocationBehavior { - - MyLocationBehavior() { - if (latLng != null) { - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - } - } - - void updateLatLng(@NonNull Location newLocation) { - location = newLocation; - } - - void updateLatLng(double lat, double lon) { - if (latLng != null) { - latLng.setLatitude(lat); - latLng.setLongitude(lon); - } - } - - void updateAccuracy(@NonNull Location location) { - if (accuracyAnimator != null && accuracyAnimator.isRunning()) { - // use current accuracy as a starting point - accuracy = (Float) accuracyAnimator.getAnimatedValue(); - accuracyAnimator.end(); - } - - float newAccuracy = location.getAccuracy() >= accuracyThreshold ? location.getAccuracy() : 0f; - accuracyAnimator = ValueAnimator.ofFloat(accuracy, newAccuracy); - accuracyAnimator.setDuration(750); - accuracyAnimator.start(); - accuracy = newAccuracy; - } - - abstract void invalidate(); - } - - private class MyLocationTrackingBehavior extends MyLocationBehavior { - - @Override - void updateLatLng(@NonNull Location location) { - super.updateLatLng(location); - if (latLng == null) { - // first location fix - latLng = new LatLng(location); - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - } - - // updateLatLng timestamp - float previousUpdateTimeStamp = locationUpdateTimestamp; - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - - // calculate animation duration - int animationDuration; - if (previousUpdateTimeStamp == 0) { - animationDuration = 0; - } else { - animationDuration = (int) ((locationUpdateTimestamp - previousUpdateTimeStamp) * 1.1f) - /*make animation slightly longer*/; - } - - // calculate interpolated location - latLng = new LatLng(location); - CameraPosition.Builder builder = new CameraPosition.Builder().target(latLng); - - // add direction - if (myBearingTrackingMode == MyBearingTracking.GPS) { - if (location.hasBearing()) { - builder.bearing(location.getBearing()); - } - setCompass(0, COMPASS_UPDATE_RATE_MS); - } - - if (myBearingTrackingMode == MyBearingTracking.GPS_NORTH_FACING) { - builder.bearing(0); - if (location.hasBearing()) { - setCompass(location.getBearing(), COMPASS_UPDATE_RATE_MS); - } - } - - // accuracy - updateAccuracy(location); - - if (locationChangeAnimationEnabled && animationDuration > 0) { - // ease to new camera position with a linear interpolator - mapboxMap.easeCamera(CameraUpdateFactory.newCameraPosition(builder.build()), animationDuration, false, null, - true); - } else { - mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(builder.build())); - } - } - - @Override - void invalidate() { - int[] mapPadding = mapboxMap.getPadding(); - float x = (getWidth() + mapPadding[0] - mapPadding[2]) / 2 + contentPaddingX; - float y = (getHeight() - mapPadding[3] + mapPadding[1]) / 2 + contentPaddingY; - screenLocation = new PointF(x, y); - MyLocationView.this.invalidate(); - } - } - - private class MyLocationShowBehavior extends MyLocationBehavior { - - @Override - void updateLatLng(@NonNull final Location location) { - super.updateLatLng(location); - if (latLng == null) { - // first location update - latLng = new LatLng(location); - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - } - - // update LatLng location - LatLng newLocation = new LatLng(location); - - // update LatLng accuracy - updateAccuracy(location); - - // calculate updateLatLng time + add some extra offset to improve animation - long previousUpdateTimeStamp = locationUpdateTimestamp; - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - long locationUpdateDuration = (long) ((locationUpdateTimestamp - previousUpdateTimeStamp) * 1.2f); - - // animate changes - if (locationChangeAnimator != null) { - locationChangeAnimator.end(); - locationChangeAnimator = null; - } - - locationChangeAnimator = ValueAnimator.ofFloat(0.0f, 1.0f); - if (locationChangeAnimationEnabled) { - locationChangeAnimator.setDuration(locationUpdateDuration); - } else { - locationChangeAnimator.setDuration(0); - } - locationChangeAnimator.addUpdateListener(new MarkerCoordinateAnimatorListener(this, - latLng, newLocation - )); - locationChangeAnimator.start(); - latLng = newLocation; - } - - @Override - void invalidate() { - if (latLng != null) { - screenLocation = projection.toScreenLocation(latLng); - } - MyLocationView.this.invalidate(); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationViewSettings.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationViewSettings.java deleted file mode 100644 index ec7c53e1d0..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/widgets/MyLocationViewSettings.java +++ /dev/null @@ -1,389 +0,0 @@ -package com.mapbox.mapboxsdk.maps.widgets; - -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.support.annotation.ColorInt; -import android.support.annotation.IntRange; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.constants.MyLocationTracking; -import com.mapbox.mapboxsdk.maps.FocalPointChangeListener; -import com.mapbox.mapboxsdk.maps.MapboxMapOptions; -import com.mapbox.mapboxsdk.maps.Projection; -import com.mapbox.mapboxsdk.utils.BitmapUtils; - -/** - * Settings to configure the visual appearance of the MyLocationView. - * - * @deprecated use location layer plugin from - * https://github.com/mapbox/mapbox-plugins-android/tree/master/plugins/locationlayer instead. - */ -@Deprecated -public class MyLocationViewSettings { - - private Projection projection; - private MyLocationView myLocationView; - private FocalPointChangeListener focalPointChangeListener; - - // - // State - // - - private boolean enabled; - - // - // Foreground - // - - private Drawable foregroundDrawable; - private Drawable foregroundBearingDrawable; - - @ColorInt - private int foregroundTintColor; - - // - // Background - // - - private Drawable backgroundDrawable; - private int[] backgroundOffset = new int[4]; - - @ColorInt - private int backgroundTintColor; - - // - // Accuracy - // - - private int accuracyAlpha; - private float accuracyThreshold = 0f; - - @ColorInt - private int accuracyTintColor; - - // - // Padding - // - - private int[] padding = new int[4]; - - /** - * Creates an instance of MyLocationViewSettings - * <p> - * - * @param myLocationView the MyLocationView to apply the settings to - * @param projection the MapView projection - * @param focalPointChangedListener the interface to be invoked when focal points changes - * @see MyLocationView - */ - public MyLocationViewSettings(MyLocationView myLocationView, Projection projection, FocalPointChangeListener - focalPointChangedListener) { - this.myLocationView = myLocationView; - this.projection = projection; - this.focalPointChangeListener = focalPointChangedListener; - } - - /** - * Initialise this with MapboxMapOptions. - * - * @param options the options to initialise this class from - */ - public void initialise(@NonNull MapboxMapOptions options) { - CameraPosition position = options.getCamera(); - if (position != null && !position.equals(CameraPosition.DEFAULT)) { - setTilt(position.tilt); - } - setForegroundDrawable(options.getMyLocationForegroundDrawable(), options.getMyLocationForegroundBearingDrawable()); - setForegroundTintColor(options.getMyLocationForegroundTintColor()); - setBackgroundDrawable(options.getMyLocationBackgroundDrawable(), options.getMyLocationBackgroundPadding()); - setBackgroundTintColor(options.getMyLocationBackgroundTintColor()); - setAccuracyAlpha(options.getMyLocationAccuracyAlpha()); - setAccuracyTintColor(options.getMyLocationAccuracyTintColor()); - setAccuracyThreshold(options.getMyLocationAccuracyThreshold()); - } - - public void onSaveInstanceState(Bundle outState) { - outState.putBoolean(MapboxConstants.STATE_LOCATION_VIEW_ENABLED, isEnabled()); - outState.putByteArray( - MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_DRAWABLE, - BitmapUtils.getByteArrayFromDrawable(getForegroundDrawable()) - ); - outState.putByteArray( - MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_BEARING_DRAWABLE, - BitmapUtils.getByteArrayFromDrawable(getForegroundBearingDrawable()) - ); - outState.putInt(MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_TINT_COLOR, getForegroundTintColor()); - outState.putByteArray( - MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_DRAWABLE, - BitmapUtils.getByteArrayFromDrawable(getBackgroundDrawable()) - ); - outState.putIntArray(MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_OFFSET, getBackgroundOffset()); - outState.putInt(MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_TINT_COLOR, getBackgroundTintColor()); - outState.putInt(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_ALPHA, getAccuracyAlpha()); - outState.putInt(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_TINT_COLOR, getAccuracyTintColor()); - outState.putFloat(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_THRESHOLD, getAccuracyThreshold()); - outState.putIntArray(MapboxConstants.STATE_LOCATION_VIEW_PADDING, getPadding()); - } - - public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { - setEnabled(savedInstanceState.getBoolean(MapboxConstants.STATE_LOCATION_VIEW_ENABLED)); - setForegroundDrawable( - BitmapUtils.getDrawableFromByteArray( - myLocationView.getContext(), - savedInstanceState.getByteArray(MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_DRAWABLE) - ), - BitmapUtils.getDrawableFromByteArray( - myLocationView.getContext(), - savedInstanceState.getByteArray(MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_BEARING_DRAWABLE) - ) - ); - setForegroundTintColor(savedInstanceState.getInt(MapboxConstants.STATE_LOCATION_VIEW_FOREGROUND_TINT_COLOR)); - setBackgroundDrawable( - BitmapUtils.getDrawableFromByteArray( - myLocationView.getContext(), - savedInstanceState.getByteArray(MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_DRAWABLE) - ), - savedInstanceState.getIntArray(MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_OFFSET) - ); - setBackgroundTintColor(savedInstanceState.getInt(MapboxConstants.STATE_LOCATION_VIEW_BACKGROUND_TINT_COLOR)); - setAccuracyAlpha(savedInstanceState.getInt(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_ALPHA)); - setAccuracyTintColor(savedInstanceState.getInt(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_TINT_COLOR)); - setAccuracyThreshold(savedInstanceState.getFloat(MapboxConstants.STATE_LOCATION_VIEW_ACCURACY_THRESHOLD)); - setPadding(savedInstanceState.getIntArray(MapboxConstants.STATE_LOCATION_VIEW_PADDING)); - } - - /** - * Returns if the MyLocationView is enabled - * - * @return true if MyLocationView is enabled, - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Set the enabled state of MyLocationView - * - * @param enabled true shows the MyLocationView on the map - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - myLocationView.setEnabled(enabled); - } - - /** - * Set the foreground drawable of the MyLocationView - * <p> - * The foreground drawable is the image visible on screen - * </p> - * It's linked with the foreground tint color - * - * @param foregroundDrawable the drawable to show as foreground without bearing - * @param foregroundBearingDrawable the drawable to show as foreground when bearing is enabled - */ - public void setForegroundDrawable(Drawable foregroundDrawable, Drawable foregroundBearingDrawable) { - this.foregroundDrawable = foregroundDrawable; - this.foregroundBearingDrawable = foregroundBearingDrawable; - myLocationView.setForegroundDrawables(foregroundDrawable, foregroundBearingDrawable); - myLocationView.setForegroundDrawableTint(foregroundTintColor); - } - - /** - * Get the foreground drawable when bearing is disabled. - * - * @return the drawable used as foreground - */ - public Drawable getForegroundDrawable() { - return foregroundDrawable; - } - - /** - * Get the foreground drawable when bearing is enabled. - * - * @return the bearing drawable used as foreground - */ - public Drawable getForegroundBearingDrawable() { - return foregroundBearingDrawable; - } - - /** - * Set the foreground tint color. - * <p> - * The color will tint both the foreground and the bearing foreground drawable. - * </p> - * - * @param foregroundTintColor the color to tint the foreground drawable or -1 (undefined color) to remove the - * existing foreground tint color - */ - public void setForegroundTintColor(@ColorInt int foregroundTintColor) { - this.foregroundTintColor = foregroundTintColor; - myLocationView.setForegroundDrawableTint(foregroundTintColor); - } - - /** - * Get the foreground tint color. - * - * @return the foreground tint color - */ - public int getForegroundTintColor() { - return foregroundTintColor; - } - - /** - * Set the background drawable of MyLocationView - * <p> - * Padding can be added to provide an offset to the background - * </p> - * It's linked with the background tint color - * - * @param backgroundDrawable the drawable to show as background - * @param padding the padding added to the background - */ - public void setBackgroundDrawable(Drawable backgroundDrawable, int[] padding) { - this.backgroundDrawable = backgroundDrawable; - this.backgroundOffset = padding; - if (padding != null && padding.length == 4) { - myLocationView.setShadowDrawable(backgroundDrawable, padding[0], padding[1], padding[2], padding[3]); - } else { - myLocationView.setShadowDrawable(backgroundDrawable); - } - myLocationView.setShadowDrawableTint(backgroundTintColor); - } - - /** - * Get the background drawable of MyLocationView. - * - * @return the drawable used as background - */ - public Drawable getBackgroundDrawable() { - return backgroundDrawable; - } - - /** - * Set the background tint color. - * - * @param backgroundTintColor the color to tint the background drawable or -1 (undefined color) to remove the - * existing background tint color - */ - public void setBackgroundTintColor(@ColorInt int backgroundTintColor) { - this.backgroundTintColor = backgroundTintColor; - myLocationView.setShadowDrawableTint(backgroundTintColor); - } - - /** - * Get the background tint color. - * - * @return the background tint color - */ - public int getBackgroundTintColor() { - return backgroundTintColor; - } - - /** - * Get the background offset. - * - * @return the background offset - */ - public int[] getBackgroundOffset() { - return backgroundOffset; - } - - /** - * Set the MyLocationView padding. - * - * @param left the padding left of MyLocationView - * @param top the padding top of MyLocationView - * @param right the padding right of MyLocationView - * @param bottom the padding bottom of MyLocaionView - */ - public void setPadding(int left, int top, int right, int bottom) { - padding = new int[] {left, top, right, bottom}; - setPadding(padding); - } - - private void setPadding(int[] padding) { - myLocationView.setContentPadding(padding); - projection.invalidateContentPadding(padding); - invalidateFocalPointForTracking(myLocationView); - } - - /** - * Get the MyLocationView padding. - * - * @return an array describing the padding in a LTRB manner - */ - public int[] getPadding() { - return padding; - } - - /** - * Get the alpha value of the accuracy circle of MyLocationView - * - * @return the alpha value - */ - public int getAccuracyAlpha() { - return accuracyAlpha; - } - - /** - * Set the alpha value of the accuracy circle of MyLocationView - * - * @param accuracyAlpha the alpha value to set - */ - public void setAccuracyAlpha(@IntRange(from = 0, to = 255) int accuracyAlpha) { - this.accuracyAlpha = accuracyAlpha; - myLocationView.setAccuracyAlpha(accuracyAlpha); - } - - /** - * Get the accuracy tint color of MyLocationView. - * - * @return the tint color used for accuracy - */ - public int getAccuracyTintColor() { - return accuracyTintColor; - } - - /** - * Set the accuracy tint color of MyLocationView. - * - * @param accuracyTintColor the accuracy tint color - */ - public void setAccuracyTintColor(@ColorInt int accuracyTintColor) { - this.accuracyTintColor = accuracyTintColor; - myLocationView.setAccuracyTint(accuracyTintColor); - } - - /** - * Returns current accuracy threshold value (in meters). - * - * @return Value of accuracy threshold (in meters), below which circle won't be displayed - */ - public float getAccuracyThreshold() { - return accuracyThreshold; - } - - /** - * Set accuracy circle threshold. Circle won't be displayed if accuracy is below set value. - * - * @param accuracyThreshold Value of accuracy (in meters), below which circle won't be displayed - */ - public void setAccuracyThreshold(float accuracyThreshold) { - this.accuracyThreshold = accuracyThreshold; - myLocationView.setAccuracyThreshold(accuracyThreshold); - } - - public void setTilt(double tilt) { - myLocationView.setTilt(tilt); - } - - private void invalidateFocalPointForTracking(MyLocationView myLocationView) { - if (!(myLocationView.getMyLocationTrackingMode() == MyLocationTracking.TRACKING_NONE)) { - focalPointChangeListener.onFocalPointChanged(myLocationView.getCenter()); - } else { - focalPointChangeListener.onFocalPointChanged(null); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineRegion.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineRegion.java index 987756876b..946d3694d5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineRegion.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineRegion.java @@ -5,7 +5,6 @@ import android.os.Looper; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; - import com.mapbox.mapboxsdk.LibraryLoader; import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.storage.FileSource; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition.java index 2a32f0bdd6..ea9a066df7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/offline/OfflineTilePyramidRegionDefinition.java @@ -10,12 +10,12 @@ 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. + * 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 + * 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. + * pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0. */ public class OfflineTilePyramidRegionDefinition implements OfflineRegionDefinition, Parcelable { diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/snapshotter/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/snapshotter/package-info.java new file mode 100644 index 0000000000..f1ce247ba8 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/snapshotter/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android Snapshotter API classes. + */ +package com.mapbox.mapboxsdk.snapshotter; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/storage/FileSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/storage/FileSource.java index f0cb8d973a..929e4b4279 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/storage/FileSource.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/storage/FileSource.java @@ -6,6 +6,8 @@ import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.os.Environment; import android.support.annotation.NonNull; +import android.support.annotation.UiThread; + import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.constants.MapboxConstants; import timber.log.Timber; @@ -43,6 +45,7 @@ public class FileSource { * @param context the context to derive the cache path from * @return the single instance of FileSource */ + @UiThread public static synchronized FileSource getInstance(Context context) { if (INSTANCE == null) { String cachePath = getCachePath(context); @@ -122,6 +125,8 @@ public class FileSource { initialize(Mapbox.getAccessToken(), cachePath, assetManager); } + public native boolean isActivated(); + public native void activate(); public native void deactivate(); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/Expression.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/Expression.java new file mode 100644 index 0000000000..bd5b40c6ce --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/Expression.java @@ -0,0 +1,3762 @@ +package com.mapbox.mapboxsdk.style.expressions; + +import android.support.annotation.ColorInt; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.Size; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonPrimitive; +import com.mapbox.mapboxsdk.style.layers.PropertyFactory; +import com.mapbox.mapboxsdk.style.layers.PropertyValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * The value for any layout property, paint property, or filter may be specified as an expression. + * An expression defines a formula for computing the value of the property using the operators described below. + * The set of expression operators provided by Mapbox GL includes: + * <ul> + * <li>Element</li> + * <li>Mathematical operators for performing arithmetic and other operations on numeric values</li> + * <li>Logical operators for manipulating boolean values and making conditional decisions</li> + * <li>String operators for manipulating strings</li> + * <li>Data operators, providing access to the properties of source features</li> + * <li>Camera operators, providing access to the parameters defining the current map view</li> + * </ul> + * <p> + * Expressions are represented as JSON arrays. + * The first element of an expression array is a string naming the expression operator, + * e.g. "*"or "case". Subsequent elements (if any) are the arguments to the expression. + * Each argument is either a literal value (a string, number, boolean, or null), or another expression array. + * </p> + * <p> + * Data expression: a data expression is any expression that access feature data -- that is, + * any expression that uses one of the data operators:get,has,id,geometry-type, or properties. + * Data expressions allow a feature's properties to determine its appearance. + * They can be used to differentiate features within the same layer and to create data visualizations. + * </p> + * <p> + * Camera expression: a camera expression is any expression that uses the zoom operator. + * Such expressions allow the the appearance of a layer to change with the map's zoom level. + * Camera expressions can be used to create the appearance of depth and to control data density. + * </p> + * <p> + * Composition: a single expression may use a mix of data operators, camera operators, and other operators. + * Such composite expressions allows a layer's appearance to be determined by + * a combination of the zoom level and individual feature properties. + * </p> + * <p> + * Example expression: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( linear(), zoom(), + * stop(12, step(get("stroke-width"), + * color(Color.BLACK), + * stop(1f, color(Color.RED)), + * stop(2f, color(Color.WHITE)), + * stop(3f, color(Color.BLUE)) + * )), + * stop(15, step(get("stroke-width"), + * color(Color.BLACK), + * stop(1f, color(Color.YELLOW)), + * stop(2f, color(Color.LTGRAY)), + * stop(3f, color(Color.CYAN)) + * )), + * stop(18, step(get("stroke-width"), + * color(Color.BLACK), + * stop(1f, color(Color.WHITE)), + * stop(2f, color(Color.GRAY)), + * stop(3f, color(Color.GREEN)) + * )) + * ) + * ) + * ) + * } + * </pre> + */ +public class Expression { + + private final String operator; + private final Expression[] arguments; + + /** + * Creates an empty expression for expression literals + */ + Expression() { + operator = null; + arguments = null; + } + + /** + * Creates an expression from its operator and varargs expressions. + * + * @param operator the expression operator + * @param arguments expressions input + */ + public Expression(@NonNull String operator, @Nullable Expression... arguments) { + this.operator = operator; + this.arguments = arguments; + } + + /** + * Create a literal number expression. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(literal(10.0f)) + * ); + * } + * </pre> + * + * @param number the number + * @return the expression + */ + public static Expression literal(@NonNull Number number) { + return new ExpressionLiteral(number); + } + + /** + * Create a literal string expression. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(literal("Text")) + * ); + * } + * </pre> + * + * @param string the string + * @return the expression + */ + public static Expression literal(@NonNull String string) { + return new ExpressionLiteral(string); + } + + /** + * Create a literal boolean expression. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillAntialias(literal(true)) + * ); + * } + * </pre> + * + * @param bool the boolean + * @return the expression + */ + public static Expression literal(boolean bool) { + return new ExpressionLiteral(bool); + } + + /** + * Create a literal object expression. + * + * @param object the object + * @return the expression + */ + public static Expression literal(@NonNull Object object) { + if (object.getClass().isArray()) { + return literal(ExpressionArray.toObjectArray(object)); + } + return new ExpressionLiteral(object); + } + + /** + * Create a literal array expression + * + * @param array the array + * @return the expression + */ + public static Expression literal(@NonNull Object[] array) { + return new ExpressionArray(array); + } + + /** + * Expression literal utility method to convert a color int to an color expression + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor(color(Color.GREEN)) + * ); + * } + * </pre> + * + * @param color the int color + * @return the color expression + */ + public static Expression color(@ColorInt int color) { + return toColor(literal(PropertyFactory.colorToRgbaString(color))); + } + + /** + * Creates a color value from red, green, and blue components, which must range between 0 and 255, + * and an alpha component of 1. + * <p> + * If any component is out of range, the expression is an error. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * rgb( + * literal(255.0f), + * literal(255.0f), + * literal(255.0f) + * ) + * ) + * ); + * } + * </pre> + * + * @param red red color expression + * @param green green color expression + * @param blue blue color expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-rgb">Style specification</a> + */ + public static Expression rgb(@NonNull Expression red, @NonNull Expression green, @NonNull Expression blue) { + return new Expression("rgb", red, green, blue); + } + + /** + * Creates a color value from red, green, and blue components, which must range between 0 and 255, + * and an alpha component of 1. + * <p> + * If any component is out of range, the expression is an error. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * rgb(255.0f, 255.0f, 255.0f) + * ) + * ); + * } + * </pre> + * + * @param red red color value + * @param green green color value + * @param blue blue color value + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-rgb">Style specification</a> + */ + public static Expression rgb(@NonNull Number red, @NonNull Number green, @NonNull Number blue) { + return rgb(literal(red), literal(green), literal(blue)); + } + + /** + * Creates a color value from red, green, blue components, which must range between 0 and 255, + * and an alpha component which must range between 0 and 1. + * <p> + * If any component is out of range, the expression is an error. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * rgba( + * literal(255.0f), + * literal(255.0f), + * literal(255.0f), + * literal(1.0f) + * ) + * ) + * ); + * } + * </pre> + * + * @param red red color value + * @param green green color value + * @param blue blue color value + * @param alpha alpha color value + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-rgba">Style specification</a> + */ + public static Expression rgba(@NonNull Expression red, @NonNull Expression green, + @NonNull Expression blue, @NonNull Expression alpha) { + return new Expression("rgba", red, green, blue, alpha); + } + + /** + * Creates a color value from red, green, blue components, which must range between 0 and 255, + * and an alpha component which must range between 0 and 1. + * <p> + * If any component is out of range, the expression is an error. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * rgb(255.0f, 255.0f, 255.0f, 1.0f) + * ) + * ); + * } + * </pre> + * + * @param red red color value + * @param green green color value + * @param blue blue color value + * @param alpha alpha color value + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-rgba">Style specification</a> + */ + public static Expression rgba(@NonNull Number red, @NonNull Number green, @NonNull Number blue, @NonNull Number alpha) { + return rgba(literal(red), literal(green), literal(blue), literal(alpha)); + } + + /** + * Returns a four-element array containing the input color's red, green, blue, and alpha components, in that order. + * + * @param expression an expression to convert to a color + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-to-rgba">Style specification</a> + */ + public static Expression toRgba(@NonNull Expression expression) { + return new Expression("to-rgba", expression); + } + + /** + * Returns true if the input values are equal, false otherwise. + * The inputs must be numbers, strings, or booleans, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * eq(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-==">Style specification</a> + */ + public static Expression eq(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression("==", compareOne, compareTwo); + } + + /** + * Returns true if the input values are equal, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * eq(get("keyToValue"), true) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second boolean + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-==">Style specification</a> + */ + public static Expression eq(Expression compareOne, boolean compareTwo) { + return eq(compareOne, literal(compareTwo)); + } + + /** + * Returns true if the input values are equal, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * eq(get("keyToValue"), "value") + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-==">Style specification</a> + */ + public static Expression eq(@NonNull Expression compareOne, @NonNull String compareTwo) { + return eq(literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the input values are equal, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * eq(get("keyToValue"), 2.0f) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-==">Style specification</a> + */ + public static Expression eq(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return eq(literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the input values are not equal, false otherwise. + * The inputs must be numbers, strings, or booleans, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * neq(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!=">Style specification</a> + */ + public static Expression neq(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression("!=", compareOne, compareTwo); + } + + /** + * Returns true if the input values are equal, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * neq(get("keyToValue"), true) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second boolean + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!=">Style specification</a> + */ + public static Expression neq(Expression compareOne, boolean compareTwo) { + return new Expression("!=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns `true` if the input values are not equal, `false` otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * neq(get("keyToValue"), "value")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!=">Style specification</a> + */ + public static Expression neq(@NonNull Expression compareOne, @NonNull String compareTwo) { + return new Expression("!=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns `true` if the input values are not equal, `false` otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * neq(get("keyToValue"), 2.0f)) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!=">Style specification</a> + */ + public static Expression neq(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return new Expression("!=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is strictly greater than the second, false otherwise. + * The inputs must be numbers or strings, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * gt(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E">Style specification</a> + */ + public static Expression gt(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression(">", compareOne, compareTwo); + } + + /** + * Returns true if the first input is strictly greater than the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * gt(get("keyToValue"), 2.0f) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E">Style specification</a> + */ + public static Expression gt(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return new Expression(">", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is strictly greater than the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * gt(get("keyToValue"), "value") + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E">Style specification</a> + */ + public static Expression gt(@NonNull Expression compareOne, @NonNull String compareTwo) { + return new Expression(">", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is strictly less than the second, false otherwise. + * The inputs must be numbers or strings, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lt(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C">Style specification</a> + */ + public static Expression lt(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression("<", compareOne, compareTwo); + } + + /** + * Returns true if the first input is strictly less than the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lt(get("keyToValue"), 2.0f) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C">Style specification</a> + */ + public static Expression lt(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return new Expression("<", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is strictly less than the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lt(get("keyToValue"), "value")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C">Style specification</a> + */ + public static Expression lt(@NonNull Expression compareOne, @NonNull String compareTwo) { + return new Expression("<", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is greater than or equal to the second, false otherwise. + * The inputs must be numbers or strings, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * gte(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E%3D">Style specification</a> + */ + public static Expression gte(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression(">=", compareOne, compareTwo); + } + + /** + * Returns true if the first input is greater than or equal to the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * gte(get("keyToValue"), 2.0f) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E%3D">Style specification</a> + */ + public static Expression gte(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return new Expression(">=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is greater than or equal to the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * neq(get("keyToValue"), "value") + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3E%3D">Style specification</a> + */ + public static Expression gte(@NonNull Expression compareOne, @NonNull String compareTwo) { + return new Expression(">=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is less than or equal to the second, false otherwise. + * The inputs must be numbers or strings, and both of the same type. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lte(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C%3D">Style specification</a> + */ + public static Expression lte(@NonNull Expression compareOne, @NonNull Expression compareTwo) { + return new Expression("<=", compareOne, compareTwo); + } + + /** + * Returns true if the first input is less than or equal to the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lte(get("keyToValue"), 2.0f) + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C%3D">Style specification</a> + */ + public static Expression lte(@NonNull Expression compareOne, @NonNull Number compareTwo) { + return new Expression("<=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns true if the first input is less than or equal to the second, false otherwise. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * lte(get("keyToValue"), "value") + * ); + * } + * </pre> + * + * @param compareOne the first expression + * @param compareTwo the second string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%3C%3D">Style specification</a> + */ + public static Expression lte(@NonNull Expression compareOne, @NonNull String compareTwo) { + return new Expression("<=", literal(compareOne), literal(compareTwo)); + } + + /** + * Returns `true` if all the inputs are `true`, `false` otherwise. + * <p> + * The inputs are evaluated in order, and evaluation is short-circuiting: + * once an input expression evaluates to `false`, + * the result is `false` and no further input expressions are evaluated. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * all(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-all">Style specification</a> + */ + public static Expression all(@NonNull Expression... input) { + return new Expression("all", input); + } + + /** + * Returns `true` if any of the inputs are `true`, `false` otherwise. + * <p> + * The inputs are evaluated in order, and evaluation is short-circuiting: + * once an input expression evaluates to `true`, + * the result is `true` and no further input expressions are evaluated. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * any(get("keyToValue"), get("keyToOtherValue")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-any">Style specification</a> + */ + public static Expression any(@NonNull Expression... input) { + return new Expression("any", input); + } + + /** + * Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * not(get("keyToValue")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!">Style specification</a> + */ + public static Expression not(@NonNull Expression input) { + return new Expression("!", input); + } + + /** + * Logical negation. Returns `true` if the input is `false`, and `false` if the input is `true`. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * not(false) + * ); + * } + * </pre> + * + * @param input boolean input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-!">Style specification</a> + */ + public static Expression not(boolean input) { + return not(literal(input)); + } + + /** + * Selects the first output whose corresponding test condition evaluates to true. + * <p> + * For each case a condition and an output should be provided. + * The last parameter should provide the default output. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * iconSize( + * switchCase( + * get(KEY_TO_BOOLEAN), literal(3.0f), + * get(KEY_TO_OTHER_BOOLEAN), literal(5.0f) + * literal(1.0f) // default value + * ) + * ) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-case">Style specification</a> + */ + public static Expression switchCase(@NonNull @Size(min = 1) Expression... input) { + return new Expression("case", input); + } + + /** + * Selects the output whose label value matches the input value, or the fallback value if no match is found. + * The `input` can be any string or number expression. + * Each label can either be a single literal value or an array of values. + * If types of the input and keys don't match, or the input value doesn't exist, + * the expresion will fail without falling back to the default value. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textColor( + * match(get("keyToValue"), + * literal(1), rgba(255, 0, 0, 1.0f), + * literal(2), rgba(0, 0, 255.0f, 1.0f), + * rgba(0.0f, 255.0f, 0.0f, 1.0f) + * ); + * ) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-match">Style specification</a> + */ + public static Expression match(@NonNull @Size(min = 2) Expression... input) { + return new Expression("match", input); + } + + /** + * Selects the output whose label value matches the input value, or the fallback value if no match is found. + * The `input` can be any string or number expression. + * Each label can either be a single literal value or an array of values. + * If types of the input and keys don't match, or the input value doesn't exist, + * the expresion will fail without falling back to the default value. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textColor( + * match(get("keyToValue"), + * literal(1), rgba(255, 0, 0, 1.0f), + * literal(2), rgba(0, 0, 255.0f, 1.0f), + * rgba(0.0f, 255.0f, 0.0f, 1.0f) + * ); + * ) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-match">Style specification</a> + */ + public static Expression match(@NonNull Expression input, @NonNull Expression defaultOutput, @NonNull Stop... stops) { + Expression[] expressionStops = new Expression[stops.length * 2]; + for (int i = 0; i < stops.length; i++) { + expressionStops[i * 2] = literal(stops[i].value); + expressionStops[i * 2 + 1] = literal(stops[i].output); + } + return match(join(join(new Expression[] {input}, expressionStops), new Expression[] {defaultOutput})); + } + + /** + * Evaluates each expression in turn until the first non-null value is obtained, and returns that value. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textColor( + * coalesce( + * get("keyToNullValue"), + * get("keyToNonNullValue") + * ); + * ) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-coalesce">Style specification</a> + */ + public static Expression coalesce(@NonNull Expression... input) { + return new Expression("coalesce", input); + } + + /** + * Gets the feature properties object. + * <p> + * Note that in some cases, it may be more efficient to use {@link #get(Expression)}} instead. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(get("key-to-value", properties()))) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-properties">Style specification</a> + */ + public static Expression properties() { + return new Expression("properties"); + } + + /** + * Gets the feature's geometry type: Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(concat(get("key-to-value"), literal(" "), geometryType()) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-geometry-types">Style specification</a> + */ + public static Expression geometryType() { + return new Expression("geometry-type"); + } + + /** + * Gets the feature's id, if it has one. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(id()) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-id">Style specification</a> + */ + public static Expression id() { + return new Expression("id"); + } + + /** + * Gets the kernel density estimation of a pixel in a heatmap layer, + * which is a relative measure of how many data points are crowded around a particular pixel. + * Can only be used in the `heatmap-color` property. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * HeatmapLayer layer = new HeatmapLayer("layer-id", "source-id"); + * layer.setProperties( + * heatmapColor(interpolate(linear(), heatmapDensity(), + * literal(0), rgba(33, 102, 172, 0), + * literal(0.2), rgb(103, 169, 207), + * literal(0.4), rgb(209, 229, 240), + * literal(0.6), rgb(253, 219, 199), + * literal(0.8), rgb(239, 138, 98), + * literal(1), rgb(178, 24, 43) + * ) + * ) + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-heatmap-density">Style specification</a> + */ + public static Expression heatmapDensity() { + return new Expression("heatmap-density"); + } + + /** + * Retrieves an item from an array. + * + * @param number the index expression + * @param expression the array expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-at">Style specification</a> + */ + public static Expression at(@NonNull Expression number, @NonNull Expression expression) { + return new Expression("at", number, expression); + } + + /** + * Retrieves an item from an array. + * + * @param number the index expression + * @param expression the array expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-at">Style specification</a> + */ + public static Expression at(@NonNull Number number, @NonNull Expression expression) { + return at(literal(number), expression); + } + + /** + * Retrieves a property value from the current feature's properties, + * or from another object if a second argument is provided. + * Returns null if the requested property is missing. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(get("key-to-feature")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-get">Style specification</a> + */ + public static Expression get(@NonNull Expression input) { + return new Expression("get", input); + } + + /** + * Retrieves a property value from the current feature's properties, + * or from another object if a second argument is provided. + * Returns null if the requested property is missing. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(get("key-to-feature")) + * ); + * } + * </pre> + * + * @param input string input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-get">Style specification</a> + */ + public static Expression get(@NonNull String input) { + return get(literal(input)); + } + + /** + * Retrieves a property value from another object. + * Returns null if the requested property is missing. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(get("key-to-property", get("key-to-object"))) + * ); + * } + * </pre> + * + * @param key a property value key + * @param object an expression object + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-get">Style specification</a> + */ + public static Expression get(@NonNull Expression key, @NonNull Expression object) { + return new Expression("get", key, object); + } + + /** + * Retrieves a property value from another object. + * Returns null if the requested property is missing. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(get("key-to-property", get("key-to-object"))) + * ); + * } + * </pre> + * + * @param key a property value key + * @param object an expression object + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-get">Style specification</a> + */ + public static Expression get(@NonNull String key, @NonNull Expression object) { + return get(literal(key), object); + } + + /** + * Tests for the presence of an property value in the current feature's properties. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * has(get("keyToValue")) + * ); + * } + * </pre> + * + * @param key the expression property value key + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-has">Style specification</a> + */ + public static Expression has(@NonNull Expression key) { + return new Expression("has", key); + } + + /** + * Tests for the presence of an property value in the current feature's properties. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * has("keyToValue") + * ); + * } + * </pre> + * + * @param key the property value key + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-has">Style specification</a> + */ + public static Expression has(@NonNull String key) { + return has(literal(key)); + } + + /** + * Tests for the presence of an property value from another object. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * has(get("keyToValue"), get("keyToObject")) + * ); + * } + * </pre> + * + * @param key the expression property value key + * @param object an expression object + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-has">Style specification</a> + */ + public static Expression has(@NonNull Expression key, @NonNull Expression object) { + return new Expression("has", key, object); + } + + /** + * Tests for the presence of an property value from another object. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setFilter( + * has("keyToValue", get("keyToObject)) + * ); + * } + * </pre> + * + * @param key the property value key + * @param object an expression object + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-has">Style specification</a> + */ + public static Expression has(@NonNull String key, @NonNull Expression object) { + return has(literal(key), object); + } + + /** + * Gets the length of an array or string. + * + * @param expression an expression object or expression string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-lenght">Style specification</a> + */ + public static Expression length(@NonNull Expression expression) { + return new Expression("length", expression); + } + + /** + * Gets the length of an array or string. + * + * @param input a string + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-lenght">Style specification</a> + */ + public static Expression length(@NonNull String input) { + return length(literal(input)); + } + + /** + * Returns mathematical constant ln(2). + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(product(literal(10.0f), ln2()))) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-ln2">Style specification</a> + */ + public static Expression ln2() { + return new Expression("ln2"); + } + + /** + * Returns the mathematical constant pi. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(product(literal(10.0f), pi()))) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-pi">Style specification</a> + */ + public static Expression pi() { + return new Expression("pi"); + } + + /** + * Returns the mathematical constant e. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(product(literal(10.0f), e()))) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-e">Style specification</a> + */ + public static Expression e() { + return new Expression("e"); + } + + /** + * Returns the sum of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sum(literal(10.0f), ln2(), pi()))) + * ); + * } + * </pre> + * + * @param numbers the numbers to calculate the sum for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-+">Style specification</a> + */ + public static Expression sum(@Size(min = 2) Expression... numbers) { + return new Expression("+", numbers); + } + + /** + * Returns the sum of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sum(10.0f, 5.0f, 3.0f))) + * ); + * } + * </pre> + * + * @param numbers the numbers to calculate the sum for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-+">Style specification</a> + */ + public static Expression sum(@Size(min = 2) Number... numbers) { + Expression[] numberExpression = new Expression[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + numberExpression[i] = literal(numbers[i]); + } + return sum(numberExpression); + } + + /** + * Returns the product of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(product(literal(10.0f), ln2()))) + * ); + * } + * </pre> + * + * @param numbers the numbers to calculate the product for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-*">Style specification</a> + */ + public static Expression product(@Size(min = 2) Expression... numbers) { + return new Expression("*", numbers); + } + + /** + * Returns the product of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(product(10.0f, 2.0f))) + * ); + * } + * </pre> + * + * @param numbers the numbers to calculate the product for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-*">Style specification</a> + */ + public static Expression product(@Size(min = 2) Number... numbers) { + Expression[] numberExpression = new Expression[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + numberExpression[i] = literal(numbers[i]); + } + return product(numberExpression); + } + + /** + * Returns the result of subtracting a number from 0. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(subtract(pi())) + * ); + * } + * </pre> + * + * @param number the number subtract from 0 + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions--">Style specification</a> + */ + public static Expression subtract(@NonNull Expression number) { + return new Expression("-", number); + } + + /** + * Returns the result of subtracting a number from 0. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(subtract(10.0f)) + * ); + * } + * </pre> + * + * @param number the number subtract from 0 + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions--">Style specification</a> + */ + public static Expression subtract(@NonNull Number number) { + return subtract(literal(number)); + } + + /** + * Returns the result of subtracting the second input from the first. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(subtract(literal(10.0f), pi()))) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions--">Style specification</a> + */ + public static Expression subtract(@NonNull Expression first, @NonNull Expression second) { + return new Expression("-", first, second); + } + + /** + * Returns the result of subtracting the second input from the first. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(subtract(10.0f, 20.0f))) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions--">Style specification</a> + */ + public static Expression subtract(@NonNull Number first, @NonNull Number second) { + return subtract(literal(first), literal(second)); + } + + /** + * Returns the result of floating point division of the first input by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(division(literal(10.0f), pi()))) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-/">Style specification</a> + */ + public static Expression division(@NonNull Expression first, @NonNull Expression second) { + return new Expression("/", first, second); + } + + /** + * Returns the result of floating point division of the first input by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(division(10.0f, 20.0f))) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-/">Style specification</a> + */ + public static Expression division(@NonNull Number first, @NonNull Number second) { + return division(literal(first), literal(second)); + } + + /** + * Returns the remainder after integer division of the first input by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(mod(literal(10.0f), pi())) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%25">Style specification</a> + */ + public static Expression mod(@NonNull Expression first, @NonNull Expression second) { + return new Expression("%", first, second); + } + + /** + * Returns the remainder after integer division of the first input by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(mod(10.0f, 10.0f)) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%25">Style specification</a> + */ + public static Expression mod(@NonNull Number first, @NonNull Number second) { + return mod(literal(first), literal(second)); + } + + /** + * Returns the result of raising the first input to the power specified by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(pow(pi(), literal(2.0f)) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%5E">Style specification</a> + */ + public static Expression pow(@NonNull Expression first, @NonNull Expression second) { + return new Expression("^", first, second); + } + + /** + * Returns the result of raising the first input to the power specified by the second. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(pow(5.0f, 2.0f)) + * ); + * } + * </pre> + * + * @param first the first number + * @param second the second number + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-%5E">Style specification</a> + */ + public static Expression pow(@NonNull Number first, @NonNull Number second) { + return pow(literal(first), literal(second)); + } + + /** + * Returns the square root of the input + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sqrt(pi())) + * ); + * } + * </pre> + * + * @param number the number to take the square root from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-sqrt">Style specification</a> + */ + public static Expression sqrt(@NonNull Expression number) { + return new Expression("sqrt", number); + } + + /** + * Returns the square root of the input + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sqrt(25.0f)) + * ); + * } + * </pre> + * + * @param number the number to take the square root from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-sqrt">Style specification</a> + */ + public static Expression sqrt(@NonNull Number number) { + return sqrt(literal(number)); + } + + /** + * Returns the base-ten logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(log10(pi())) + * ); + * } + * </pre> + * + * @param number the number to take base-ten logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-log10">Style specification</a> + */ + public static Expression log10(@NonNull Expression number) { + return new Expression("log10", number); + } + + /** + * Returns the base-ten logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(log10(10)) + * ); + * } + * </pre> + * + * @param number the number to take base-ten logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-log10">Style specification</a> + */ + public static Expression log10(@NonNull Number number) { + return log10(literal(number)); + } + + /** + * Returns the natural logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(ln(pi())) + * ); + * } + * </pre> + * + * @param number the number to take natural logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-ln">Style specification</a> + */ + public static Expression ln(Expression number) { + return new Expression("ln", number); + } + + /** + * Returns the natural logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(ln(10)) + * ); + * } + * </pre> + * + * @param number the number to take natural logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-ln">Style specification</a> + */ + public static Expression ln(Number number) { + return ln(literal(number)); + } + + /** + * Returns the base-two logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(log2(pi())) + * ); + * } + * </pre> + * + * @param number the number to take base-two logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-log2">Style specification</a> + */ + public static Expression log2(@NonNull Expression number) { + return new Expression("log2", number); + } + + /** + * Returns the base-two logarithm of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(log2(2)) + * ); + * } + * </pre> + * + * @param number the number to take base-two logarithm from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-log2">Style specification</a> + */ + public static Expression log2(@NonNull Number number) { + return log2(literal(number)); + } + + /** + * Returns the sine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sin(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the sine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-sin">Style specification</a> + */ + public static Expression sin(@NonNull Expression number) { + return new Expression("sin", number); + } + + /** + * Returns the sine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(sin(90.0f)) + * ); + * } + * </pre> + * + * @param number the number to calculate the sine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-sin">Style specification</a> + */ + public static Expression sin(@NonNull Number number) { + return sin(literal(number)); + } + + /** + * Returns the cosine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(cos(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the cosine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-cos">Style specification</a> + */ + public static Expression cos(@NonNull Expression number) { + return new Expression("cos", number); + } + + /** + * Returns the cosine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(cos(0))) + * ); + * } + * </pre> + * + * @param number the number to calculate the cosine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-cos">Style specification</a> + */ + public static Expression cos(@NonNull Number number) { + return new Expression("cos", literal(number)); + } + + /** + * Returns the tangent of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(tan(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the tangent for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-tan">Style specification</a> + */ + public static Expression tan(@NonNull Expression number) { + return new Expression("tan", number); + } + + /** + * Returns the tangent of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(tan(45.0f)) + * ); + * } + * </pre> + * + * @param number the number to calculate the tangent for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-tan">Style specification</a> + */ + public static Expression tan(@NonNull Number number) { + return new Expression("tan", literal(number)); + } + + /** + * Returns the arcsine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(asin(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the arcsine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-asin">Style specification</a> + */ + public static Expression asin(@NonNull Expression number) { + return new Expression("asin", number); + } + + /** + * Returns the arcsine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(asin(90)) + * ); + * } + * </pre> + * + * @param number the number to calculate the arcsine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-asin">Style specification</a> + */ + public static Expression asin(@NonNull Number number) { + return asin(literal(number)); + } + + /** + * Returns the arccosine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(acos(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the arccosine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-acos">Style specification</a> + */ + public static Expression acos(@NonNull Expression number) { + return new Expression("acos", number); + } + + /** + * Returns the arccosine of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(acos(0)) + * ); + * } + * </pre> + * + * @param number the number to calculate the arccosine for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-acos">Style specification</a> + */ + public static Expression acos(@NonNull Number number) { + return acos(literal(number)); + } + + /** + * Returns the arctangent of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(asin(pi())) + * ); + * } + * </pre> + * + * @param number the number to calculate the arctangent for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-atan">Style specification</a> + */ + public static Expression atan(@NonNull Expression number) { + return new Expression("atan", number); + } + + /** + * Returns the arctangent of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(atan(90)) + * ); + * } + * </pre> + * + * @param number the number to calculate the arctangent for + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-atan">Style specification</a> + */ + public static Expression atan(@NonNull Number number) { + return atan(literal(number)); + } + + /** + * Returns the minimum value of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(min(pi(), literal(3.14f), literal(3.15f)) + * ); + * } + * </pre> + * + * @param numbers varargs of numbers to get the minimum from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-min">Style specification</a> + */ + public static Expression min(@Size(min = 1) Expression... numbers) { + return new Expression("min", numbers); + } + + /** + * Returns the minimum value of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(min(3.141, 3.14f, 3.15f)) + * ); + * } + * </pre> + * + * @param numbers varargs of numbers to get the minimum from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-min">Style specification</a> + */ + public static Expression min(@Size(min = 1) Number... numbers) { + Expression[] numberExpression = new Expression[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + numberExpression[i] = literal(numbers[i]); + } + return min(numberExpression); + } + + /** + * Returns the maximum value of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(max(pi(), 3.14f, 3.15f)) + * ); + * } + * </pre> + * + * @param numbers varargs of numbers to get the maximum from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-max">Style specification</a> + */ + public static Expression max(@Size(min = 1) Expression... numbers) { + return new Expression("max", numbers); + } + + /** + * Returns the maximum value of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(max(3.141, 3.14f, 3.15f)) + * ); + * } + * </pre> + * + * @param numbers varargs of numbers to get the maximum from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-max">Style specification</a> + */ + public static Expression max(@Size(min = 1) Number... numbers) { + Expression[] numberExpression = new Expression[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + numberExpression[i] = literal(numbers[i]); + } + return max(numberExpression); + } + + /** + * Rounds the input to the nearest integer. + * Halfway values are rounded away from zero. + * For example `[\"round\", -1.5]` evaluates to -2. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(round(pi())) + * ); + * } + * </pre> + * + * @param expression number expression to round + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-round">Style specification</a> + */ + public static Expression round(Expression expression) { + return new Expression("round", expression); + } + + /** + * Rounds the input to the nearest integer. + * Halfway values are rounded away from zero. + * For example `[\"round\", -1.5]` evaluates to -2. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(round(3.14159265359f)) + * ); + * } + * </pre> + * + * @param number number to round + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-round">Style specification</a> + */ + public static Expression round(Number number) { + return round(literal(number)); + } + + /** + * Returns the absolute value of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(abs(subtract(pi()))) + * ); + * } + * </pre> + * + * @param expression number expression to get absolute value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression abs(Expression expression) { + return new Expression("abs", expression); + } + + /** + * Returns the absolute value of the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(abs(-3.14159265359f)) + * ); + * } + * </pre> + * + * @param number number to get absolute value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression abs(Number number) { + return abs(literal(number)); + } + + /** + * Returns the smallest integer that is greater than or equal to the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(ceil(pi())) + * ); + * } + * </pre> + * + * @param expression number expression to get value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression ceil(Expression expression) { + return new Expression("ceil", expression); + } + + /** + * Returns the smallest integer that is greater than or equal to the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(ceil(3.14159265359)) + * ); + * } + * </pre> + * @param number number to get value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression ceil(Number number) { + return ceil(literal(number)); + } + + /** + * Returns the largest integer that is less than or equal to the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(floor(pi())) + * ); + * } + * </pre> + * + * @param expression number expression to get value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression floor(Expression expression) { + return new Expression("floor", expression); + } + + /** + * Returns the largest integer that is less than or equal to the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(floor(pi())) + * ); + * } + * </pre> + * + * @param number number to get value from + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-abs">Style specification</a> + */ + public static Expression floor(Number number) { + return floor(literal(number)); + } + + /** + * Returns the input string converted to uppercase. + * <p> + * Follows the Unicode Default Case Conversion algorithm + * and the locale-insensitive case mappings in the Unicode Character Database. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(upcase(get("key-to-string-value")) + * ); + * } + * </pre> + * + * @param string the string to upcase + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-upcase">Style specification</a> + */ + public static Expression upcase(@NonNull Expression string) { + return new Expression("upcase", string); + } + + /** + * Returns the input string converted to uppercase. + * <p> + * Follows the Unicode Default Case Conversion algorithm + * and the locale-insensitive case mappings in the Unicode Character Database. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(upcase("text")) + * ); + * } + * </pre> + * + * @param string string to upcase + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-upcase">Style specification</a> + */ + public static Expression upcase(@NonNull String string) { + return upcase(literal(string)); + } + + /** + * Returns the input string converted to lowercase. + * <p> + * Follows the Unicode Default Case Conversion algorithm + * and the locale-insensitive case mappings in the Unicode Character Database. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(downcase(get("key-to-string-value")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-downcase">Style specification</a> + */ + public static Expression downcase(@NonNull Expression input) { + return new Expression("downcase", input); + } + + /** + * Returns the input string converted to lowercase. + * <p> + * Follows the Unicode Default Case Conversion algorithm + * and the locale-insensitive case mappings in the Unicode Character Database. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(upcase("key-to-string-value") + * ); + * } + * </pre> + * + * @param input string to downcase + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-downcase">Style specification</a> + */ + public static Expression downcase(@NonNull String input) { + return downcase(literal(input)); + } + + /** + * Returns a string consisting of the concatenation of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(concat(get("key-to-string-value"), literal("other string")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-concat">Style specification</a> + */ + public static Expression concat(@NonNull Expression... input) { + return new Expression("concat", input); + } + + /** + * Returns a string consisting of the concatenation of the inputs. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(concat("foo", "bar")) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-concat">Style specification</a> + */ + public static Expression concat(@NonNull String... input) { + Expression[] stringExpression = new Expression[input.length]; + for (int i = 0; i < input.length; i++) { + stringExpression[i] = literal(input[i]); + } + return concat(stringExpression); + } + + /** + * Asserts that the input is an array (optionally with a specific item type and length). + * If, when the input expression is evaluated, it is not of the asserted type, + * then this assertion will cause the whole expression to be aborted. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-array">Style specification</a> + */ + public static Expression array(@NonNull Expression input) { + return new Expression("array", input); + } + + /** + * Returns a string describing the type of the given value. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-typeof">Style specification</a> + */ + public static Expression typeOf(@NonNull Expression input) { + return new Expression("typeof", input); + } + + /** + * Asserts that the input value is a string. + * If multiple values are provided, each one is evaluated in order until a string value is obtained. + * If none of the inputs are strings, the expression is an error. + * The asserted input value is returned as result. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-string">Style specification</a> + */ + public static Expression string(@NonNull Expression... input) { + return new Expression("string", input); + } + + /** + * Asserts that the input value is a number. + * If multiple values are provided, each one is evaluated in order until a number value is obtained. + * If none of the inputs are numbers, the expression is an error. + * The asserted input value is returned as result. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-number">Style specification</a> + */ + public static Expression number(@NonNull Expression... input) { + return new Expression("number", input); + } + + /** + * Asserts that the input value is a boolean. + * If multiple values are provided, each one is evaluated in order until a boolean value is obtained. + * If none of the inputs are booleans, the expression is an error. + * The asserted input value is returned as result. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-boolean">Style specification</a> + */ + public static Expression bool(@NonNull Expression... input) { + return new Expression("boolean", input); + } + + /** + * Asserts that the input value is an object. If it is not, the expression is an error + * The asserted input value is returned as result. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-object">Style specification</a> + */ + public static Expression object(@NonNull Expression input) { + return new Expression("object", input); + } + + /** + * Converts the input value to a string. + * If the input is null, the result is null. + * If the input is a boolean, the result is true or false. + * If the input is a number, it is converted to a string by NumberToString in the ECMAScript Language Specification. + * If the input is a color, it is converted to a string of the form "rgba(r,g,b,a)", + * where `r`, `g`, and `b` are numerals ranging from 0 to 255, and `a` ranges from 0 to 1. + * Otherwise, the input is converted to a string in the format specified by the JSON.stringify in the ECMAScript + * Language Specification. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id"); + * symbolLayer.setProperties( + * textField(toString(get("key-to-number-value"))) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-to-string">Style specification</a> + */ + public static Expression toString(@NonNull Expression input) { + return new Expression("to-string", input); + } + + /** + * Converts the input value to a number, if possible. + * If the input is null or false, the result is 0. + * If the input is true, the result is 1. + * If the input is a string, it is converted to a number as specified by the ECMAScript Language Specification. + * If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. + * If none of the inputs can be converted, the expression is an error. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(toNumber(get("key-to-string-value"))) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-to-number">Style specification</a> + */ + public static Expression toNumber(@NonNull Expression input) { + return new Expression("to-number", input); + } + + /** + * Converts the input value to a boolean. The result is `false` when then input is an empty string, 0, false, + * null, or NaN; otherwise it is true. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius(toBool(get("key-to-value")); + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-to-boolean">Style specification</a> + */ + public static Expression toBool(@NonNull Expression input) { + return new Expression("to-boolean", input); + } + + /** + * Converts the input value to a color. If multiple values are provided, + * each one is evaluated in order until the first successful conversion is obtained. + * If none of the inputs can be converted, the expression is an error. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new FillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor(toColor(get("keyStringValue"))) + * ); + * } + * </pre> + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-to-color">Style specification</a> + */ + public static Expression toColor(@NonNull Expression input) { + return new Expression("to-color", input); + } + + /** + * Binds input to named variables, + * which can then be referenced in the result expression using {@link #var(String)} or {@link #var(Expression)}. + * + * @param input expression input + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-let">Style specification</a> + */ + public static Expression let(@Size(min = 1) Expression... input) { + return new Expression("let", input); + } + + /** + * References variable bound using let. + * + * @param expression the variable naming expression that was bound with using let + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-var">Style specification</a> + */ + public static Expression var(@NonNull Expression expression) { + return new Expression("var", expression); + } + + /** + * References variable bound using let. + * + * @param variableName the variable naming that was bound with using let + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-var">Style specification</a> + */ + public static Expression var(@NonNull String variableName) { + return var(literal(variableName)); + } + + /** + * Gets the current zoom level. + * <p> + * Note that in style layout and paint properties, + * zoom may only appear as the input to a top-level step or interpolate expression. + * </p> + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * exponential(0.5f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-zoom">Style specification</a> + */ + public static Expression zoom() { + return new Expression("zoom"); + } + + /** + * Produces a stop value to be used as part of the step expression. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), literal(0.0f), + * stop(1.0f, 2.5f), + * stop(10.0f, 5.0f) + * ) + * ); + * } + * </pre> + * + * @param stop the stop input + * @param value the stop output + * @return the stop + */ + public static Stop stop(@NonNull Object stop, @NonNull Object value) { + return new Stop(stop, value); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), literal(0.0f), + * literal(1.0f), literal(2.5f), + * literal(10.0f), literal(5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Number input, @NonNull Expression defaultOutput, Expression... stops) { + return step(literal(input), defaultOutput, stops); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), literal(0.0f), + * literal(1.0f), literal(2.5f), + * literal(10.0f), literal(5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input expression + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Expression input, @NonNull Expression defaultOutput, Expression... stops) { + return new Expression("step", join(new Expression[] {input, defaultOutput}, stops)); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), literal(0.0f), + * stop(1, 2.5f), + * stop(10, 5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Number input, @NonNull Expression defaultOutput, Stop... stops) { + return step(literal(input), defaultOutput, Stop.toExpressionArray(stops)); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), literal(0.0f), + * stop(1, 2.5f), + * stop(10, 5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Expression input, @NonNull Expression defaultOutput, Stop... stops) { + return step(input, defaultOutput, Stop.toExpressionArray(stops)); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(1.0f, 0.0f, + * literal(1.0f), literal(2.5f), + * literal(10.0f), literal(5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Number input, @NonNull Number defaultOutput, Expression... stops) { + return step(literal(input), defaultOutput, stops); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), 0.0f, + * literal(1.0f), literal(2.5f), + * literal(10.0f), literal(5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input expression + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Expression input, @NonNull Number defaultOutput, Expression... stops) { + return step(input, literal(defaultOutput), stops); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), 0.0f, + * stop(1, 2.5f), + * stop(10, 5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Number input, @NonNull Number defaultOutput, Stop... stops) { + return step(literal(input), defaultOutput, Stop.toExpressionArray(stops)); + } + + /** + * Produces discrete, stepped results by evaluating a piecewise-constant function defined by pairs of + * input and output values (\"stops\"). The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * Returns the output value of the stop just less than the input, + * or the first input if the input is less than the first stop. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * CircleLayer circleLayer = new CircleLayer("layer-id", "source-id"); + * circleLayer.setProperties( + * circleRadius( + * step(zoom(), 0.0f, + * stop(1, 2.5f), + * stop(10, 5.0f) + * ) + * ); + * } + * </pre> + * + * @param input the input value + * @param defaultOutput the default output expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step">Style specification</a> + */ + public static Expression step(@NonNull Expression input, @NonNull Number defaultOutput, Stop... stops) { + return step(input, defaultOutput, Stop.toExpressionArray(stops)); + } + + /** + * Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). + * The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * The output type must be `number`, `array<number>`, or `color`. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * exponential(0.5f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param interpolation type of interpolation + * @param number the input expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Expression interpolate(@NonNull Interpolator interpolation, + @NonNull Expression number, Expression... stops) { + return new Expression("interpolate", join(new Expression[] {interpolation, number}, stops)); + } + + /** + * Produces continuous, smooth results by interpolating between pairs of input and output values (\"stops\"). + * The `input` may be any numeric expression (e.g., `[\"get\", \"population\"]`). + * Stop inputs must be numeric literals in strictly ascending order. + * The output type must be `number`, `array<number>`, or `color`. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * exponential(0.5f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param interpolation type of interpolation + * @param number the input expression + * @param stops pair of input and output values + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Expression interpolate(@NonNull Interpolator interpolation, + @NonNull Expression number, Stop... stops) { + return interpolate(interpolation, number, Stop.toExpressionArray(stops)); + } + + /** + * interpolates linearly between the pair of stops just less than and just greater than the input. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * linear(), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Interpolator linear() { + return new Interpolator("linear"); + } + + /** + * Interpolates exponentially between the stops just less than and just greater than the input. + * `base` controls the rate at which the output increases: + * higher values make the output increase more towards the high end of the range. + * With values close to 1 the output increases linearly. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * exponential(0.5f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param base value controlling the route at which the output increases + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Interpolator exponential(@NonNull Number base) { + return exponential(literal(base)); + } + + /** + * Interpolates exponentially between the stops just less than and just greater than the input. + * The parameter controls the rate at which the output increases: + * higher values make the output increase more towards the high end of the range. + * With values close to 1 the output increases linearly. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * exponential(get("keyToValue"), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param expression base number expression + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Interpolator exponential(@NonNull Expression expression) { + return new Interpolator("exponential", expression); + } + + /** + * Interpolates using the cubic bezier curve defined by the given control points. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * cubicBezier(0.42f, 0.0f, 1.0f, 1.0f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param x1 x value of the first point of a cubic bezier, ranges from 0 to 1 + * @param y1 y value of the first point of a cubic bezier, ranges from 0 to 1 + * @param x2 x value of the second point of a cubic bezier, ranges from 0 to 1 + * @param y2 y value fo the second point of a cubic bezier, ranges from 0 to 1 + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Interpolator cubicBezier(@NonNull Expression x1, @NonNull Expression y1, + @NonNull Expression x2, @NonNull Expression y2) { + return new Interpolator("cubic-bezier", x1, y1, x2, y2); + } + + /** + * Interpolates using the cubic bezier curve defined by the given control points. + * <p> + * Example usage: + * </p> + * <pre> + * {@code + * FillLayer fillLayer = new fillLayer("layer-id", "source-id"); + * fillLayer.setProperties( + * fillColor( + * interpolate( + * cubicBezier(0.42f, 0.0f, 1.0f, 1.0f), zoom(), + * literal(1.0f), color(Color.RED), + * literal(5.0f, color(Color.BLUE), + * literal(10.0f, color(Color.GREEN) + * ) + * ) + * ); + * } + * </pre> + * + * @param x1 x value of the first point of a cubic bezier, ranges from 0 to 1 + * @param y1 y value of the first point of a cubic bezier, ranges from 0 to 1 + * @param x2 x value of the second point of a cubic bezier, ranges from 0 to 1 + * @param y2 y value fo the second point of a cubic bezier, ranges from 0 to 1 + * @return expression + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-interpolate">Style specification</a> + */ + public static Interpolator cubicBezier(@NonNull Number x1, @NonNull Number y1, + @NonNull Number x2, @NonNull Number y2) { + return cubicBezier(literal(x1), literal(y1), literal(x2), literal(y2)); + } + + /** + * Joins two expressions arrays. + * <p> + * This flattens the object array output of an expression from a nested expression hierarchy. + * </p> + * + * @param left the left part of an expression + * @param right the right part of an expression + * @return the joined expression + */ + private static Expression[] join(Expression[] left, Expression[] right) { + Expression[] output = new Expression[left.length + right.length]; + System.arraycopy(left, 0, output, 0, left.length); + System.arraycopy(right, 0, output, left.length, right.length); + return output; + } + + /** + * Converts the expression to Object array representation. + * <p> + * The output will later be converted to a JSON Object array. + * </p> + * + * @return the converted object array expression + */ + @NonNull + public Object[] toArray() { + List<Object> array = new ArrayList<>(); + array.add(operator); + if (arguments != null) { + for (Expression argument : arguments) { + if (argument instanceof Expression.ExpressionLiteral) { + array.add(toValue((ExpressionLiteral) argument)); + } else { + array.add(argument.toArray()); + } + } + } + return array.toArray(); + } + + /** + * Converts the expression value to an Object. + * + * @param expressionValue the expression value to convert + * @return the converted object expression + */ + private Object toValue(ExpressionLiteral expressionValue) { + Object value = expressionValue.toValue(); + if (value instanceof PropertyValue) { + throw new IllegalArgumentException("PropertyValue are not allowed as an expression literal, use value instead."); + } else if (value instanceof Expression.ExpressionLiteral) { + return toValue((ExpressionLiteral) value); + } else if (value instanceof Expression) { + return ((Expression) value).toArray(); + } + return value; + } + + /** + * Returns a string representation of the object that matches the definition set in the style specification. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("[\"").append(operator).append("\""); + if (arguments != null) { + for (Object argument : arguments) { + builder.append(", "); + if (argument instanceof ExpressionLiteral) { + builder.append(((ExpressionLiteral) argument).toValue()); + } else { + builder.append(argument.toString()); + } + } + } + builder.append("]"); + return builder.toString(); + } + + /** + * Indicates whether some other object is "equal to" this one. + * + * @param o the other object + * @return true if equal, false if not + */ + @Override + public boolean equals(Object o) { + super.equals(o); + if (this == o) { + return true; + } + + if (o == null || !(o instanceof Expression)) { + return false; + } + + Expression that = (Expression) o; + + if (operator != null ? !operator.equals(that.operator) : that.operator != null) { + return false; + } + return Arrays.deepEquals(arguments, that.arguments); + } + + /** + * Returns a hash code value for the expression. + * + * @return a hash code value for this expression + */ + @Override + public int hashCode() { + int result = operator != null ? operator.hashCode() : 0; + result = 31 * result + Arrays.hashCode(arguments); + return result; + } + + /** + * ExpressionLiteral wraps an object to be used as a literal in an expression. + * <p> + * ExpressionLiteral is created with {@link #literal(Number)}, {@link #literal(boolean)}, + * {@link #literal(String)} and {@link #literal(Object)}. + * </p> + */ + public static class ExpressionLiteral extends Expression { + + protected Object literal; + + /** + * Create an expression literal. + * + * @param object the object to be treated as literal + */ + public ExpressionLiteral(@NonNull Object object) { + this.literal = object; + } + + /** + * Get the literal object. + * + * @return the literal object + */ + Object toValue() { + return literal; + } + + /** + * Returns a string representation of the expression literal. + * + * @return a string representation of the object. + */ + @Override + public String toString() { + return literal.toString(); + } + + /** + * Indicates whether some other object is "equal to" this one. + * + * @param o the other object + * @return true if equal, false if not + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + + ExpressionLiteral that = (ExpressionLiteral) o; + + return literal != null ? literal.equals(that.literal) : that.literal == null; + } + + /** + * Returns a hash code value for the expression literal. + * + * @return a hash code value for this expression literal + */ + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (literal != null ? literal.hashCode() : 0); + return result; + } + } + + /** + * Expression interpolator type. + * <p> + * Is used for first parameter of {@link #interpolate(Interpolator, Expression, Stop...)}. + * </p> + */ + public static class Interpolator extends Expression { + + Interpolator(@NonNull String operator, @Nullable Expression... arguments) { + super(operator, arguments); + } + } + + /** + * Expression array type. + */ + public static class Array { + } + + /** + * Expression stop type. + * <p> + * Can be used for {@link #stop(Object, Object)} as part of varargs parameter in + * {@link #step(Number, Expression, Stop...)} or {@link #interpolate(Interpolator, Expression, Stop...)}. + * </p> + */ + public static class Stop { + + private Object value; + private Object output; + + Stop(Object value, Object output) { + this.value = value; + this.output = output; + } + + /** + * Converts a varargs of Stops to a Expression array. + * + * @param stops the stops to convert + * @return the converted stops as an expression array + */ + static Expression[] toExpressionArray(Stop... stops) { + Expression[] expressions = new Expression[stops.length * 2]; + Stop stop; + Object inputValue, outputValue; + for (int i = 0; i < stops.length; i++) { + stop = stops[i]; + inputValue = stop.value; + outputValue = stop.output; + + if (!(inputValue instanceof Expression)) { + inputValue = literal(inputValue); + } + + if (!(outputValue instanceof Expression)) { + outputValue = literal(outputValue); + } + + expressions[i * 2] = (Expression) inputValue; + expressions[i * 2 + 1] = (Expression) outputValue; + } + return expressions; + } + } + + /** + * Converts a JsonArray to an expression. + */ + public final static class Converter { + + /** + * Converts a JsonArray to an expression + * + * @param jsonArray the json array to convert + * @return the expression + */ + public static Expression convert(@NonNull JsonArray jsonArray) { + if (jsonArray.size() == 0) { + throw new IllegalArgumentException("Can't convert empty jsonArray expressions"); + } + + final String operator = jsonArray.get(0).getAsString(); + final List<Expression> arguments = new ArrayList<>(); + + JsonElement jsonElement; + for (int i = 1; i < jsonArray.size(); i++) { + jsonElement = jsonArray.get(i); + if (jsonElement instanceof JsonArray) { + arguments.add(convert((JsonArray) jsonElement)); + } else if (jsonElement instanceof JsonPrimitive) { + arguments.add(convert((JsonPrimitive) jsonElement)); + } else { + throw new RuntimeException("Unsupported expression conversion for " + jsonElement.getClass()); + } + } + return new Expression(operator, arguments.toArray(new Expression[arguments.size()])); + } + + /** + * Converts a JsonPrimitive to an expression literal + * + * @param jsonPrimitive the json primitive to convert + * @return the expression literal + */ + private static Expression convert(@NonNull JsonPrimitive jsonPrimitive) { + if (jsonPrimitive.isBoolean()) { + return new Expression.ExpressionLiteral(jsonPrimitive.getAsBoolean()); + } else if (jsonPrimitive.isNumber()) { + return new Expression.ExpressionLiteral(jsonPrimitive.getAsFloat()); + } else if (jsonPrimitive.isString()) { + return new Expression.ExpressionLiteral(jsonPrimitive.getAsString()); + } else { + throw new RuntimeException("Unsupported literal expression conversion for " + jsonPrimitive.getClass()); + } + } + } + + /** + * Expression to wrap Object[] as a literal + */ + private static class ExpressionArray extends Expression { + + private Object[] array; + + ExpressionArray(Object[] array) { + this.array = array; + } + + @NonNull + @Override + public Object[] toArray() { + return new Object[] { + "literal", array + }; + } + + /** + * Convert the expression array to a string representation. + * + * @return the string representation of the expression array + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder("[\"literal\"], ["); + Object argument; + for (int i = 0; i < array.length; i++) { + argument = array[i]; + if (argument instanceof String) { + builder.append("\"").append(argument).append("\""); + } else { + builder.append(argument); + } + + if (i != array.length - 1) { + builder.append(", "); + } + } + builder.append("]]"); + return builder.toString(); + } + } + + /** + * Converts an object that is a primitive array to an Object[] + * + * @param object the object to convert to an object array + * @return the converted object array + */ + static Object[] toObjectArray(Object object) { + // object is a primitive array + int len = java.lang.reflect.Array.getLength(object); + Object[] objects = new Object[len]; + for (int i = 0; i < len; i++) { + objects[i] = java.lang.reflect.Array.get(object, i); + } + return objects; + } +}
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/package-info.java new file mode 100644 index 0000000000..ee2b96fa61 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/expressions/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android Expression API classes. + */ +package com.mapbox.mapboxsdk.style.expressions; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CameraFunction.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CameraFunction.java deleted file mode 100644 index bb87fe8a39..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CameraFunction.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions; - -import android.support.annotation.Keep; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.style.functions.stops.ExponentialStops; -import com.mapbox.mapboxsdk.style.functions.stops.IntervalStops; -import com.mapbox.mapboxsdk.style.functions.stops.Stop; -import com.mapbox.mapboxsdk.style.functions.stops.Stops; - -/** - * Camera function. Functions that take camera properties as input (zoom for now) - * <p> - * Zoom functions allow the appearance of a map feature to change with map’s zoom level. - * Zoom functions can be used to create the illusion of depth and control data density. - * Each stop is an array with two elements: the first is a zoom level and the second is - * a function output value. - * - * @param <I> the input type - * @param <O> the output type - * @see Function#zoom - */ -public class CameraFunction<I extends Number, O> extends Function<I, O> { - - /** - * Create an exponential camera function - * - * @param stops @see {@link com.mapbox.mapboxsdk.style.functions.stops.Stops#exponential(float, Stop[])} - */ - CameraFunction(@NonNull ExponentialStops<I, O> stops) { - super(stops); - } - - /** - * Create an interval camera function - * - * @param stops @see {@link com.mapbox.mapboxsdk.style.functions.stops.Stops#interval(Stop[])} - */ - CameraFunction(@NonNull IntervalStops<I, O> stops) { - super(stops); - } - - /** - * JNI constructor - */ - @Keep - private CameraFunction(Stops<I, O> stops) { - super(stops); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CompositeFunction.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CompositeFunction.java deleted file mode 100644 index 15e4474105..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/CompositeFunction.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.style.functions.stops.CategoricalStops; -import com.mapbox.mapboxsdk.style.functions.stops.ExponentialStops; -import com.mapbox.mapboxsdk.style.functions.stops.IntervalStops; -import com.mapbox.mapboxsdk.style.functions.stops.Stop; -import com.mapbox.mapboxsdk.style.functions.stops.Stops; -import com.mapbox.mapboxsdk.style.layers.PropertyValue; - -import java.util.Map; - -/** - * Composite functions combine Camera and SourceFunctions. - * <p> - * Composite functions allow the appearance of a map feature to change with both its - * properties and zoom. Each stop is an array with two elements, the first is an object - * with a property input value and a zoom, and the second is a function output value. Note - * that support for property functions is not yet complete. - * - * @param <Z> the zoom type (usually Float) - * @param <I> the input type (the feature property type) - * @param <O> the output type (the property type) - * @see Function#composite - */ -public class CompositeFunction<Z extends Number, I, O> extends Function<Stop.CompositeValue<Z, I>, O> { - - private final String property; - private PropertyValue<O> defaultValue; - - CompositeFunction(@NonNull String property, - @NonNull CategoricalStops<Stop.CompositeValue<Z, I>, O> stops) { - this(null, property, stops); - } - - CompositeFunction(@NonNull String property, - @NonNull ExponentialStops<Stop.CompositeValue<Z, I>, O> stops) { - this(null, property, stops); - } - - CompositeFunction(@NonNull String property, - @NonNull IntervalStops<Stop.CompositeValue<Z, I>, O> stops) { - this(null, property, stops); - } - - - /** - * JNI Constructor - */ - private CompositeFunction(@Nullable O defaultValue, @NonNull String property, - @NonNull Stops<Stop.CompositeValue<Z, I>, O> stops) { - super(stops); - this.defaultValue = new PropertyValue<>(property, defaultValue); - this.property = property; - } - - /** - * Set the default value - * - * @param defaultValue the default value to use when no other applies - * @return this (for chaining) - */ - public CompositeFunction<Z, I, O> withDefaultValue(PropertyValue<O> defaultValue) { - this.defaultValue = defaultValue; - return this; - } - - /** - * @return the defaultValue - */ - @Nullable - public PropertyValue<O> getDefaultValue() { - return defaultValue; - } - - /** - * INTERNAL USAGE ONLY - * - * @return the feature property name - */ - public String getProperty() { - return property; - } - - /** - * {@inheritDoc} - */ - @Override - public Map<String, Object> toValueObject() { - Map<String, Object> valueObject = super.toValueObject(); - valueObject.put(PROPERTY_KEY, property); - if (defaultValue != null) { - valueObject.put(DEFAULT_VALUE_KEY, defaultValue.value); - } - return valueObject; - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/Function.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/Function.java deleted file mode 100644 index e7bb52ebb3..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/Function.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.style.functions.stops.CategoricalStops; -import com.mapbox.mapboxsdk.style.functions.stops.ExponentialStops; -import com.mapbox.mapboxsdk.style.functions.stops.IdentityStops; -import com.mapbox.mapboxsdk.style.functions.stops.IntervalStops; -import com.mapbox.mapboxsdk.style.functions.stops.Stop; -import com.mapbox.mapboxsdk.style.functions.stops.Stops; - -import java.util.Map; - -import timber.log.Timber; - -/** - * Functions are used to change properties in relation to the state of the map. - * <p> - * The value for any layout or paint property may be specified as a function. Functions allow you to - * make the appearance of a map feature change with the current zoom level and/or the feature's properties. - * - * @param <I> the function's input type - * @param <O> the target property's value type. Make sure it matches. - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-function">The style specification</a> - */ -public class Function<I, O> { - - static final String PROPERTY_KEY = "property"; - static final String DEFAULT_VALUE_KEY = "default"; - - /** - * Create an exponential {@link CameraFunction} - * <p> - * Zoom functions allow the appearance of a map feature to change with map’s zoom. - * Zoom functions can be used to create the illusion of depth and control data density. - * Each stop is an array with two elements, the first is a zoom and the second is a function output value. - * - * @param <Z> the zoom level type (Float, Integer) - * @param <O> the property type - * @param stops the stops implementation that define the function. @see {@link Stops#exponential(Stop[])} - * @return the {@link CameraFunction} - * @see CameraFunction - * @see ExponentialStops - * @see Stops#exponential(Stop[]) - * @see Stops#exponential(Stop[]) - * @see Stop#stop - */ - public static <Z extends Number, O> CameraFunction<Z, O> zoom(@NonNull ExponentialStops<Z, O> stops) { - return new CameraFunction<>(stops); - } - - /** - * Create an interval {@link CameraFunction} - * <p> - * Zoom functions allow the appearance of a map feature to change with map’s zoom. - * Zoom functions can be used to create the illusion of depth and control data density. - * Each stop is an array with two elements, the first is a zoom and the second is a function output value. - * - * @param <Z> the zoom level type (Float, Integer) - * @param <O> the property type - * @param stops the stops implementation that define the function. @see {@link Stops#interval(Stop[])} - * @return the {@link CameraFunction} - * @see CameraFunction - * @see IntervalStops - * @see Stops#interval(Stop[]) - * @see Stop#stop - */ - public static <Z extends Number, O> CameraFunction<Z, O> zoom(@NonNull IntervalStops<Z, O> stops) { - return new CameraFunction<>(stops); - } - - /** - * Create an exponential {@link SourceFunction} - * <p> - * Source functions allow the appearance of a map feature to change with - * its properties. Source functions can be used to visually differentiate - * types of features within the same layer or create data visualizations. - * Each stop is an array with two elements, the first is a property input - * value and the second is a function output value. Note that support for - * property functions is not available across all properties and platforms - * at this time. - * - * @param property the feature property name - * @param stops the stops - * @param <I> the function input type - * @param <O> the function output type - * @return the {@link SourceFunction} - * @see SourceFunction - * @see ExponentialStops - * @see Stops#exponential(Stop[]) - * @see Stop#stop - */ - public static <I, O> SourceFunction<I, O> property(@NonNull String property, @NonNull ExponentialStops<I, O> stops) { - return new SourceFunction<>(property, stops); - } - - /** - * Create an identity {@link SourceFunction} - * <p> - * Source functions allow the appearance of a map feature to change with - * its properties. Source functions can be used to visually differentiate - * types of features within the same layer or create data visualizations. - * Each stop is an array with two elements, the first is a property input - * value and the second is a function output value. Note that support for - * property functions is not available across all properties and platforms - * at this time. - * - * @param property the feature property name - * @param stops the stops - * @param <T> the function input/output type - * @return the {@link SourceFunction} - * @see SourceFunction - * @see IdentityStops - * @see Stops#identity() - * @see Stop#stop - */ - public static <T> SourceFunction<T, T> property(@NonNull String property, @NonNull IdentityStops<T> stops) { - return new SourceFunction<>(property, stops); - } - - /** - * Create an interval {@link SourceFunction} - * <p> - * Source functions allow the appearance of a map feature to change with - * its properties. Source functions can be used to visually differentiate - * types of features within the same layer or create data visualizations. - * Each stop is an array with two elements, the first is a property input - * value and the second is a function output value. Note that support for - * property functions is not available across all properties and platforms - * at this time. - * - * @param property the feature property name - * @param stops the stops - * @param <I> the function input type - * @param <O> the function output type - * @return the {@link SourceFunction} - * @see SourceFunction - * @see IntervalStops - * @see Stops#interval(Stop[]) - * @see Stop#stop - */ - public static <I, O> SourceFunction<I, O> property(@NonNull String property, @NonNull IntervalStops<I, O> stops) { - return new SourceFunction<>(property, stops); - } - - /** - * Create an categorical {@link SourceFunction} - * <p> - * Source functions allow the appearance of a map feature to change with - * its properties. Source functions can be used to visually differentiate - * types of features within the same layer or create data visualizations. - * Each stop is an array with two elements, the first is a property input - * value and the second is a function output value. Note that support for - * property functions is not available across all properties and platforms - * at this time. - * - * @param property the feature property name - * @param stops the stops - * @param <I> the function input type - * @param <O> the function output type - * @return the {@link SourceFunction} - * @see SourceFunction - * @see CategoricalStops - * @see Stops#categorical(Stop[]) - * @see Stop#stop - */ - public static <I, O> SourceFunction<I, O> property(@NonNull String property, @NonNull CategoricalStops<I, O> stops) { - return new SourceFunction<>(property, stops); - } - - /** - * Create a composite, categorical function. - * <p> - * Composite functions allow the appearance of a map feature to change with both its - * properties and zoom. Each stop is an array with two elements, the first is an object - * with a property input value and a zoom, and the second is a function output value. Note - * that support for property functions is not yet complete. - * - * @param property the feature property name for the source part of the function - * @param stops the stops - * @param <Z> the zoom function input type (Float usually) - * @param <I> the function input type for the source part of the function - * @param <O> the function output type - * @return the {@link CompositeFunction} - * @see CompositeFunction - * @see CategoricalStops - * @see Stops#categorical(Stop[]) - * @see Stop#stop - */ - public static <Z extends Number, I, O> CompositeFunction<Z, I, O> composite( - @NonNull String property, - @NonNull CategoricalStops<Stop.CompositeValue<Z, I>, O> stops) { - - return new CompositeFunction<>(property, stops); - } - - /** - * Create a composite, exponential function. - * <p> - * Composite functions allow the appearance of a map feature to change with both its - * properties and zoom. Each stop is an array with two elements, the first is an object - * with a property input value and a zoom, and the second is a function output value. Note - * that support for property functions is not yet complete. - * - * @param property the feature property name for the source part of the function - * @param stops the stops - * @param <Z> the zoom function input type (Float usually) - * @param <I> the function input type for the source part of the function - * @param <O> the function output type - * @return the {@link CompositeFunction} - * @see CompositeFunction - * @see ExponentialStops - * @see Stops#exponential(Stop[]) - * @see Stop#stop - */ - public static <Z extends Number, I, O> CompositeFunction<Z, I, O> composite( - @NonNull String property, - @NonNull ExponentialStops<Stop.CompositeValue<Z, I>, O> stops) { - - return new CompositeFunction<>(property, stops); - } - - /** - * Create a composite, interval function. - * <p> - * Composite functions allow the appearance of a map feature to change with both its - * properties and zoom. Each stop is an array with two elements, the first is an object - * with a property input value and a zoom, and the second is a function output value. Note - * that support for property functions is not yet complete. - * - * @param property the feature property name for the source part of the function - * @param stops the stops - * @param <Z> the zoom function input type (Float usually) - * @param <I> the function input type for the source part of the function - * @param <O> the function output type - * @return the {@link CompositeFunction} - * @see CompositeFunction - * @see IntervalStops - * @see Stops#interval(Stop[]) - * @see Stop#stop - */ - public static <Z extends Number, I, O> CompositeFunction<Z, I, O> composite( - @NonNull String property, - @NonNull IntervalStops<Stop.CompositeValue<Z, I>, O> stops) { - - return new CompositeFunction<>(property, stops); - } - - // Class definition // - - private final Stops<I, O> stops; - - /** - * JNI Cosntructor for implementation classes - * - * @param stops the stops - */ - Function(@NonNull Stops<I, O> stops) { - this.stops = stops; - } - - /** - * @return the stops in this function - */ - public Stops getStops() { - return stops; - } - - /** - * Convenience method - * - * @param <S> the Stops implementation type - * @return the Stops implementation or null when the wrong type is specified - */ - @Nullable - public <S extends Stops> S getStopsAs() { - try { - // noinspection unchecked - return (S) stops; - } catch (ClassCastException exception) { - Timber.e(exception, "Stops: %s is a different type: ", stops.getClass()); - return null; - } - } - - /** - * INTERNAL USAGE ONLY - * - * @return a value object representation for core conversion - */ - public Map<String, Object> toValueObject() { - return stops.toValueObject(); - } - - @Override - public String toString() { - return String.format("%s: %s", getClass().getSimpleName(), stops); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/SourceFunction.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/SourceFunction.java deleted file mode 100644 index 33f436ae71..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/SourceFunction.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.style.functions.stops.Stops; -import com.mapbox.mapboxsdk.style.layers.PropertyValue; - -import java.util.Map; - -/** - * Source functions take Feature property names as input. - * <p> - * Source functions allow the appearance of a map feature to change with - * its properties. Source functions can be used to visually differentiate - * types of features within the same layer or create data visualizations. - * Each stop is an array with two elements, the first is a property input - * value and the second is a function output value. Note that support for - * property functions is not available across all properties and platforms - * at this time. - * - * @param <I> the input type - * @param <O> the output type - * @see Function#property - */ -public class SourceFunction<I, O> extends Function<I, O> { - - private final String property; - private PropertyValue<O> defaultValue; - - SourceFunction(@NonNull String property, @NonNull Stops<I, O> stops) { - this(null, property, stops); - } - - /** - * JNI Constructor - */ - private SourceFunction(@Nullable O defaultValue, @NonNull String property, @NonNull Stops<I, O> stops) { - super(stops); - this.property = property; - this.defaultValue = defaultValue != null ? new PropertyValue<>(property, defaultValue) : null; - } - - - /** - * INTERNAL USAGE ONLY - * - * @return The feature property name - */ - public String getProperty() { - return property; - } - - /** - * Set the default value - * - * @param defaultValue the default value to use when no other applies - * @return this (for chaining) - */ - public SourceFunction<I, O> withDefaultValue(PropertyValue<O> defaultValue) { - this.defaultValue = defaultValue; - return this; - } - - /** - * @return the defaultValue - */ - @Nullable - public PropertyValue<O> getDefaultValue() { - return defaultValue; - } - - /** - * {@inheritDoc} - */ - @Override - public Map<String, Object> toValueObject() { - Map<String, Object> valueObject = super.toValueObject(); - valueObject.put(PROPERTY_KEY, property); - if (defaultValue != null) { - valueObject.put(DEFAULT_VALUE_KEY, defaultValue.value); - } - return valueObject; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/package-info.java deleted file mode 100644 index 6979676c9e..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Contains the Mapbox Maps Android Style Function API classes. - * - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-function">The style specification</a> - */ -package com.mapbox.mapboxsdk.style.functions; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/CategoricalStops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/CategoricalStops.java deleted file mode 100644 index f9b2929350..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/CategoricalStops.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import android.support.annotation.NonNull; -import android.support.annotation.Size; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; - -/** - * {@link Stops} implementation for categorical functions - * - * @param <I> the {@link Stop} input type - * @param <O> the {@link Stop} output type - */ -public class CategoricalStops<I, O> extends IterableStops<I, O, Stop<I, O>> { - - private final Stop<I, O>[] stops; - - /** - * Create a categorical {@link Stops} implementation. Use through {@link Stops#categorical(Stop[])} - * - * @param stops the stops - */ - @SafeVarargs - public CategoricalStops(@NonNull @Size(min = 1) Stop<I, O>... stops) { - this.stops = stops; - } - - /** - * {@inheritDoc} - */ - @Override - public Map<String, Object> toValueObject() { - Map<String, Object> map = super.toValueObject(); - map.put("stops", toValueObjects(stops)); - return map; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeName() { - return "categorical"; - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator<Stop<I, O>> iterator() { - return Arrays.asList(stops).iterator(); - } - - /** - * {@inheritDoc} - */ - @Override - public int size() { - return stops.length; - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/ExponentialStops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/ExponentialStops.java deleted file mode 100644 index d47aa1fc91..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/ExponentialStops.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import android.support.annotation.NonNull; -import android.support.annotation.Size; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; - -/** - * The {@link Stops} implementation for exponential functions - * - * @param <I> the input type - * @param <O> the output type - */ -public class ExponentialStops<I, O> extends IterableStops<I, O, Stop<I, O>> { - - private float base; - private final Stop<I, O>[] stops; - - /** - * Create exponential stops with an explicit base. Use through {@link Stops#exponential(Stop[])} - * - * @param base The exponential base of the interpolation curve. It controls the rate at which the function output - * increases. Higher values make the output increase more towards the high end of the range. - * With values close to 1 the output increases linearly. - * @param stops the stops - */ - @SafeVarargs - public ExponentialStops(Float base, @NonNull @Size(min = 1) Stop<I, O>... stops) { - this.base = base != null ? base : 1.0f; - this.stops = stops; - } - - /** - * Create exponential stops without an explicit base. Use through {@link Stops#exponential(Stop[])} - * - * @param stops the stops - */ - @SafeVarargs - public ExponentialStops(@NonNull @Size(min = 1) Stop<I, O>... stops) { - this(null, stops); - } - - /** - * Set the exponential base - * - * @param base the base to use in the exponential function - * @return this (for chaining) - */ - public ExponentialStops<I, O> withBase(float base) { - this.base = base; - return this; - } - - /** - * @return The exponential base - */ - public float getBase() { - return base; - } - - /** - * {@inheritDoc} - */ - @Override - public Map<String, Object> toValueObject() { - Map<String, Object> map = super.toValueObject(); - map.put("base", base); - map.put("stops", toValueObjects(stops)); - return map; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeName() { - return "exponential"; - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator<Stop<I, O>> iterator() { - return Arrays.asList(stops).iterator(); - } - - /** - * {@inheritDoc} - */ - @Override - public int size() { - return stops.length; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IdentityStops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IdentityStops.java deleted file mode 100644 index 2c0b198dc2..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IdentityStops.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -/** - * The {@link Stops} implementation for identity functions - * - * @param <T> the input/output type - */ -public class IdentityStops<T> extends Stops<T, T> { - - /** - * {@inheritDoc} - */ - @Override - protected String getTypeName() { - return "identity"; - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IntervalStops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IntervalStops.java deleted file mode 100644 index 9d95b3f8c1..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IntervalStops.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import android.support.annotation.NonNull; -import android.support.annotation.Size; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; - -/** - * The {@link Stops} implementation for interval functions - * - * @param <I> the input type - * @param <O> the output type - */ -public class IntervalStops<I, O> extends IterableStops<I, O, Stop<I, O>> { - - private final Stop<I, O>[] stops; - - @SafeVarargs - public IntervalStops(@NonNull @Size(min = 1) Stop<I, O>... stops) { - this.stops = stops; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeName() { - return "interval"; - } - - /** - * {@inheritDoc} - */ - @Override - public Map<String, Object> toValueObject() { - Map<String, Object> map = super.toValueObject(); - map.put("stops", toValueObjects(stops)); - return map; - } - - /** - * @return an {@link Iterator} for the contained stops - */ - @Override - public Iterator<Stop<I, O>> iterator() { - return Arrays.asList(stops).iterator(); - } - - /** - * @return The number of contained stops - */ - @Override - public int size() { - return stops.length; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IterableStops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IterableStops.java deleted file mode 100644 index 8c5a6e8913..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/IterableStops.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import java.util.Iterator; - -/** - * Base class for {@link Stops} implementations with a collection of stops - * - * @param <I> the {@link Stops} input type - * @param <O> the {@link Stops} output type - * @param <S> the {@link Iterable} element type (usually {@link Stop}) - */ -public abstract class IterableStops<I, O, S> extends Stops<I, O> implements Iterable<S> { - - /** - * @return The size of the contained stops collection - */ - public abstract int size(); - - /** - * Convenience function to toValueObjects an array of stops to an array of value objects - * - * @param stops the stops to toValueObjects - * @return the stops as value objects - */ - Object[] toValueObjects(Stop<I, O>[] stops) { - if (stops != null) { - Object[] stopsValue = new Object[stops.length]; - - for (int i = 0; i < stopsValue.length; i++) { - Stop stop = stops[i]; - stopsValue[i] = stop.toValueObject(); - } - return stopsValue; - } - - return null; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - Iterator<S> iterator = iterator(); - while (iterator.hasNext()) { - S stop = iterator.next(); - buffer.append(stop); - if (iterator.hasNext()) { - buffer.append(","); - } - } - return String.format("%s: [%s]", super.toString(), buffer.toString()); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stop.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stop.java deleted file mode 100644 index 72164f4c4b..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stop.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import com.mapbox.mapboxsdk.style.functions.Function; -import com.mapbox.mapboxsdk.style.layers.PropertyValue; - -import java.util.HashMap; -import java.util.Map; - -/** - * A stop represents a certain point in the range of this function - * - * @param <I> input the stop (function) input type - * @param <O> output the stop (function) output type - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-function">The style specification</a> - */ -public class Stop<I, O> { - /** - * Creates a {@link Stop} to use in a {@link Function} - * - * @param in the input for the stop - * @param output the output for the stop - * @param <I> the input property type - * @param <O> the output property type - * @return the {@link Stop} - */ - public static <I, O> Stop<I, O> stop(I in, PropertyValue<O> output) { - return new Stop<>(in, output.value); - } - - /** - * Create a composite {@link Stop} for use in a {@link com.mapbox.mapboxsdk.style.functions.CompositeFunction} - * - * @param zoom the zoom input - * @param value the feature property input - * @param output the output for the stop - * @param <Z> the zoom type - * @param <I> the feature property input type - * @param <O> the output property type - * @return the {@link Stop} - * @see Function#composite(String, ExponentialStops) - */ - public static <Z extends Number, I, O> Stop<Stop.CompositeValue<Z, I>, O> stop(Z zoom, - I value, - PropertyValue<O> output) { - return new Stop<>(new Stop.CompositeValue<>(zoom, value), output.value); - } - - /** - * Represents a composite input value for composite functions (eg zoom and feature property value) - * - * @param <Z> the zoom input type (typically Float) - * @param <V> the feature property input type - */ - public static class CompositeValue<Z extends Number, V> { - public final Z zoom; - public final V value; - - CompositeValue(Z zoom, V value) { - this.zoom = zoom; - this.value = value; - } - - /** - * INTERNAL USAGE ONLY - * - * @return the value object representation for core conversion - */ - Map<String, Object> toValueObject() { - HashMap<String, Object> map = new HashMap<>(); - map.put("zoom", zoom); - map.put("value", value); - return map; - } - - @Override - public String toString() { - return String.format("[zoom: %s, value: %s]", zoom, value); - } - } - - /** - * The input type - */ - public final I in; - - /** - * The output type - */ - public final O out; - - Stop(I in, O out) { - this.in = in; - this.out = out; - } - - /** - * INTERNAL USAGE ONLY - * - * @return an array representation of the Stop - */ - Object[] toValueObject() { - return new Object[] {in instanceof CompositeValue ? ((CompositeValue) in).toValueObject() : in, out}; - } - - @Override - public String toString() { - return String.format("[%s, %s]", in, out); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stops.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stops.java deleted file mode 100644 index af4f53c072..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/Stops.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.mapbox.mapboxsdk.style.functions.stops; - -import android.support.annotation.CallSuper; -import android.support.annotation.NonNull; -import android.support.annotation.Size; - -import java.util.HashMap; -import java.util.Map; - -/** - * The base class for different stops implementations - * - * @param <I> the input type - * @param <O> the output type - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-function">The style specification</a> - */ -public abstract class Stops<I, O> { - - /** - * Convenience method for use in function declarations - * - * @param stops the collections of discrete stops - * @param <I> the Stops input type - * @param <O> the Stops output type - * @return the {@link Stops} implementation - * @see Stop#stop - * @see CategoricalStops - */ - @SafeVarargs - public static <I, O> CategoricalStops<I, O> categorical(@NonNull @Size(min = 1) Stop<I, O>... stops) { - return new CategoricalStops<>(stops); - } - - /** - * Convenience method for use in function declarations - * - * @param stops the collections of discrete stops - * @param <I> the Stops input type - * @param <O> the Stops output type - * @return the {@link Stops} implementation - * @see Stop#stop - * @see ExponentialStops - */ - @SafeVarargs - public static <I, O> ExponentialStops<I, O> exponential(@NonNull @Size(min = 1) Stop<I, O>... stops) { - return new ExponentialStops<>(stops); - } - - /** - * Convenience method for use in function declarations - * - * @param <T> the Stops input/output type - * @return the {@link IdentityStops} implementation - * @see Stop#stop - * @see IdentityStops - */ - public static <T> IdentityStops<T> identity() { - return new IdentityStops<>(); - } - - /** - * Convenience method for use in function declarations - * - * @param stops the collections of discrete stops - * @param <I> the Stops input type - * @param <O> the Stops output type - * @return the {@link Stops} implementation - * @see Stop#stop - * @see IntervalStops - */ - @SafeVarargs - public static <I, O> IntervalStops<I, O> interval(@NonNull @Size(min = 1) Stop<I, O>... stops) { - return new IntervalStops<>(stops); - } - - /** - * INTERNAL USAGE ONLY - * - * @return the value object representation for conversion to core - */ - @CallSuper - public Map<String, Object> toValueObject() { - HashMap<String, Object> map = new HashMap<>(); - map.put("type", getTypeName()); - return map; - } - - /** - * INTERNAL USAGE ONLY - * - * @return the unique type name as a string according to the style specification - */ - protected abstract String getTypeName(); - - @Override - public String toString() { - return getTypeName(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/package-info.java deleted file mode 100644 index fa388a9589..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/functions/stops/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Contains the Mapbox Maps Android Style Function Stop implementation API classes. - * - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-function">The style specification</a> - */ -package com.mapbox.mapboxsdk.style.functions.stops; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/BackgroundLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/BackgroundLayer.java index 978fa29ef8..60c2aa907b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/BackgroundLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/BackgroundLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CircleLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CircleLayer.java index 10663142b5..94929398d5 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CircleLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CircleLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -69,26 +72,41 @@ public class CircleLayer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public CircleLayer withFilter(Filter.Statement filter) { + public CircleLayer withFilter(Expression filter) { setFilter(filter); return this; } /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** * Set a property or properties. * * @param properties the var-args properties diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CustomLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CustomLayer.java index f77e7280f0..a0ba1e2159 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CustomLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/CustomLayer.java @@ -9,20 +9,8 @@ package com.mapbox.mapboxsdk.style.layers; public class CustomLayer extends Layer { public CustomLayer(String id, - long context, - long initializeFunction, - long renderFunction, - long deinitializeFunction) { - this(id, context, initializeFunction, renderFunction, 0L, deinitializeFunction); - } - - public CustomLayer(String id, - long context, - long initializeFunction, - long renderFunction, - long contextLostFunction, - long deinitializeFunction) { - initialize(id, initializeFunction, renderFunction, contextLostFunction, deinitializeFunction, context); + long host) { + initialize(id, host); } public CustomLayer(long nativePtr) { @@ -33,9 +21,7 @@ public class CustomLayer extends Layer { nativeUpdate(); } - protected native void initialize(String id, long initializeFunction, long renderFunction, - long contextLostFunction, long deinitializeFunction, - long context); + protected native void initialize(String id, long host); protected native void nativeUpdate(); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillExtrusionLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillExtrusionLayer.java index 6772da73b1..29e2b49d76 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillExtrusionLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillExtrusionLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -69,26 +72,41 @@ public class FillExtrusionLayer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public FillExtrusionLayer withFilter(Filter.Statement filter) { + public FillExtrusionLayer withFilter(Expression filter) { setFilter(filter); return this; } /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** * Set a property or properties. * * @param properties the var-args properties diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillLayer.java index 3719ae9e1b..ed780811c0 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/FillLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -69,26 +72,41 @@ public class FillLayer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public FillLayer withFilter(Filter.Statement filter) { + public FillLayer withFilter(Expression filter) { setFilter(filter); return this; } /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** * Set a property or properties. * * @param properties the var-args properties diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Filter.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Filter.java deleted file mode 100644 index 4dbb461e4c..0000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Filter.java +++ /dev/null @@ -1,230 +0,0 @@ -package com.mapbox.mapboxsdk.style.layers; - -import java.util.ArrayList; -import java.util.Collections; - -/** - * Utility to build filter expressions more easily. - * - * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#types-filter">The online documentation</a> - */ -public class Filter { - - /** - * Base Filter statement. Subclassed to provide concrete statements. - */ - public abstract static class Statement { - protected final String operator; - - public Statement(String operator) { - this.operator = operator; - } - - /** - * Generate a raw array representation of the filter - * - * @return the filter represented as an array - */ - public abstract Object[] toArray(); - } - - /** - * Represents a {@link Filter} statement. Can be unary (eg `has()`, etc) or take any number of values. - */ - private static class SimpleStatement extends Statement { - private final String key; - private final Object[] values; - - /** - * @param operator the operator (eg `=`, etc) - * @param key the property key - * @param values the values to operate on, if any - */ - SimpleStatement(String operator, String key, Object... values) { - super(operator); - this.key = key; - this.values = values; - } - - - /** - * {@inheritDoc} - */ - @Override - public Object[] toArray() { - ArrayList<Object> array = new ArrayList<>(2 + values.length); - array.add(operator); - array.add(key); - Collections.addAll(array, values); - return array.toArray(); - } - } - - /** - * Represents a collection of {@link Statement}s with an operator that describes their relationship - */ - private static class CompoundStatement extends Statement { - private final Statement[] statements; - - /** - * @param operator the relationship operator - * @param statements the statements to compound - */ - CompoundStatement(String operator, Statement... statements) { - super(operator); - this.statements = statements; - } - - /** - * {@inheritDoc} - */ - @Override - public Object[] toArray() { - ArrayList<Object> array = new ArrayList<>(1 + statements.length); - array.add(operator); - for (Statement statement : statements) { - array.add(statement.toArray()); - } - return array.toArray(); - } - } - - /** - * Groups a collection of statements in an 'all' relationship - * - * @param statements the collection of statements - * @return the statements compounded - */ - public static Statement all(Statement... statements) { - return new CompoundStatement("all", statements); - } - - /** - * Groups a collection of statements in an 'any' relationship - * - * @param statements the collection of statements - * @return the statements compounded - */ - public static Statement any(Statement... statements) { - return new CompoundStatement("any", statements); - } - - /** - * Groups a collection of statements in an 'none' relationship - * - * @param statements the collection of statements - * @return the statements compounded - */ - public static Statement none(Statement... statements) { - return new CompoundStatement("none", statements); - } - - /** - * Check the property's existence - * - * @param key the property key - * @return the statement - */ - public static Statement has(String key) { - return new SimpleStatement("has", key); - } - - /** - * Check the property's existence, negated - * - * @param key the property key - * @return the statement - */ - public static Statement notHas(String key) { - return new SimpleStatement("!has", key); - } - - /** - * Check the property equals the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement eq(String key, Object value) { - return new SimpleStatement("==", key, value); - } - - /** - * Check the property does not equals the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement neq(String key, Object value) { - return new SimpleStatement("!=", key, value); - } - - /** - * Check the property exceeds the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement gt(String key, Object value) { - return new SimpleStatement(">", key, value); - } - - /** - * Check the property exceeds or equals the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement gte(String key, Object value) { - return new SimpleStatement(">=", key, value); - } - - /** - * Check the property does not exceeds the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement lt(String key, Object value) { - return new SimpleStatement("<", key, value); - } - - /** - * Check the property equals or does not exceeds the given value - * - * @param key the property key - * @param value the value to check against - * @return the statement - */ - public static Statement lte(String key, Object value) { - return new SimpleStatement("<=", key, value); - } - - /** - * Check the property is within the given set - * - * @param key the property key - * @param values the set of values to check against - * @return the statement - */ - public static Statement in(String key, Object... values) { - return new SimpleStatement("in", key, values); - } - - /** - * Check the property is not within the given set - * - * @param key the property key - * @param values the set of values to check against - * @return the statement - */ - public static Statement notIn(String key, Object... values) { - return new SimpleStatement("!in", key, values); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HeatmapLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HeatmapLayer.java new file mode 100644 index 0000000000..42b4210710 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HeatmapLayer.java @@ -0,0 +1,267 @@ +// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`. + +package com.mapbox.mapboxsdk.style.layers; + +import android.support.annotation.ColorInt; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.UiThread; + +import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; + +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; +import com.mapbox.mapboxsdk.style.layers.TransitionOptions; + +/** + * A heatmap. + * + * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#layers-heatmap">The online documentation</a> + */ +@UiThread +public class HeatmapLayer extends Layer { + + /** + * Creates a HeatmapLayer. + * + * @param nativePtr pointer used by core + */ + public HeatmapLayer(long nativePtr) { + super(nativePtr); + } + + /** + * Creates a HeatmapLayer. + * + * @param layerId the id of the layer + * @param sourceId the id of the source + */ + public HeatmapLayer(String layerId, String sourceId) { + initialize(layerId, sourceId); + } + + protected native void initialize(String layerId, String sourceId); + + /** + * Set the source layer. + * + * @param sourceLayer the source layer to set + */ + public void setSourceLayer(String sourceLayer) { + nativeSetSourceLayer(sourceLayer); + } + + /** + * Set the source Layer. + * + * @param sourceLayer the source layer to set + * @return This + */ + public HeatmapLayer withSourceLayer(String sourceLayer) { + setSourceLayer(sourceLayer); + return this; + } + + /** + * Get the source layer. + * + * @return sourceLayer the source layer to get + */ + public String getSourceLayer() { + return nativeGetSourceLayer(); + } + + /** + * Set a single expression filter. + * + * @param filter the expression filter to set + */ + public void setFilter(Expression filter) { + nativeSetFilter(filter.toArray()); + } + + /** + * Set a single expression filter. + * + * @param filter the expression filter to set + * @return This + */ + public HeatmapLayer withFilter(Expression filter) { + setFilter(filter); + return this; + } + + /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** + * Set a property or properties. + * + * @param properties the var-args properties + * @return This + */ + public HeatmapLayer withProperties(@NonNull PropertyValue<?>... properties) { + setProperties(properties); + return this; + } + + // Property getters + + /** + * Get the HeatmapRadius property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHeatmapRadius() { + return (PropertyValue<Float>) new PropertyValue("heatmap-radius", nativeGetHeatmapRadius()); + } + + /** + * Get the HeatmapRadius property transition options + * + * @return transition options for Float + */ + public TransitionOptions getHeatmapRadiusTransition() { + return nativeGetHeatmapRadiusTransition(); + } + + /** + * Set the HeatmapRadius property transition options + * + * @param options transition options for Float + */ + public void setHeatmapRadiusTransition(TransitionOptions options) { + nativeSetHeatmapRadiusTransition(options.getDuration(), options.getDelay()); + } + + /** + * Get the HeatmapWeight property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHeatmapWeight() { + return (PropertyValue<Float>) new PropertyValue("heatmap-weight", nativeGetHeatmapWeight()); + } + + /** + * Get the HeatmapIntensity property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHeatmapIntensity() { + return (PropertyValue<Float>) new PropertyValue("heatmap-intensity", nativeGetHeatmapIntensity()); + } + + /** + * Get the HeatmapIntensity property transition options + * + * @return transition options for Float + */ + public TransitionOptions getHeatmapIntensityTransition() { + return nativeGetHeatmapIntensityTransition(); + } + + /** + * Set the HeatmapIntensity property transition options + * + * @param options transition options for Float + */ + public void setHeatmapIntensityTransition(TransitionOptions options) { + nativeSetHeatmapIntensityTransition(options.getDuration(), options.getDelay()); + } + + /** + * Get the HeatmapColor property + * + * @return property wrapper value around String + */ + @SuppressWarnings("unchecked") + public PropertyValue<String> getHeatmapColor() { + return (PropertyValue<String>) new PropertyValue("heatmap-color", nativeGetHeatmapColor()); + } + + /** + * Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `["heatmap-density"]` as input. + * + * @return int representation of a rgba string color + * @throws RuntimeException thrown if property isn't a value + */ + @ColorInt + public int getHeatmapColorAsInt() { + PropertyValue<String> value = getHeatmapColor(); + if (value.isValue()) { + return rgbaToColor(value.getValue()); + } else { + throw new RuntimeException("heatmap-color was set as a Function"); + } + } + + /** + * Get the HeatmapOpacity property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHeatmapOpacity() { + return (PropertyValue<Float>) new PropertyValue("heatmap-opacity", nativeGetHeatmapOpacity()); + } + + /** + * Get the HeatmapOpacity property transition options + * + * @return transition options for Float + */ + public TransitionOptions getHeatmapOpacityTransition() { + return nativeGetHeatmapOpacityTransition(); + } + + /** + * Set the HeatmapOpacity property transition options + * + * @param options transition options for Float + */ + public void setHeatmapOpacityTransition(TransitionOptions options) { + nativeSetHeatmapOpacityTransition(options.getDuration(), options.getDelay()); + } + + private native Object nativeGetHeatmapRadius(); + + private native TransitionOptions nativeGetHeatmapRadiusTransition(); + + private native void nativeSetHeatmapRadiusTransition(long duration, long delay); + + private native Object nativeGetHeatmapWeight(); + + private native Object nativeGetHeatmapIntensity(); + + private native TransitionOptions nativeGetHeatmapIntensityTransition(); + + private native void nativeSetHeatmapIntensityTransition(long duration, long delay); + + private native Object nativeGetHeatmapColor(); + + private native Object nativeGetHeatmapOpacity(); + + private native TransitionOptions nativeGetHeatmapOpacityTransition(); + + private native void nativeSetHeatmapOpacityTransition(long duration, long delay); + + @Override + protected native void finalize() throws Throwable; + +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HillshadeLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HillshadeLayer.java new file mode 100644 index 0000000000..fb086f424b --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/HillshadeLayer.java @@ -0,0 +1,289 @@ +// This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`. + +package com.mapbox.mapboxsdk.style.layers; + +import android.support.annotation.ColorInt; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.UiThread; + +import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; + +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; +import com.mapbox.mapboxsdk.style.layers.TransitionOptions; + +/** + * Client-side hillshading visualization based on DEM data. Currently, the implementation only supports Mapbox Terrain RGB and Mapzen Terrarium tiles. + * + * @see <a href="https://www.mapbox.com/mapbox-gl-style-spec/#layers-hillshade">The online documentation</a> + */ +@UiThread +public class HillshadeLayer extends Layer { + + /** + * Creates a HillshadeLayer. + * + * @param nativePtr pointer used by core + */ + public HillshadeLayer(long nativePtr) { + super(nativePtr); + } + + /** + * Creates a HillshadeLayer. + * + * @param layerId the id of the layer + * @param sourceId the id of the source + */ + public HillshadeLayer(String layerId, String sourceId) { + initialize(layerId, sourceId); + } + + protected native void initialize(String layerId, String sourceId); + + /** + * Set the source layer. + * + * @param sourceLayer the source layer to set + */ + public void setSourceLayer(String sourceLayer) { + nativeSetSourceLayer(sourceLayer); + } + + /** + * Set the source Layer. + * + * @param sourceLayer the source layer to set + * @return This + */ + public HillshadeLayer withSourceLayer(String sourceLayer) { + setSourceLayer(sourceLayer); + return this; + } + + /** + * Set a property or properties. + * + * @param properties the var-args properties + * @return This + */ + public HillshadeLayer withProperties(@NonNull PropertyValue<?>... properties) { + setProperties(properties); + return this; + } + + // Property getters + + /** + * Get the HillshadeIlluminationDirection property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHillshadeIlluminationDirection() { + return (PropertyValue<Float>) new PropertyValue("hillshade-illumination-direction", nativeGetHillshadeIlluminationDirection()); + } + + /** + * Get the HillshadeIlluminationAnchor property + * + * @return property wrapper value around String + */ + @SuppressWarnings("unchecked") + public PropertyValue<String> getHillshadeIlluminationAnchor() { + return (PropertyValue<String>) new PropertyValue("hillshade-illumination-anchor", nativeGetHillshadeIlluminationAnchor()); + } + + /** + * Get the HillshadeExaggeration property + * + * @return property wrapper value around Float + */ + @SuppressWarnings("unchecked") + public PropertyValue<Float> getHillshadeExaggeration() { + return (PropertyValue<Float>) new PropertyValue("hillshade-exaggeration", nativeGetHillshadeExaggeration()); + } + + /** + * Get the HillshadeExaggeration property transition options + * + * @return transition options for Float + */ + public TransitionOptions getHillshadeExaggerationTransition() { + return nativeGetHillshadeExaggerationTransition(); + } + + /** + * Set the HillshadeExaggeration property transition options + * + * @param options transition options for Float + */ + public void setHillshadeExaggerationTransition(TransitionOptions options) { + nativeSetHillshadeExaggerationTransition(options.getDuration(), options.getDelay()); + } + + /** + * Get the HillshadeShadowColor property + * + * @return property wrapper value around String + */ + @SuppressWarnings("unchecked") + public PropertyValue<String> getHillshadeShadowColor() { + return (PropertyValue<String>) new PropertyValue("hillshade-shadow-color", nativeGetHillshadeShadowColor()); + } + + /** + * The shading color of areas that face away from the light source. + * + * @return int representation of a rgba string color + * @throws RuntimeException thrown if property isn't a value + */ + @ColorInt + public int getHillshadeShadowColorAsInt() { + PropertyValue<String> value = getHillshadeShadowColor(); + if (value.isValue()) { + return rgbaToColor(value.getValue()); + } else { + throw new RuntimeException("hillshade-shadow-color was set as a Function"); + } + } + + /** + * Get the HillshadeShadowColor property transition options + * + * @return transition options for String + */ + public TransitionOptions getHillshadeShadowColorTransition() { + return nativeGetHillshadeShadowColorTransition(); + } + + /** + * Set the HillshadeShadowColor property transition options + * + * @param options transition options for String + */ + public void setHillshadeShadowColorTransition(TransitionOptions options) { + nativeSetHillshadeShadowColorTransition(options.getDuration(), options.getDelay()); + } + + /** + * Get the HillshadeHighlightColor property + * + * @return property wrapper value around String + */ + @SuppressWarnings("unchecked") + public PropertyValue<String> getHillshadeHighlightColor() { + return (PropertyValue<String>) new PropertyValue("hillshade-highlight-color", nativeGetHillshadeHighlightColor()); + } + + /** + * The shading color of areas that faces towards the light source. + * + * @return int representation of a rgba string color + * @throws RuntimeException thrown if property isn't a value + */ + @ColorInt + public int getHillshadeHighlightColorAsInt() { + PropertyValue<String> value = getHillshadeHighlightColor(); + if (value.isValue()) { + return rgbaToColor(value.getValue()); + } else { + throw new RuntimeException("hillshade-highlight-color was set as a Function"); + } + } + + /** + * Get the HillshadeHighlightColor property transition options + * + * @return transition options for String + */ + public TransitionOptions getHillshadeHighlightColorTransition() { + return nativeGetHillshadeHighlightColorTransition(); + } + + /** + * Set the HillshadeHighlightColor property transition options + * + * @param options transition options for String + */ + public void setHillshadeHighlightColorTransition(TransitionOptions options) { + nativeSetHillshadeHighlightColorTransition(options.getDuration(), options.getDelay()); + } + + /** + * Get the HillshadeAccentColor property + * + * @return property wrapper value around String + */ + @SuppressWarnings("unchecked") + public PropertyValue<String> getHillshadeAccentColor() { + return (PropertyValue<String>) new PropertyValue("hillshade-accent-color", nativeGetHillshadeAccentColor()); + } + + /** + * The shading color used to accentuate rugged terrain like sharp cliffs and gorges. + * + * @return int representation of a rgba string color + * @throws RuntimeException thrown if property isn't a value + */ + @ColorInt + public int getHillshadeAccentColorAsInt() { + PropertyValue<String> value = getHillshadeAccentColor(); + if (value.isValue()) { + return rgbaToColor(value.getValue()); + } else { + throw new RuntimeException("hillshade-accent-color was set as a Function"); + } + } + + /** + * Get the HillshadeAccentColor property transition options + * + * @return transition options for String + */ + public TransitionOptions getHillshadeAccentColorTransition() { + return nativeGetHillshadeAccentColorTransition(); + } + + /** + * Set the HillshadeAccentColor property transition options + * + * @param options transition options for String + */ + public void setHillshadeAccentColorTransition(TransitionOptions options) { + nativeSetHillshadeAccentColorTransition(options.getDuration(), options.getDelay()); + } + + private native Object nativeGetHillshadeIlluminationDirection(); + + private native Object nativeGetHillshadeIlluminationAnchor(); + + private native Object nativeGetHillshadeExaggeration(); + + private native TransitionOptions nativeGetHillshadeExaggerationTransition(); + + private native void nativeSetHillshadeExaggerationTransition(long duration, long delay); + + private native Object nativeGetHillshadeShadowColor(); + + private native TransitionOptions nativeGetHillshadeShadowColorTransition(); + + private native void nativeSetHillshadeShadowColorTransition(long duration, long delay); + + private native Object nativeGetHillshadeHighlightColor(); + + private native TransitionOptions nativeGetHillshadeHighlightColorTransition(); + + private native void nativeSetHillshadeHighlightColorTransition(long duration, long delay); + + private native Object nativeGetHillshadeAccentColor(); + + private native TransitionOptions nativeGetHillshadeAccentColorTransition(); + + private native void nativeSetHillshadeAccentColorTransition(long duration, long delay); + + @Override + protected native void finalize() throws Throwable; + +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Layer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Layer.java index 5015dd009d..411fbe4435 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Layer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Layer.java @@ -2,7 +2,9 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.style.functions.Function; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.mapbox.mapboxsdk.style.expressions.Expression; /** * Base class for the different Layer types @@ -71,6 +73,8 @@ public abstract class Layer { protected native void nativeSetFilter(Object[] filter); + protected native JsonElement nativeGetFilter(); + protected native void nativeSetSourceLayer(String sourceLayer); protected native String nativeGetSourceLayer(); @@ -88,6 +92,10 @@ public abstract class Layer { } private Object convertValue(Object value) { - return value != null && value instanceof Function ? ((Function) value).toValueObject() : value; + if (value != null && value instanceof Expression) { + return ((Expression) value).toArray(); + } + return value; } -} + +}
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/LineLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/LineLayer.java index ca106cc106..5e6e6d38e7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/LineLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/LineLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -69,26 +72,41 @@ public class LineLayer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public LineLayer withFilter(Filter.Statement filter) { + public LineLayer withFilter(Expression filter) { setFilter(filter); return this; } /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** * Set a property or properties. * * @param properties the var-args properties diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Property.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Property.java index 8d5858217b..e52474c35b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Property.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Property.java @@ -402,7 +402,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface TEXT_TRANSFORM {} - // FILL_TRANSLATE_ANCHOR: Controls the translation reference point. + // FILL_TRANSLATE_ANCHOR: Controls the frame of reference for `fill-translate`. /** * The fill is translated relative to the map. @@ -414,7 +414,7 @@ public final class Property { public static final String FILL_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `fill-translate`. */ @StringDef({ FILL_TRANSLATE_ANCHOR_MAP, @@ -423,7 +423,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface FILL_TRANSLATE_ANCHOR {} - // LINE_TRANSLATE_ANCHOR: Controls the translation reference point. + // LINE_TRANSLATE_ANCHOR: Controls the frame of reference for `line-translate`. /** * The line is translated relative to the map. @@ -435,7 +435,7 @@ public final class Property { public static final String LINE_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `line-translate`. */ @StringDef({ LINE_TRANSLATE_ANCHOR_MAP, @@ -444,7 +444,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface LINE_TRANSLATE_ANCHOR {} - // ICON_TRANSLATE_ANCHOR: Controls the translation reference point. + // ICON_TRANSLATE_ANCHOR: Controls the frame of reference for `icon-translate`. /** * Icons are translated relative to the map. @@ -456,7 +456,7 @@ public final class Property { public static final String ICON_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `icon-translate`. */ @StringDef({ ICON_TRANSLATE_ANCHOR_MAP, @@ -465,7 +465,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface ICON_TRANSLATE_ANCHOR {} - // TEXT_TRANSLATE_ANCHOR: Controls the translation reference point. + // TEXT_TRANSLATE_ANCHOR: Controls the frame of reference for `text-translate`. /** * The text is translated relative to the map. @@ -477,7 +477,7 @@ public final class Property { public static final String TEXT_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `text-translate`. */ @StringDef({ TEXT_TRANSLATE_ANCHOR_MAP, @@ -486,7 +486,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface TEXT_TRANSLATE_ANCHOR {} - // CIRCLE_TRANSLATE_ANCHOR: Controls the translation reference point. + // CIRCLE_TRANSLATE_ANCHOR: Controls the frame of reference for `circle-translate`. /** * The circle is translated relative to the map. @@ -498,7 +498,7 @@ public final class Property { public static final String CIRCLE_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `circle-translate`. */ @StringDef({ CIRCLE_TRANSLATE_ANCHOR_MAP, @@ -549,7 +549,7 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface CIRCLE_PITCH_ALIGNMENT {} - // FILL_EXTRUSION_TRANSLATE_ANCHOR: Controls the translation reference point. + // FILL_EXTRUSION_TRANSLATE_ANCHOR: Controls the frame of reference for `fill-extrusion-translate`. /** * The fill extrusion is translated relative to the map. @@ -561,7 +561,7 @@ public final class Property { public static final String FILL_EXTRUSION_TRANSLATE_ANCHOR_VIEWPORT = "viewport"; /** - * Controls the translation reference point. + * Controls the frame of reference for `fill-extrusion-translate`. */ @StringDef({ FILL_EXTRUSION_TRANSLATE_ANCHOR_MAP, @@ -570,6 +570,27 @@ public final class Property { @Retention(RetentionPolicy.SOURCE) public @interface FILL_EXTRUSION_TRANSLATE_ANCHOR {} + // HILLSHADE_ILLUMINATION_ANCHOR: Direction of light source when map is rotated. + + /** + * The hillshade illumination is relative to the north direction. + */ + public static final String HILLSHADE_ILLUMINATION_ANCHOR_MAP = "map"; + /** + * The hillshade illumination is relative to the top of the viewport. + */ + public static final String HILLSHADE_ILLUMINATION_ANCHOR_VIEWPORT = "viewport"; + + /** + * Direction of light source when map is rotated. + */ + @StringDef({ + HILLSHADE_ILLUMINATION_ANCHOR_MAP, + HILLSHADE_ILLUMINATION_ANCHOR_VIEWPORT, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface HILLSHADE_ILLUMINATION_ANCHOR {} + // ANCHOR: Whether extruded geometries are lit relative to the map or viewport. /** diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyFactory.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyFactory.java index c43977aec6..1dd8eddab9 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyFactory.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyFactory.java @@ -2,11 +2,9 @@ package com.mapbox.mapboxsdk.style.layers; -import android.annotation.SuppressLint; import android.support.annotation.ColorInt; -import com.mapbox.mapboxsdk.style.functions.Function; -import com.mapbox.mapboxsdk.style.functions.CameraFunction; +import com.mapbox.mapboxsdk.style.expressions.Expression; import java.util.Locale; @@ -28,17 +26,6 @@ public class PropertyFactory { } /** - * Set the property visibility. - * - * @param <T> the function input type - * @param function the visibility function - * @return property wrapper around a String function - */ - public static <T> PropertyValue<Function<T, String>> visibility(Function<T, String> function) { - return new LayoutPropertyValue<>("visibility", function); - } - - /** * Whether or not the fill should be antialiased. * * @param value a Boolean value @@ -48,16 +35,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-antialias", value); } - /** * Whether or not the fill should be antialiased. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> fillAntialias(CameraFunction<Z, Boolean> function) { - return new PaintPropertyValue<>("fill-antialias", function); + public static PropertyValue<Expression> fillAntialias(Expression expression) { + return new PaintPropertyValue<>("fill-antialias", expression); } /** @@ -70,16 +55,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-opacity", value); } - /** * The opacity of the entire fill layer. In contrast to the {@link PropertyFactory#fillColor}, this value will also affect the 1px stroke around the fill, if the stroke is used. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> fillOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("fill-opacity", function); + public static PropertyValue<Expression> fillOpacity(Expression expression) { + return new PaintPropertyValue<>("fill-opacity", expression); } /** @@ -102,16 +85,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-color", value); } - /** * The color of the filled part of this layer. This color can be specified as `rgba` with an alpha component and the color's opacity will not affect the opacity of the 1px stroke, if it is used. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> fillColor(Function<T, String> function) { - return new PaintPropertyValue<>("fill-color", function); + public static PropertyValue<Expression> fillColor(Expression expression) { + return new PaintPropertyValue<>("fill-color", expression); } /** @@ -134,16 +115,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-outline-color", value); } - /** * The outline color of the fill. Matches the value of {@link PropertyFactory#fillColor} if unspecified. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> fillOutlineColor(Function<T, String> function) { - return new PaintPropertyValue<>("fill-outline-color", function); + public static PropertyValue<Expression> fillOutlineColor(Expression expression) { + return new PaintPropertyValue<>("fill-outline-color", expression); } /** @@ -156,20 +135,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-translate", value); } - /** * The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> fillTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("fill-translate", function); + public static PropertyValue<Expression> fillTranslate(Expression expression) { + return new PaintPropertyValue<>("fill-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#fillTranslate}. * * @param value a String value * @return property wrapper around String @@ -178,20 +155,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#fillTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> fillTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("fill-translate-anchor", function); + public static PropertyValue<Expression> fillTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("fill-translate-anchor", expression); } /** - * Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * * @param value a String value * @return property wrapper around String @@ -200,16 +175,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-pattern", value); } - /** - * Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> fillPattern(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("fill-pattern", function); + public static PropertyValue<Expression> fillPattern(Expression expression) { + return new PaintPropertyValue<>("fill-pattern", expression); } /** @@ -222,16 +195,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-opacity", value); } - /** * The opacity at which the line will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> lineOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("line-opacity", function); + public static PropertyValue<Expression> lineOpacity(Expression expression) { + return new PaintPropertyValue<>("line-opacity", expression); } /** @@ -254,16 +225,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-color", value); } - /** * The color with which the line will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> lineColor(Function<T, String> function) { - return new PaintPropertyValue<>("line-color", function); + public static PropertyValue<Expression> lineColor(Expression expression) { + return new PaintPropertyValue<>("line-color", expression); } /** @@ -276,20 +245,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-translate", value); } - /** * The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> lineTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("line-translate", function); + public static PropertyValue<Expression> lineTranslate(Expression expression) { + return new PaintPropertyValue<>("line-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#lineTranslate}. * * @param value a String value * @return property wrapper around String @@ -298,16 +265,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#lineTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> lineTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("line-translate-anchor", function); + public static PropertyValue<Expression> lineTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("line-translate-anchor", expression); } /** @@ -320,16 +285,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-width", value); } - /** * Stroke thickness. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> lineWidth(Function<T, Float> function) { - return new PaintPropertyValue<>("line-width", function); + public static PropertyValue<Expression> lineWidth(Expression expression) { + return new PaintPropertyValue<>("line-width", expression); } /** @@ -342,16 +305,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-gap-width", value); } - /** * Draws a line casing outside of a line's actual path. Value indicates the width of the inner gap. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> lineGapWidth(Function<T, Float> function) { - return new PaintPropertyValue<>("line-gap-width", function); + public static PropertyValue<Expression> lineGapWidth(Expression expression) { + return new PaintPropertyValue<>("line-gap-width", expression); } /** @@ -364,16 +325,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-offset", value); } - /** * The line's offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> lineOffset(Function<T, Float> function) { - return new PaintPropertyValue<>("line-offset", function); + public static PropertyValue<Expression> lineOffset(Expression expression) { + return new PaintPropertyValue<>("line-offset", expression); } /** @@ -386,20 +345,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-blur", value); } - /** * Blur applied to the line, in density-independent pixels. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> lineBlur(Function<T, Float> function) { - return new PaintPropertyValue<>("line-blur", function); + public static PropertyValue<Expression> lineBlur(Expression expression) { + return new PaintPropertyValue<>("line-blur", expression); } /** - * Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to density-independent pixels, multiply the length by the current line width. + * Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to density-independent pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels. * * @param value a Float[] value * @return property wrapper around Float[] @@ -408,20 +365,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-dasharray", value); } - /** - * Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to density-independent pixels, multiply the length by the current line width. + * Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to density-independent pixels, multiply the length by the current line width. Note that GeoJSON sources with `lineMetrics: true` specified won't render dashed lines to the expected scale. Also note that zoom-dependent expressions will be evaluated only at integer zoom levels. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> lineDasharray(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("line-dasharray", function); + public static PropertyValue<Expression> lineDasharray(Expression expression) { + return new PaintPropertyValue<>("line-dasharray", expression); } /** - * Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * * @param value a String value * @return property wrapper around String @@ -430,16 +385,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("line-pattern", value); } - /** - * Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> linePattern(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("line-pattern", function); + public static PropertyValue<Expression> linePattern(Expression expression) { + return new PaintPropertyValue<>("line-pattern", expression); } /** @@ -452,16 +405,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-opacity", value); } - /** * The opacity at which the icon will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> iconOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("icon-opacity", function); + public static PropertyValue<Expression> iconOpacity(Expression expression) { + return new PaintPropertyValue<>("icon-opacity", expression); } /** @@ -484,16 +435,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-color", value); } - /** * The color of the icon. This can only be used with sdf icons. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> iconColor(Function<T, String> function) { - return new PaintPropertyValue<>("icon-color", function); + public static PropertyValue<Expression> iconColor(Expression expression) { + return new PaintPropertyValue<>("icon-color", expression); } /** @@ -516,16 +465,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-halo-color", value); } - /** * The color of the icon's halo. Icon halos can only be used with SDF icons. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> iconHaloColor(Function<T, String> function) { - return new PaintPropertyValue<>("icon-halo-color", function); + public static PropertyValue<Expression> iconHaloColor(Expression expression) { + return new PaintPropertyValue<>("icon-halo-color", expression); } /** @@ -538,16 +485,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-halo-width", value); } - /** * Distance of halo to the icon outline. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> iconHaloWidth(Function<T, Float> function) { - return new PaintPropertyValue<>("icon-halo-width", function); + public static PropertyValue<Expression> iconHaloWidth(Expression expression) { + return new PaintPropertyValue<>("icon-halo-width", expression); } /** @@ -560,16 +505,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-halo-blur", value); } - /** * Fade out the halo towards the outside. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> iconHaloBlur(Function<T, Float> function) { - return new PaintPropertyValue<>("icon-halo-blur", function); + public static PropertyValue<Expression> iconHaloBlur(Expression expression) { + return new PaintPropertyValue<>("icon-halo-blur", expression); } /** @@ -582,20 +525,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-translate", value); } - /** * Distance that the icon's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> iconTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("icon-translate", function); + public static PropertyValue<Expression> iconTranslate(Expression expression) { + return new PaintPropertyValue<>("icon-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#iconTranslate}. * * @param value a String value * @return property wrapper around String @@ -604,16 +545,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("icon-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#iconTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> iconTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("icon-translate-anchor", function); + public static PropertyValue<Expression> iconTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("icon-translate-anchor", expression); } /** @@ -626,16 +565,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-opacity", value); } - /** * The opacity at which the text will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> textOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("text-opacity", function); + public static PropertyValue<Expression> textOpacity(Expression expression) { + return new PaintPropertyValue<>("text-opacity", expression); } /** @@ -658,16 +595,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-color", value); } - /** * The color with which the text will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> textColor(Function<T, String> function) { - return new PaintPropertyValue<>("text-color", function); + public static PropertyValue<Expression> textColor(Expression expression) { + return new PaintPropertyValue<>("text-color", expression); } /** @@ -690,16 +625,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-halo-color", value); } - /** * The color of the text's halo, which helps it stand out from backgrounds. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> textHaloColor(Function<T, String> function) { - return new PaintPropertyValue<>("text-halo-color", function); + public static PropertyValue<Expression> textHaloColor(Expression expression) { + return new PaintPropertyValue<>("text-halo-color", expression); } /** @@ -712,16 +645,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-halo-width", value); } - /** * Distance of halo to the font outline. Max text halo width is 1/4 of the font-size. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> textHaloWidth(Function<T, Float> function) { - return new PaintPropertyValue<>("text-halo-width", function); + public static PropertyValue<Expression> textHaloWidth(Expression expression) { + return new PaintPropertyValue<>("text-halo-width", expression); } /** @@ -734,16 +665,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-halo-blur", value); } - /** * The halo's fadeout distance towards the outside. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> textHaloBlur(Function<T, Float> function) { - return new PaintPropertyValue<>("text-halo-blur", function); + public static PropertyValue<Expression> textHaloBlur(Expression expression) { + return new PaintPropertyValue<>("text-halo-blur", expression); } /** @@ -756,20 +685,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-translate", value); } - /** * Distance that the text's anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> textTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("text-translate", function); + public static PropertyValue<Expression> textTranslate(Expression expression) { + return new PaintPropertyValue<>("text-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#textTranslate}. * * @param value a String value * @return property wrapper around String @@ -778,16 +705,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("text-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#textTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> textTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("text-translate-anchor", function); + public static PropertyValue<Expression> textTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("text-translate-anchor", expression); } /** @@ -800,16 +725,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-radius", value); } - /** * Circle radius. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> circleRadius(Function<T, Float> function) { - return new PaintPropertyValue<>("circle-radius", function); + public static PropertyValue<Expression> circleRadius(Expression expression) { + return new PaintPropertyValue<>("circle-radius", expression); } /** @@ -832,16 +755,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-color", value); } - /** * The fill color of the circle. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> circleColor(Function<T, String> function) { - return new PaintPropertyValue<>("circle-color", function); + public static PropertyValue<Expression> circleColor(Expression expression) { + return new PaintPropertyValue<>("circle-color", expression); } /** @@ -854,16 +775,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-blur", value); } - /** * Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> circleBlur(Function<T, Float> function) { - return new PaintPropertyValue<>("circle-blur", function); + public static PropertyValue<Expression> circleBlur(Expression expression) { + return new PaintPropertyValue<>("circle-blur", expression); } /** @@ -876,16 +795,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-opacity", value); } - /** * The opacity at which the circle will be drawn. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> circleOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("circle-opacity", function); + public static PropertyValue<Expression> circleOpacity(Expression expression) { + return new PaintPropertyValue<>("circle-opacity", expression); } /** @@ -898,20 +815,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-translate", value); } - /** * The geometry's offset. Values are [x, y] where negatives indicate left and up, respectively. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> circleTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("circle-translate", function); + public static PropertyValue<Expression> circleTranslate(Expression expression) { + return new PaintPropertyValue<>("circle-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#circleTranslate}. * * @param value a String value * @return property wrapper around String @@ -920,16 +835,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#circleTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> circleTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("circle-translate-anchor", function); + public static PropertyValue<Expression> circleTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("circle-translate-anchor", expression); } /** @@ -942,16 +855,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-pitch-scale", value); } - /** * Controls the scaling behavior of the circle when the map is pitched. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> circlePitchScale(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("circle-pitch-scale", function); + public static PropertyValue<Expression> circlePitchScale(Expression expression) { + return new PaintPropertyValue<>("circle-pitch-scale", expression); } /** @@ -964,16 +875,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-pitch-alignment", value); } - /** * Orientation of circle when map is pitched. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> circlePitchAlignment(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("circle-pitch-alignment", function); + public static PropertyValue<Expression> circlePitchAlignment(Expression expression) { + return new PaintPropertyValue<>("circle-pitch-alignment", expression); } /** @@ -986,16 +895,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-stroke-width", value); } - /** * The width of the circle's stroke. Strokes are placed outside of the {@link PropertyFactory#circleRadius}. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> circleStrokeWidth(Function<T, Float> function) { - return new PaintPropertyValue<>("circle-stroke-width", function); + public static PropertyValue<Expression> circleStrokeWidth(Expression expression) { + return new PaintPropertyValue<>("circle-stroke-width", expression); } /** @@ -1018,16 +925,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-stroke-color", value); } - /** * The stroke color of the circle. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> circleStrokeColor(Function<T, String> function) { - return new PaintPropertyValue<>("circle-stroke-color", function); + public static PropertyValue<Expression> circleStrokeColor(Expression expression) { + return new PaintPropertyValue<>("circle-stroke-color", expression); } /** @@ -1040,16 +945,124 @@ public class PropertyFactory { return new PaintPropertyValue<>("circle-stroke-opacity", value); } - /** * The opacity of the circle's stroke. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> circleStrokeOpacity(Expression expression) { + return new PaintPropertyValue<>("circle-stroke-opacity", expression); + } + + /** + * Radius of influence of one heatmap point in density-independent pixels. Increasing the value makes the heatmap smoother, but less detailed. + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> heatmapRadius(Float value) { + return new PaintPropertyValue<>("heatmap-radius", value); + } + + /** + * Radius of influence of one heatmap point in density-independent pixels. Increasing the value makes the heatmap smoother, but less detailed. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> heatmapRadius(Expression expression) { + return new PaintPropertyValue<>("heatmap-radius", expression); + } + + /** + * A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering. + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> heatmapWeight(Float value) { + return new PaintPropertyValue<>("heatmap-weight", value); + } + + /** + * A measure of how much an individual point contributes to the heatmap. A value of 10 would be equivalent to having 10 points of weight 1 in the same spot. Especially useful when combined with clustering. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> heatmapWeight(Expression expression) { + return new PaintPropertyValue<>("heatmap-weight", expression); + } + + /** + * Similar to {@link PropertyFactory#heatmapWeight} but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level. + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> heatmapIntensity(Float value) { + return new PaintPropertyValue<>("heatmap-intensity", value); + } + + /** + * Similar to {@link PropertyFactory#heatmapWeight} but controls the intensity of the heatmap globally. Primarily used for adjusting the heatmap based on zoom level. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> heatmapIntensity(Expression expression) { + return new PaintPropertyValue<>("heatmap-intensity", expression); + } + + /** + * Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `["heatmap-density"]` as input. + * + * @param value a int color value + * @return property wrapper around String color + */ + public static PropertyValue<String> heatmapColor(@ColorInt int value) { + return new PaintPropertyValue<>("heatmap-color", colorToRgbaString(value)); + } + + /** + * Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `["heatmap-density"]` as input. + * + * @param value a String value + * @return property wrapper around String + */ + public static PropertyValue<String> heatmapColor(String value) { + return new PaintPropertyValue<>("heatmap-color", value); + } + + /** + * Defines the color of each pixel based on its density value in a heatmap. Should be an expression that uses `["heatmap-density"]` as input. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> heatmapColor(Expression expression) { + return new PaintPropertyValue<>("heatmap-color", expression); + } + + /** + * The global opacity at which the heatmap layer will be drawn. + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> heatmapOpacity(Float value) { + return new PaintPropertyValue<>("heatmap-opacity", value); + } + + /** + * The global opacity at which the heatmap layer will be drawn. + * + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> circleStrokeOpacity(Function<T, Float> function) { - return new PaintPropertyValue<>("circle-stroke-opacity", function); + public static PropertyValue<Expression> heatmapOpacity(Expression expression) { + return new PaintPropertyValue<>("heatmap-opacity", expression); } /** @@ -1062,16 +1075,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-opacity", value); } - /** * The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> fillExtrusionOpacity(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("fill-extrusion-opacity", function); + public static PropertyValue<Expression> fillExtrusionOpacity(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-opacity", expression); } /** @@ -1094,16 +1105,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-color", value); } - /** * The base color of the extruded fill. The extrusion's surfaces will be shaded differently based on this color in combination with the root `light` settings. If this color is specified as `rgba` with an alpha component, the alpha component will be ignored; use {@link PropertyFactory#fillExtrusionOpacity} to set layer opacity. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, String>> fillExtrusionColor(Function<T, String> function) { - return new PaintPropertyValue<>("fill-extrusion-color", function); + public static PropertyValue<Expression> fillExtrusionColor(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-color", expression); } /** @@ -1116,20 +1125,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-translate", value); } - /** * The geometry's offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> fillExtrusionTranslate(CameraFunction<Z, Float[]> function) { - return new PaintPropertyValue<>("fill-extrusion-translate", function); + public static PropertyValue<Expression> fillExtrusionTranslate(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-translate", expression); } /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#fillExtrusionTranslate}. * * @param value a String value * @return property wrapper around String @@ -1138,20 +1145,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-translate-anchor", value); } - /** - * Controls the translation reference point. + * Controls the frame of reference for {@link PropertyFactory#fillExtrusionTranslate}. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> fillExtrusionTranslateAnchor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("fill-extrusion-translate-anchor", function); + public static PropertyValue<Expression> fillExtrusionTranslateAnchor(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-translate-anchor", expression); } /** - * Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * * @param value a String value * @return property wrapper around String @@ -1160,16 +1165,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-pattern", value); } - /** - * Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> fillExtrusionPattern(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("fill-extrusion-pattern", function); + public static PropertyValue<Expression> fillExtrusionPattern(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-pattern", expression); } /** @@ -1182,16 +1185,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-height", value); } - /** * The height with which to extrude this layer. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> fillExtrusionHeight(Function<T, Float> function) { - return new PaintPropertyValue<>("fill-extrusion-height", function); + public static PropertyValue<Expression> fillExtrusionHeight(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-height", expression); } /** @@ -1204,16 +1205,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("fill-extrusion-base", value); } - /** * The height with which to extrude the base of this layer. Must be less than or equal to {@link PropertyFactory#fillExtrusionHeight}. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <T> PropertyValue<Function<T, Float>> fillExtrusionBase(Function<T, Float> function) { - return new PaintPropertyValue<>("fill-extrusion-base", function); + public static PropertyValue<Expression> fillExtrusionBase(Expression expression) { + return new PaintPropertyValue<>("fill-extrusion-base", expression); } /** @@ -1226,16 +1225,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-opacity", value); } - /** * The opacity at which the image will be drawn. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterOpacity(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-opacity", function); + public static PropertyValue<Expression> rasterOpacity(Expression expression) { + return new PaintPropertyValue<>("raster-opacity", expression); } /** @@ -1248,16 +1245,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-hue-rotate", value); } - /** * Rotates hues around the color wheel. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterHueRotate(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-hue-rotate", function); + public static PropertyValue<Expression> rasterHueRotate(Expression expression) { + return new PaintPropertyValue<>("raster-hue-rotate", expression); } /** @@ -1270,16 +1265,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-brightness-min", value); } - /** * Increase or reduce the brightness of the image. The value is the minimum brightness. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterBrightnessMin(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-brightness-min", function); + public static PropertyValue<Expression> rasterBrightnessMin(Expression expression) { + return new PaintPropertyValue<>("raster-brightness-min", expression); } /** @@ -1292,16 +1285,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-brightness-max", value); } - /** * Increase or reduce the brightness of the image. The value is the maximum brightness. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterBrightnessMax(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-brightness-max", function); + public static PropertyValue<Expression> rasterBrightnessMax(Expression expression) { + return new PaintPropertyValue<>("raster-brightness-max", expression); } /** @@ -1314,16 +1305,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-saturation", value); } - /** * Increase or reduce the saturation of the image. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterSaturation(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-saturation", function); + public static PropertyValue<Expression> rasterSaturation(Expression expression) { + return new PaintPropertyValue<>("raster-saturation", expression); } /** @@ -1336,16 +1325,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-contrast", value); } - /** * Increase or reduce the contrast of the image. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterContrast(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-contrast", function); + public static PropertyValue<Expression> rasterContrast(Expression expression) { + return new PaintPropertyValue<>("raster-contrast", expression); } /** @@ -1358,16 +1345,164 @@ public class PropertyFactory { return new PaintPropertyValue<>("raster-fade-duration", value); } - /** * Fade duration when a new tile is added. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> rasterFadeDuration(Expression expression) { + return new PaintPropertyValue<>("raster-fade-duration", expression); + } + + /** + * The direction of the light source used to generate the hillshading with 0 as the top of the viewport if {@link Property.HILLSHADE_ILLUMINATION_ANCHOR} is set to `viewport` and due north if {@link Property.HILLSHADE_ILLUMINATION_ANCHOR} is set to `map`. + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> hillshadeIlluminationDirection(Float value) { + return new PaintPropertyValue<>("hillshade-illumination-direction", value); + } + + /** + * The direction of the light source used to generate the hillshading with 0 as the top of the viewport if {@link Property.HILLSHADE_ILLUMINATION_ANCHOR} is set to `viewport` and due north if {@link Property.HILLSHADE_ILLUMINATION_ANCHOR} is set to `map`. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> hillshadeIlluminationDirection(Expression expression) { + return new PaintPropertyValue<>("hillshade-illumination-direction", expression); + } + + /** + * Direction of light source when map is rotated. + * + * @param value a String value + * @return property wrapper around String + */ + public static PropertyValue<String> hillshadeIlluminationAnchor(@Property.HILLSHADE_ILLUMINATION_ANCHOR String value) { + return new PaintPropertyValue<>("hillshade-illumination-anchor", value); + } + + /** + * Direction of light source when map is rotated. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> hillshadeIlluminationAnchor(Expression expression) { + return new PaintPropertyValue<>("hillshade-illumination-anchor", expression); + } + + /** + * Intensity of the hillshade + * + * @param value a Float value + * @return property wrapper around Float + */ + public static PropertyValue<Float> hillshadeExaggeration(Float value) { + return new PaintPropertyValue<>("hillshade-exaggeration", value); + } + + /** + * Intensity of the hillshade + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> hillshadeExaggeration(Expression expression) { + return new PaintPropertyValue<>("hillshade-exaggeration", expression); + } + + /** + * The shading color of areas that face away from the light source. + * + * @param value a int color value + * @return property wrapper around String color + */ + public static PropertyValue<String> hillshadeShadowColor(@ColorInt int value) { + return new PaintPropertyValue<>("hillshade-shadow-color", colorToRgbaString(value)); + } + + /** + * The shading color of areas that face away from the light source. + * + * @param value a String value + * @return property wrapper around String + */ + public static PropertyValue<String> hillshadeShadowColor(String value) { + return new PaintPropertyValue<>("hillshade-shadow-color", value); + } + + /** + * The shading color of areas that face away from the light source. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> hillshadeShadowColor(Expression expression) { + return new PaintPropertyValue<>("hillshade-shadow-color", expression); + } + + /** + * The shading color of areas that faces towards the light source. + * + * @param value a int color value + * @return property wrapper around String color + */ + public static PropertyValue<String> hillshadeHighlightColor(@ColorInt int value) { + return new PaintPropertyValue<>("hillshade-highlight-color", colorToRgbaString(value)); + } + + /** + * The shading color of areas that faces towards the light source. + * + * @param value a String value + * @return property wrapper around String + */ + public static PropertyValue<String> hillshadeHighlightColor(String value) { + return new PaintPropertyValue<>("hillshade-highlight-color", value); + } + + /** + * The shading color of areas that faces towards the light source. + * + * @param expression an expression statement + * @return property wrapper around an expression statement + */ + public static PropertyValue<Expression> hillshadeHighlightColor(Expression expression) { + return new PaintPropertyValue<>("hillshade-highlight-color", expression); + } + + /** + * The shading color used to accentuate rugged terrain like sharp cliffs and gorges. + * + * @param value a int color value + * @return property wrapper around String color + */ + public static PropertyValue<String> hillshadeAccentColor(@ColorInt int value) { + return new PaintPropertyValue<>("hillshade-accent-color", colorToRgbaString(value)); + } + + /** + * The shading color used to accentuate rugged terrain like sharp cliffs and gorges. + * + * @param value a String value + * @return property wrapper around String + */ + public static PropertyValue<String> hillshadeAccentColor(String value) { + return new PaintPropertyValue<>("hillshade-accent-color", value); + } + + /** + * The shading color used to accentuate rugged terrain like sharp cliffs and gorges. + * + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> rasterFadeDuration(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("raster-fade-duration", function); + public static PropertyValue<Expression> hillshadeAccentColor(Expression expression) { + return new PaintPropertyValue<>("hillshade-accent-color", expression); } /** @@ -1390,20 +1525,18 @@ public class PropertyFactory { return new PaintPropertyValue<>("background-color", value); } - /** * The color with which the background will be drawn. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> backgroundColor(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("background-color", function); + public static PropertyValue<Expression> backgroundColor(Expression expression) { + return new PaintPropertyValue<>("background-color", expression); } /** - * Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * * @param value a String value * @return property wrapper around String @@ -1412,16 +1545,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("background-pattern", value); } - /** - * Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). + * Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, ..., 512). Note that zoom-dependent expressions will be evaluated only at integer zoom levels. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> backgroundPattern(CameraFunction<Z, String> function) { - return new PaintPropertyValue<>("background-pattern", function); + public static PropertyValue<Expression> backgroundPattern(Expression expression) { + return new PaintPropertyValue<>("background-pattern", expression); } /** @@ -1434,16 +1565,14 @@ public class PropertyFactory { return new PaintPropertyValue<>("background-opacity", value); } - /** * The opacity at which the background will be drawn. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> backgroundOpacity(CameraFunction<Z, Float> function) { - return new PaintPropertyValue<>("background-opacity", function); + public static PropertyValue<Expression> backgroundOpacity(Expression expression) { + return new PaintPropertyValue<>("background-opacity", expression); } /** @@ -1456,17 +1585,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("line-cap", value); } - - /** * The display of line endings. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> lineCap(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("line-cap", function); + public static PropertyValue<Expression> lineCap(Expression value) { + return new LayoutPropertyValue<>("line-cap", value); } /** @@ -1479,17 +1605,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("line-join", value); } - - /** * The display of lines when joining. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> lineJoin(Function<T, String> function) { - return new LayoutPropertyValue<>("line-join", function); + public static PropertyValue<Expression> lineJoin(Expression value) { + return new LayoutPropertyValue<>("line-join", value); } /** @@ -1502,17 +1625,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("line-miter-limit", value); } - - /** * Used to automatically convert miter joins to bevel joins for sharp angles. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> lineMiterLimit(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("line-miter-limit", function); + public static PropertyValue<Expression> lineMiterLimit(Expression value) { + return new LayoutPropertyValue<>("line-miter-limit", value); } /** @@ -1525,17 +1645,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("line-round-limit", value); } - - /** * Used to automatically convert round joins to miter joins for shallow angles. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> lineRoundLimit(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("line-round-limit", function); + public static PropertyValue<Expression> lineRoundLimit(Expression value) { + return new LayoutPropertyValue<>("line-round-limit", value); } /** @@ -1548,17 +1665,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("symbol-placement", value); } - - /** * Label placement relative to its geometry. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> symbolPlacement(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("symbol-placement", function); + public static PropertyValue<Expression> symbolPlacement(Expression value) { + return new LayoutPropertyValue<>("symbol-placement", value); } /** @@ -1571,17 +1685,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("symbol-spacing", value); } - - /** * Distance between two symbol anchors. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> symbolSpacing(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("symbol-spacing", function); + public static PropertyValue<Expression> symbolSpacing(Expression value) { + return new LayoutPropertyValue<>("symbol-spacing", value); } /** @@ -1594,17 +1705,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("symbol-avoid-edges", value); } - - /** * If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don't have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> symbolAvoidEdges(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("symbol-avoid-edges", function); + public static PropertyValue<Expression> symbolAvoidEdges(Expression value) { + return new LayoutPropertyValue<>("symbol-avoid-edges", value); } /** @@ -1617,17 +1725,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-allow-overlap", value); } - - /** * If true, the icon will be visible even if it collides with other previously drawn symbols. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> iconAllowOverlap(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("icon-allow-overlap", function); + public static PropertyValue<Expression> iconAllowOverlap(Expression value) { + return new LayoutPropertyValue<>("icon-allow-overlap", value); } /** @@ -1640,17 +1745,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-ignore-placement", value); } - - /** * If true, other symbols can be visible even if they collide with the icon. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> iconIgnorePlacement(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("icon-ignore-placement", function); + public static PropertyValue<Expression> iconIgnorePlacement(Expression value) { + return new LayoutPropertyValue<>("icon-ignore-placement", value); } /** @@ -1663,17 +1765,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-optional", value); } - - /** * If true, text will display without their corresponding icons when the icon collides with other symbols and the text does not. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> iconOptional(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("icon-optional", function); + public static PropertyValue<Expression> iconOptional(Expression value) { + return new LayoutPropertyValue<>("icon-optional", value); } /** @@ -1686,17 +1785,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-rotation-alignment", value); } - - /** * In combination with {@link Property.SYMBOL_PLACEMENT}, determines the rotation behavior of icons. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> iconRotationAlignment(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("icon-rotation-alignment", function); + public static PropertyValue<Expression> iconRotationAlignment(Expression value) { + return new LayoutPropertyValue<>("icon-rotation-alignment", value); } /** @@ -1709,17 +1805,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-size", value); } - - /** * Scales the original size of the icon by the provided factor. The new pixel size of the image will be the original pixel size multiplied by {@link PropertyFactory#iconSize}. 1 is the original size; 3 triples the size of the image. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> iconSize(Function<T, Float> function) { - return new LayoutPropertyValue<>("icon-size", function); + public static PropertyValue<Expression> iconSize(Expression value) { + return new LayoutPropertyValue<>("icon-size", value); } /** @@ -1732,17 +1825,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-text-fit", value); } - - /** * Scales the icon to fit around the associated text. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> iconTextFit(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("icon-text-fit", function); + public static PropertyValue<Expression> iconTextFit(Expression value) { + return new LayoutPropertyValue<>("icon-text-fit", value); } /** @@ -1755,21 +1845,18 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-text-fit-padding", value); } - - /** * Size of the additional area added to dimensions determined by {@link Property.ICON_TEXT_FIT}, in clockwise order: top, right, bottom, left. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float[] - * @return property wrapper around a Float[] function + * @param value a Float[] value + * @return property wrapper around Float[] */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float[]>> iconTextFitPadding(CameraFunction<Z, Float[]> function) { - return new LayoutPropertyValue<>("icon-text-fit-padding", function); + public static PropertyValue<Expression> iconTextFitPadding(Expression value) { + return new LayoutPropertyValue<>("icon-text-fit-padding", value); } /** - * Name of image in sprite to use for drawing an image background. A string with {tokens} replaced, referencing the data property to pull from. + * Name of image in sprite to use for drawing an image background. * * @param value a String value * @return property wrapper around String @@ -1778,17 +1865,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-image", value); } - - /** - * Name of image in sprite to use for drawing an image background. A string with {tokens} replaced, referencing the data property to pull from. + * Name of image in sprite to use for drawing an image background. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> iconImage(Function<T, String> function) { - return new LayoutPropertyValue<>("icon-image", function); + public static PropertyValue<Expression> iconImage(Expression value) { + return new LayoutPropertyValue<>("icon-image", value); } /** @@ -1801,17 +1885,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-rotate", value); } - - /** * Rotates the icon clockwise. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> iconRotate(Function<T, Float> function) { - return new LayoutPropertyValue<>("icon-rotate", function); + public static PropertyValue<Expression> iconRotate(Expression value) { + return new LayoutPropertyValue<>("icon-rotate", value); } /** @@ -1824,17 +1905,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-padding", value); } - - /** * Size of the additional area around the icon bounding box used for detecting symbol collisions. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> iconPadding(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("icon-padding", function); + public static PropertyValue<Expression> iconPadding(Expression value) { + return new LayoutPropertyValue<>("icon-padding", value); } /** @@ -1847,21 +1925,18 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-keep-upright", value); } - - /** * If true, the icon may be flipped to prevent it from being rendered upside-down. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> iconKeepUpright(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("icon-keep-upright", function); + public static PropertyValue<Expression> iconKeepUpright(Expression value) { + return new LayoutPropertyValue<>("icon-keep-upright", value); } /** - * Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. When combined with {@link PropertyFactory#iconRotate} the offset will be as if the rotated direction was up. + * Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of {@link PropertyFactory#iconSize} to obtain the final offset in density-independent pixels. When combined with {@link PropertyFactory#iconRotate} the offset will be as if the rotated direction was up. * * @param value a Float[] value * @return property wrapper around Float[] @@ -1870,17 +1945,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-offset", value); } - - /** - * Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. When combined with {@link PropertyFactory#iconRotate} the offset will be as if the rotated direction was up. + * Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. Each component is multiplied by the value of {@link PropertyFactory#iconSize} to obtain the final offset in density-independent pixels. When combined with {@link PropertyFactory#iconRotate} the offset will be as if the rotated direction was up. * - * @param <T> the function input type - * @param function a wrapper function for Float[] - * @return property wrapper around a Float[] function + * @param value a Float[] value + * @return property wrapper around Float[] */ - public static <T> PropertyValue<Function<T, Float[]>> iconOffset(Function<T, Float[]> function) { - return new LayoutPropertyValue<>("icon-offset", function); + public static PropertyValue<Expression> iconOffset(Expression value) { + return new LayoutPropertyValue<>("icon-offset", value); } /** @@ -1893,17 +1965,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-anchor", value); } - - /** * Part of the icon placed closest to the anchor. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> iconAnchor(Function<T, String> function) { - return new LayoutPropertyValue<>("icon-anchor", function); + public static PropertyValue<Expression> iconAnchor(Expression value) { + return new LayoutPropertyValue<>("icon-anchor", value); } /** @@ -1916,17 +1985,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("icon-pitch-alignment", value); } - - /** * Orientation of icon when map is pitched. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> iconPitchAlignment(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("icon-pitch-alignment", function); + public static PropertyValue<Expression> iconPitchAlignment(Expression value) { + return new LayoutPropertyValue<>("icon-pitch-alignment", value); } /** @@ -1939,17 +2005,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-pitch-alignment", value); } - - /** * Orientation of text when map is pitched. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> textPitchAlignment(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("text-pitch-alignment", function); + public static PropertyValue<Expression> textPitchAlignment(Expression value) { + return new LayoutPropertyValue<>("text-pitch-alignment", value); } /** @@ -1962,21 +2025,18 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-rotation-alignment", value); } - - /** * In combination with {@link Property.SYMBOL_PLACEMENT}, determines the rotation behavior of the individual glyphs forming the text. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String>> textRotationAlignment(CameraFunction<Z, String> function) { - return new LayoutPropertyValue<>("text-rotation-alignment", function); + public static PropertyValue<Expression> textRotationAlignment(Expression value) { + return new LayoutPropertyValue<>("text-rotation-alignment", value); } /** - * Value to use for a text label. Feature properties are specified using tokens like {field_name}. (Token replacement is only supported for literal {@link PropertyFactory#textField} values--not for property functions.) + * Value to use for a text label. * * @param value a String value * @return property wrapper around String @@ -1985,17 +2045,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-field", value); } - - /** - * Value to use for a text label. Feature properties are specified using tokens like {field_name}. (Token replacement is only supported for literal {@link PropertyFactory#textField} values--not for property functions.) + * Value to use for a text label. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> textField(Function<T, String> function) { - return new LayoutPropertyValue<>("text-field", function); + public static PropertyValue<Expression> textField(Expression value) { + return new LayoutPropertyValue<>("text-field", value); } /** @@ -2008,17 +2065,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-font", value); } - - /** * Font stack to use for displaying text. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for String[] - * @return property wrapper around a String[] function + * @param value a String[] value + * @return property wrapper around String[] */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, String[]>> textFont(CameraFunction<Z, String[]> function) { - return new LayoutPropertyValue<>("text-font", function); + public static PropertyValue<Expression> textFont(Expression value) { + return new LayoutPropertyValue<>("text-font", value); } /** @@ -2031,17 +2085,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-size", value); } - - /** * Font size. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> textSize(Function<T, Float> function) { - return new LayoutPropertyValue<>("text-size", function); + public static PropertyValue<Expression> textSize(Expression value) { + return new LayoutPropertyValue<>("text-size", value); } /** @@ -2054,17 +2105,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-max-width", value); } - - /** * The maximum line width for text wrapping. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> textMaxWidth(Function<T, Float> function) { - return new LayoutPropertyValue<>("text-max-width", function); + public static PropertyValue<Expression> textMaxWidth(Expression value) { + return new LayoutPropertyValue<>("text-max-width", value); } /** @@ -2077,17 +2125,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-line-height", value); } - - /** * Text leading value for multi-line text. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> textLineHeight(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("text-line-height", function); + public static PropertyValue<Expression> textLineHeight(Expression value) { + return new LayoutPropertyValue<>("text-line-height", value); } /** @@ -2100,17 +2145,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-letter-spacing", value); } - - /** * Text tracking amount. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> textLetterSpacing(Function<T, Float> function) { - return new LayoutPropertyValue<>("text-letter-spacing", function); + public static PropertyValue<Expression> textLetterSpacing(Expression value) { + return new LayoutPropertyValue<>("text-letter-spacing", value); } /** @@ -2123,17 +2165,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-justify", value); } - - /** * Text justification options. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> textJustify(Function<T, String> function) { - return new LayoutPropertyValue<>("text-justify", function); + public static PropertyValue<Expression> textJustify(Expression value) { + return new LayoutPropertyValue<>("text-justify", value); } /** @@ -2146,17 +2185,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-anchor", value); } - - /** * Part of the text placed closest to the anchor. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> textAnchor(Function<T, String> function) { - return new LayoutPropertyValue<>("text-anchor", function); + public static PropertyValue<Expression> textAnchor(Expression value) { + return new LayoutPropertyValue<>("text-anchor", value); } /** @@ -2169,17 +2205,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-max-angle", value); } - - /** * Maximum angle change between adjacent characters. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> textMaxAngle(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("text-max-angle", function); + public static PropertyValue<Expression> textMaxAngle(Expression value) { + return new LayoutPropertyValue<>("text-max-angle", value); } /** @@ -2192,17 +2225,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-rotate", value); } - - /** * Rotates the text clockwise. * - * @param <T> the function input type - * @param function a wrapper function for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <T> PropertyValue<Function<T, Float>> textRotate(Function<T, Float> function) { - return new LayoutPropertyValue<>("text-rotate", function); + public static PropertyValue<Expression> textRotate(Expression value) { + return new LayoutPropertyValue<>("text-rotate", value); } /** @@ -2215,17 +2245,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-padding", value); } - - /** * Size of the additional area around the text bounding box used for detecting symbol collisions. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Float - * @return property wrapper around a Float function + * @param value a Float value + * @return property wrapper around Float */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Float>> textPadding(CameraFunction<Z, Float> function) { - return new LayoutPropertyValue<>("text-padding", function); + public static PropertyValue<Expression> textPadding(Expression value) { + return new LayoutPropertyValue<>("text-padding", value); } /** @@ -2238,17 +2265,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-keep-upright", value); } - - /** * If true, the text may be flipped vertically to prevent it from being rendered upside-down. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> textKeepUpright(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("text-keep-upright", function); + public static PropertyValue<Expression> textKeepUpright(Expression value) { + return new LayoutPropertyValue<>("text-keep-upright", value); } /** @@ -2261,17 +2285,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-transform", value); } - - /** * Specifies how to capitalize text, similar to the CSS {@link PropertyFactory#textTransform} property. * - * @param <T> the function input type - * @param function a wrapper function for String - * @return property wrapper around a String function + * @param value a String value + * @return property wrapper around String */ - public static <T> PropertyValue<Function<T, String>> textTransform(Function<T, String> function) { - return new LayoutPropertyValue<>("text-transform", function); + public static PropertyValue<Expression> textTransform(Expression value) { + return new LayoutPropertyValue<>("text-transform", value); } /** @@ -2284,17 +2305,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-offset", value); } - - /** * Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. * - * @param <T> the function input type - * @param function a wrapper function for Float[] - * @return property wrapper around a Float[] function + * @param value a Float[] value + * @return property wrapper around Float[] */ - public static <T> PropertyValue<Function<T, Float[]>> textOffset(Function<T, Float[]> function) { - return new LayoutPropertyValue<>("text-offset", function); + public static PropertyValue<Expression> textOffset(Expression value) { + return new LayoutPropertyValue<>("text-offset", value); } /** @@ -2307,17 +2325,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-allow-overlap", value); } - - /** * If true, the text will be visible even if it collides with other previously drawn symbols. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> textAllowOverlap(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("text-allow-overlap", function); + public static PropertyValue<Expression> textAllowOverlap(Expression value) { + return new LayoutPropertyValue<>("text-allow-overlap", value); } /** @@ -2330,17 +2345,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-ignore-placement", value); } - - /** * If true, other symbols can be visible even if they collide with the text. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> textIgnorePlacement(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("text-ignore-placement", function); + public static PropertyValue<Expression> textIgnorePlacement(Expression value) { + return new LayoutPropertyValue<>("text-ignore-placement", value); } /** @@ -2353,16 +2365,14 @@ public class PropertyFactory { return new LayoutPropertyValue<>("text-optional", value); } - /** * If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not. * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for Boolean - * @return property wrapper around a Boolean function + * @param value a Boolean value + * @return property wrapper around Boolean */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, Boolean>> textOptional(CameraFunction<Z, Boolean> function) { - return new LayoutPropertyValue<>("text-optional", function); + public static PropertyValue<Expression> textOptional(Expression value) { + return new LayoutPropertyValue<>("text-optional", value); } public static String colorToRgbaString(@ColorInt int value) { diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyValue.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyValue.java index a57c440df4..fa1779a6c7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyValue.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyValue.java @@ -4,8 +4,9 @@ import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import com.google.gson.JsonArray; import com.mapbox.mapboxsdk.exceptions.ConversionException; -import com.mapbox.mapboxsdk.style.functions.Function; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.utils.ColorUtils; import timber.log.Timber; @@ -40,35 +41,39 @@ public class PropertyValue<T> { } /** - * Returns if this is a function. + * Returns if this is a expression. * - * @return true if is a function, false if not + * @return true if this is a expression, false if not */ - public boolean isFunction() { - return !isNull() && value instanceof Function; + public boolean isExpression() { + return !isNull() && value instanceof JsonArray; } /** - * Returns if this is a value. + * Get the expression of the property. * - * @return true if is a value, false if not + * @return the property expression */ - public boolean isValue() { - return !isNull() && !isFunction(); - } - @Nullable - public Function<?, T> getFunction() { - if (isFunction()) { - // noinspection unchecked - return (Function<?, T>) value; + public Expression getExpression() { + if (isExpression()) { + return Expression.Converter.convert((JsonArray) value); } else { - Timber.w("not a function, try value"); + Timber.w("not a expression, try value"); return null; } } /** + * Returns if this is a value. + * + * @return true if is a value, false if not + */ + public boolean isValue() { + return !isNull() && !isExpression(); + } + + /** * Get the value of the property. * * @return the property value @@ -77,7 +82,7 @@ public class PropertyValue<T> { public T getValue() { if (isValue()) { // noinspection unchecked - return (T) value; + return value; } else { Timber.w("not a value, try function"); return null; @@ -114,4 +119,4 @@ public class PropertyValue<T> { public String toString() { return String.format("%s: %s", name, value); } -} +}
\ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/RasterLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/RasterLayer.java index e67e71b61d..0c7948f62a 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/RasterLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/RasterLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -250,24 +253,6 @@ public class RasterLayer extends Layer { return (PropertyValue<Float>) new PropertyValue("raster-fade-duration", nativeGetRasterFadeDuration()); } - /** - * Get the RasterFadeDuration property transition options - * - * @return transition options for Float - */ - public TransitionOptions getRasterFadeDurationTransition() { - return nativeGetRasterFadeDurationTransition(); - } - - /** - * Set the RasterFadeDuration property transition options - * - * @param options transition options for Float - */ - public void setRasterFadeDurationTransition(TransitionOptions options) { - nativeSetRasterFadeDurationTransition(options.getDuration(), options.getDelay()); - } - private native Object nativeGetRasterOpacity(); private native TransitionOptions nativeGetRasterOpacityTransition(); @@ -306,10 +291,6 @@ public class RasterLayer extends Layer { private native Object nativeGetRasterFadeDuration(); - private native TransitionOptions nativeGetRasterFadeDurationTransition(); - - private native void nativeSetRasterFadeDurationTransition(long duration, long delay); - @Override protected native void finalize() throws Throwable; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/SymbolLayer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/SymbolLayer.java index d0fb82dce5..6a2e131d7d 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/SymbolLayer.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/SymbolLayer.java @@ -4,10 +4,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -69,26 +72,41 @@ public class SymbolLayer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public SymbolLayer withFilter(Filter.Statement filter) { + public SymbolLayer withFilter(Expression filter) { setFilter(filter); return this; } /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + + /** * Set a property or properties. * * @param properties the var-args properties diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/layer.java.ejs b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/layer.java.ejs index 56e0af8b45..851a85f3d6 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/layer.java.ejs +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/layer.java.ejs @@ -9,10 +9,13 @@ package com.mapbox.mapboxsdk.style.layers; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; +import android.support.annotation.Nullable; import android.support.annotation.UiThread; import static com.mapbox.mapboxsdk.utils.ColorUtils.rgbaToColor; +import com.google.gson.JsonArray; +import com.mapbox.mapboxsdk.style.expressions.Expression; import com.mapbox.mapboxsdk.style.layers.TransitionOptions; /** @@ -78,7 +81,7 @@ public class <%- camelize(type) %>Layer extends Layer { } <% } -%> -<% if (type !== 'background' && type !== 'raster') { -%> +<% if (type !== 'background' && type !== 'raster' && type !== 'hillshade') { -%> /** * Get the source layer. * @@ -89,25 +92,40 @@ public class <%- camelize(type) %>Layer extends Layer { } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set */ - public void setFilter(Filter.Statement filter) { + public void setFilter(Expression filter) { nativeSetFilter(filter.toArray()); } /** - * Set a single filter. + * Set a single expression filter. * - * @param filter the filter to set + * @param filter the expression filter to set * @return This */ - public <%- camelize(type) %>Layer withFilter(Filter.Statement filter) { + public <%- camelize(type) %>Layer withFilter(Expression filter) { setFilter(filter); return this; } + /** + * Get a single expression filter. + * + * @return the expression filter to get + */ + @Nullable + public Expression getFilter() { + Expression expression = null; + JsonArray array = (JsonArray) nativeGetFilter(); + if (array != null) { + expression = Expression.Converter.convert(array); + } + return expression; + } + <% } -%> /** * Set a property or properties. diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property_factory.java.ejs b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property_factory.java.ejs index 2d3421d1d9..6480dde3c8 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property_factory.java.ejs +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property_factory.java.ejs @@ -6,11 +6,11 @@ package com.mapbox.mapboxsdk.style.layers; -import android.annotation.SuppressLint; import android.support.annotation.ColorInt; -import com.mapbox.mapboxsdk.style.functions.Function; -import com.mapbox.mapboxsdk.style.functions.CameraFunction; +import com.mapbox.mapboxsdk.style.expressions.Expression; + +import java.util.Locale; /** * Constructs paint/layout properties for Layers @@ -29,17 +29,6 @@ public class PropertyFactory { return new LayoutPropertyValue<>("visibility", value); } - /** - * Set the property visibility. - * - * @param <T> the function input type - * @param function the visibility function - * @return property wrapper around a String function - */ - public static <T> PropertyValue<Function<T, String>> visibility(Function<T, String> function) { - return new LayoutPropertyValue<>("visibility", function); - } - <% for (const property of paintProperties) { -%> <% if (property.type == 'color') { -%> /** @@ -63,34 +52,17 @@ public class PropertyFactory { return new PaintPropertyValue<>("<%- property.name %>", value); } -<% if (supportsPropertyFunction(property)) { -%> - - /** - * <%- propertyFactoryMethodDoc(property) %> - * - * @param <T> the function input type - * @param function a wrapper function for <%- propertyType(property) %> - * @return property wrapper around a <%- propertyType(property) %> function - */ - public static <T> PropertyValue<Function<T, <%- propertyType(property) %>>> <%- camelizeWithLeadingLowercase(property.name) %>(Function<T, <%- propertyType(property) %>> function) { - return new PaintPropertyValue<>("<%- property.name %>", function); - } - -<% } else if (supportsZoomFunction(property)) { -%> - /** * <%- propertyFactoryMethodDoc(property) %> * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for <%- propertyType(property) %> - * @return property wrapper around a <%- propertyType(property) %> function + * @param expression an expression statement + * @return property wrapper around an expression statement */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, <%- propertyType(property) %>>> <%- camelizeWithLeadingLowercase(property.name) %>(CameraFunction<Z, <%- propertyType(property) %>> function) { - return new PaintPropertyValue<>("<%- property.name %>", function); + public static PropertyValue<Expression> <%- camelizeWithLeadingLowercase(property.name) %>(Expression expression) { + return new PaintPropertyValue<>("<%- property.name %>", expression); } <% } -%> -<% } -%> <% for (const property of layoutProperties) { -%> /** * <%- propertyFactoryMethodDoc(property) %> @@ -102,38 +74,20 @@ public class PropertyFactory { return new LayoutPropertyValue<>("<%- property.name %>", value); } - -<% if (supportsPropertyFunction(property)) { -%> - - /** - * <%- propertyFactoryMethodDoc(property) %> - * - * @param <T> the function input type - * @param function a wrapper function for <%- propertyType(property) %> - * @return property wrapper around a <%- propertyType(property) %> function - */ - public static <T> PropertyValue<Function<T, <%- propertyType(property) %>>> <%- camelizeWithLeadingLowercase(property.name) %>(Function<T, <%- propertyType(property) %>> function) { - return new LayoutPropertyValue<>("<%- property.name %>", function); - } - -<% } else if (supportsZoomFunction(property)) { -%> - /** * <%- propertyFactoryMethodDoc(property) %> * - * @param <Z> the zoom parameter type - * @param function a wrapper {@link CameraFunction} for <%- propertyType(property) %> - * @return property wrapper around a <%- propertyType(property) %> function + * @param value a <%- propertyType(property) %> value + * @return property wrapper around <%- propertyType(property) %> */ - public static <Z extends Number> PropertyValue<CameraFunction<Z, <%- propertyType(property) %>>> <%- camelizeWithLeadingLowercase(property.name) %>(CameraFunction<Z, <%- propertyType(property) %>> function) { - return new LayoutPropertyValue<>("<%- property.name %>", function); + public static PropertyValue<Expression> <%- camelizeWithLeadingLowercase(property.name) %>(Expression value) { + return new LayoutPropertyValue<>("<%- property.name %>", value); } <% } -%> -<% } -%> - @SuppressLint("DefaultLocale") public static String colorToRgbaString(@ColorInt int value) { - return String.format("rgba(%d, %d, %d, %d)", (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF, (value >> 24) & 0xFF); + return String.format(Locale.US,"rgba(%d, %d, %d, %d)", + (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF, (value >> 24) & 0xFF); } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Light.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Light.java index 8f23e7d01e..7df48001cc 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Light.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Light.java @@ -48,7 +48,7 @@ public class Light { } /** - * Set the Position property. Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below). + * Set the Position property. Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below). * * @param position of the light */ @@ -57,7 +57,7 @@ public class Light { } /** - * Get the Position property. Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below). + * Get the Position property. Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when `light.anchor` is set to `viewport` corresponds to the top of the viewport, or 0° when `light.anchor` is set to `map` corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below). * * @return position as Position */ diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Position.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Position.java index cd6218d3e2..00f8486a1c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Position.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Position.java @@ -5,11 +5,11 @@ package com.mapbox.mapboxsdk.style.light; * <p> * The position is constructed out of a radial coordinate, an azimuthal angle and a polar angle. * where the radial coordinate indicates the distance from the center of the base of an object to its light, the - * azimuthal angle indicates the position of the light relative to 0° (0° when + * azimuthal angle indicates the position of the light relative to 0° (0° when * {@link com.mapbox.mapboxsdk.style.layers.Property.ANCHOR} is set to viewport corresponds to the top of the - * viewport, or 0° when {@link com.mapbox.mapboxsdk.style.layers.Property.ANCHOR} is set to map corresponds to due + * viewport, or 0° when {@link com.mapbox.mapboxsdk.style.layers.Property.ANCHOR} is set to map corresponds to due * north, and degrees proceed clockwise), and polar indicates the height of the light - * (from 0°, directly above, to 180°, directly below). + * (from 0°, directly above, to 180°, directly below). */ public class Position { @@ -21,7 +21,7 @@ public class Position { * Creates a Position from a radial coordinate, an azimuthal angle and a polar angle. * * @param radialCoordinate the distance from the center of the base of an object to its light - * @param azimuthalAngle the position of the light relative to 0° + * @param azimuthalAngle the position of the light relative to 0° * @param polarAngle the height of the light */ public Position(float radialCoordinate, float azimuthalAngle, float polarAngle) { diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySource.java new file mode 100644 index 0000000000..21a34f6064 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySource.java @@ -0,0 +1,203 @@ +package com.mapbox.mapboxsdk.style.sources; + +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.annotation.UiThread; +import android.support.annotation.WorkerThread; + +import com.mapbox.geojson.Feature; +import com.mapbox.geojson.FeatureCollection; +import com.mapbox.mapboxsdk.geometry.LatLngBounds; +import com.mapbox.mapboxsdk.style.expressions.Expression; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Custom Vector Source, allows using FeatureCollections. + * + */ +@UiThread +public class CustomGeometrySource extends Source { + private ExecutorService executor; + private GeometryTileProvider provider; + private final Map<TileID, AtomicBoolean> cancelledTileRequests = new ConcurrentHashMap<>(); + + /** + * Create a CustomGeometrySource + * + * @param id The source id. + * @param provider The tile provider that returns geometry data for this source. + */ + public CustomGeometrySource(String id, GeometryTileProvider provider) { + this(id, provider, new CustomGeometrySourceOptions()); + } + + /** + * Create a CustomGeometrySource with non-default CustomGeometrySourceOptions. + * <p>Supported options are minZoom, maxZoom, buffer, and tolerance.</p> + * + * @param id The source id. + * @param provider The tile provider that returns geometry data for this source. + * @param options CustomGeometrySourceOptions. + */ + public CustomGeometrySource(String id, GeometryTileProvider provider, CustomGeometrySourceOptions options) { + this.provider = provider; + executor = Executors.newFixedThreadPool(4); + initialize(id, options); + } + + /** + * Invalidate previously provided features within a given bounds at all zoom levels. + * Invoking this method will result in new requests to `GeometryTileProvider` for regions + * that contain, include, or intersect with the provided bounds. + * + * @param bounds The region in which features should be invalidated at all zoom levels + */ + public void invalidateRegion(LatLngBounds bounds) { + nativeInvalidateBounds(bounds); + } + + /** + * Invalidate the geometry contents of a specific tile. Invoking this method will result + * in new requests to `GeometryTileProvider` for visible tiles. + * + * @param zoomLevel Tile zoom level. + * @param x Tile X coordinate. + * @param y Tile Y coordinate. + */ + public void invalidateTile(int zoomLevel, int x, int y) { + nativeInvalidateTile(zoomLevel, x, y); + } + + /** + * Set or update geometry contents of a specific tile. Use this method to update tiles + * for which `GeometryTileProvider` was previously invoked. This method can be called from + * background threads. + * + * @param zoomLevel Tile zoom level. + * @param x Tile X coordinate. + * @param y Tile Y coordinate. + * @param data Feature collection for the tile. + */ + public void setTileData(int zoomLevel, int x, int y, FeatureCollection data) { + nativeSetTileData(zoomLevel, x, y, data); + } + + /** + * Queries the source for features. + * + * @param filter an optional filter expression to filter the returned Features + * @return the features + */ + @NonNull + public List<Feature> querySourceFeatures(@Nullable Expression filter) { + Feature[] features = querySourceFeatures(filter != null ? filter.toArray() : null); + return features != null ? Arrays.asList(features) : new ArrayList<Feature>(); + } + + protected native void initialize(String sourceId, Object options); + + private native Feature[] querySourceFeatures(Object[] filter); + + private native void nativeSetTileData(int z, int x, int y, FeatureCollection data); + + private native void nativeInvalidateTile(int z, int x, int y); + + private native void nativeInvalidateBounds(LatLngBounds bounds); + + @Override + protected native void finalize() throws Throwable; + + private void setTileData(TileID tileId, FeatureCollection data) { + cancelledTileRequests.remove(tileId); + nativeSetTileData(tileId.z, tileId.x, tileId.y, data); + } + + @WorkerThread + private void fetchTile(int z, int x, int y) { + AtomicBoolean cancelFlag = new AtomicBoolean(false); + TileID tileID = new TileID(z, x, y); + cancelledTileRequests.put(tileID, cancelFlag); + GeometryTileRequest request = new GeometryTileRequest(tileID, provider, this, cancelFlag); + executor.execute(request); + } + + @WorkerThread + private void cancelTile(int z, int x, int y) { + AtomicBoolean cancelFlag = cancelledTileRequests.get(new TileID(z, x, y)); + if (cancelFlag != null) { + cancelFlag.compareAndSet(false, true); + } + } + + private static class TileID { + public int z; + public int x; + public int y; + + public TileID(int _z, int _x, int _y) { + z = _z; + x = _x; + y = _y; + } + + public int hashCode() { + return Arrays.hashCode(new int[]{z, x, y}); + } + + public boolean equals(Object object) { + if (object == this) { + return true; + } + + if (object == null || getClass() != object.getClass()) { + return false; + } + + if (object instanceof TileID) { + TileID other = (TileID)object; + return this.z == other.z && this.x == other.x && this.y == other.y; + } + return false; + } + } + + private static class GeometryTileRequest implements Runnable { + private TileID id; + private GeometryTileProvider provider; + private WeakReference<CustomGeometrySource> sourceRef; + private AtomicBoolean cancelled; + + public GeometryTileRequest(TileID _id, GeometryTileProvider p, + CustomGeometrySource _source, AtomicBoolean _cancelled) { + id = _id; + provider = p; + sourceRef = new WeakReference<>(_source); + cancelled = _cancelled; + } + + public void run() { + if (isCancelled()) { + return; + } + + FeatureCollection data = provider.getFeaturesForBounds(LatLngBounds.from(id.z, id.x, id.y), id.z); + CustomGeometrySource source = sourceRef.get(); + if (!isCancelled() && source != null && data != null) { + source.setTileData(id, data); + } + } + + private Boolean isCancelled() { + return cancelled.get(); + } + } +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySourceOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySourceOptions.java new file mode 100644 index 0000000000..4ada38c238 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/CustomGeometrySourceOptions.java @@ -0,0 +1,31 @@ +package com.mapbox.mapboxsdk.style.sources; + +/** + * Builder class for composing CustomGeometrySource objects. + */ +public class CustomGeometrySourceOptions extends GeoJsonOptions { + + /** + * If the data includes wrapped coordinates, setting this to true unwraps the coordinates. + * + * @param wrap defaults to false + * @return the current instance for chaining + */ + public CustomGeometrySourceOptions withWrap(boolean wrap) { + this.put("wrap", wrap); + return this; + } + + /** + * If the data includes geometry outside the tile boundaries, setting this to true clips the geometry + * to the tile boundaries. + * + * @param clip defaults to false + * @return the current instance for chaining + */ + public CustomGeometrySourceOptions withClip(boolean clip) { + this.put("clip", clip); + return this; + } + +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonOptions.java index 1a1711e547..79cde7429c 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonOptions.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonOptions.java @@ -13,6 +13,17 @@ public class GeoJsonOptions extends HashMap<String, Object> { /** * Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels). * + * @param minZoom the maximum zoom - Defaults to 18. + * @return the current instance for chaining + */ + public GeoJsonOptions withMinZoom(int minZoom) { + this.put("minzoom", minZoom); + return this; + } + + /** + * Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels). + * * @param maxZoom the maximum zoom - Defaults to 18. * @return the current instance for chaining */ diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonSource.java index 10ecb945ad..efacc18741 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonSource.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeoJsonSource.java @@ -4,10 +4,10 @@ import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; -import com.mapbox.mapboxsdk.style.layers.Filter; -import com.mapbox.services.commons.geojson.Feature; -import com.mapbox.services.commons.geojson.FeatureCollection; -import com.mapbox.services.commons.geojson.Geometry; +import com.mapbox.geojson.Feature; +import com.mapbox.geojson.FeatureCollection; +import com.mapbox.geojson.Geometry; +import com.mapbox.mapboxsdk.style.expressions.Expression; import java.net.URL; import java.util.ArrayList; @@ -187,7 +187,7 @@ public class GeoJsonSource extends Source { * * @param geometry the GeoJSON {@link Geometry} to set */ - public void setGeoJson(Geometry<?> geometry) { + public void setGeoJson(Geometry geometry) { nativeSetGeometry(geometry); } @@ -238,11 +238,11 @@ public class GeoJsonSource extends Source { /** * Queries the source for features. * - * @param filter an optional filter statement to filter the returned Features + * @param filter an optional filter expression to filter the returned Features * @return the features */ @NonNull - public List<Feature> querySourceFeatures(@Nullable Filter.Statement filter) { + public List<Feature> querySourceFeatures(@Nullable Expression filter) { Feature[] features = querySourceFeatures(filter != null ? filter.toArray() : null); return features != null ? Arrays.asList(features) : new ArrayList<Feature>(); } @@ -259,7 +259,7 @@ public class GeoJsonSource extends Source { private native void nativeSetFeature(Feature feature); - private native void nativeSetGeometry(Geometry<?> geometry); + private native void nativeSetGeometry(Geometry geometry); private native Feature[] querySourceFeatures(Object[] filter); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeometryTileProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeometryTileProvider.java new file mode 100644 index 0000000000..17e7f0f5e4 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/GeometryTileProvider.java @@ -0,0 +1,22 @@ +package com.mapbox.mapboxsdk.style.sources; + +import android.support.annotation.WorkerThread; + +import com.mapbox.geojson.FeatureCollection; +import com.mapbox.mapboxsdk.geometry.LatLngBounds; + +/** + * Interface that defines methods for working with {@link CustomGeometrySource}. + */ +public interface GeometryTileProvider { + + /*** + * Interface method called by {@link CustomGeometrySource} to request features for a tile. + * + * @param bounds {@link LatLngBounds} of the tile. + * @param zoomLevel Tile zoom level. + * @return Return a @{link FeatureCollection} to be displayed in the requested tile. + */ + @WorkerThread + FeatureCollection getFeaturesForBounds(LatLngBounds bounds, int zoomLevel); +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/RasterDemSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/RasterDemSource.java new file mode 100644 index 0000000000..ee6fc5d7b7 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/RasterDemSource.java @@ -0,0 +1,93 @@ +package com.mapbox.mapboxsdk.style.sources; + +import android.support.annotation.Nullable; +import android.support.annotation.UiThread; + +import java.net.URL; + +/** + * A raster DEM source. Currently only supports Mapbox Terrain RGB (mapbox://mapbox.terrain-rgb) + * + * @see <a href="https://www.mapbox.com/mapbox-gl-js/style-spec/#sources-raster-dem">The style specification</a> + */ +@UiThread +public class RasterDemSource extends Source { + public static final int DEFAULT_TILE_SIZE = 512; + + /** + * Internal use + * + * @param nativePtr - pointer to native peer + */ + private RasterDemSource(long nativePtr) { + super(nativePtr); + } + + /** + * Create the raster dem source from an URL + * + * @param id the source id + * @param url the source url + */ + public RasterDemSource(String id, URL url) { + this(id, url.toExternalForm()); + } + + /** + * Create the raster dem source from an URL + * + * @param id the source id + * @param url the source url + */ + public RasterDemSource(String id, String url) { + initialize(id, url, DEFAULT_TILE_SIZE); + } + + /** + * Create the raster source from an URL with a specific tile size + * + * @param id the source id + * @param url the source url + * @param tileSize the tile size + */ + public RasterDemSource(String id, String url, int tileSize) { + initialize(id, url, tileSize); + } + + /** + * Create the raster dem source from a {@link TileSet} + * + * @param id the source id + * @param tileSet the {@link TileSet} + */ + public RasterDemSource(String id, TileSet tileSet) { + initialize(id, tileSet.toValueObject(), DEFAULT_TILE_SIZE); + } + + /** + * Create the raster source from a {@link TileSet} with a specific tile size + * + * @param id the source id + * @param tileSet the {@link TileSet} + * @param tileSize tje tile size + */ + public RasterDemSource(String id, TileSet tileSet, int tileSize) { + initialize(id, tileSet.toValueObject(), tileSize); + } + + /** + * @return The url or null + */ + @Nullable + public String getUrl() { + return nativeGetUrl(); + } + + protected native void initialize(String layerId, Object payload, int tileSize); + + @Override + protected native void finalize() throws Throwable; + + protected native String nativeGetUrl(); + +} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/TileSet.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/TileSet.java index 54e4e5f5d3..25df2d91e7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/TileSet.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/TileSet.java @@ -9,6 +9,7 @@ import java.util.Map; /** * Tile set, allows using TileJson specification as source. + * Note that `encoding` is only relevant to `raster-dem` sources, and is not supported in the TileJson spec. * * @see <a href="https://github.com/mapbox/tilejson-spec/tree/master/2.1.0">The tileset specification</a> */ @@ -28,6 +29,7 @@ public class TileSet { private Float maxZoom; private Float[] bounds; private Float[] center; + private String encoding; /** * @param tilejson A semver.org style version number. Describes the version of the TileJSON spec that is implemented @@ -246,6 +248,20 @@ public class TileSet { this.bounds = bounds; } + public String getEncoding() { + return encoding; + } + + /** + * Default: "mapbox". The encoding formula for a raster-dem tileset. + * Supported values are "mapbox" and "terrarium". + * + * @param encoding the String encoding formula to set + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + public Float[] getCenter() { return center; } @@ -313,6 +329,10 @@ public class TileSet { if (center != null) { result.put("center", center); } + if (encoding != null) { + result.put("encoding", encoding); + } + return result; } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/VectorSource.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/VectorSource.java index 9b59cf8967..d82eaaa1c7 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/VectorSource.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/sources/VectorSource.java @@ -5,8 +5,8 @@ import android.support.annotation.Nullable; import android.support.annotation.Size; import android.support.annotation.UiThread; -import com.mapbox.mapboxsdk.style.layers.Filter; -import com.mapbox.services.commons.geojson.Feature; +import com.mapbox.geojson.Feature; +import com.mapbox.mapboxsdk.style.expressions.Expression; import java.net.URL; import java.util.ArrayList; @@ -64,12 +64,12 @@ public class VectorSource extends Source { * Queries the source for features. * * @param sourceLayerIds the source layer identifiers. At least one must be specified. - * @param filter an optional filter statement to filter the returned Features + * @param filter an optional filter expression to filter the returned Features * @return the features */ @NonNull public List<Feature> querySourceFeatures(@Size(min = 1) String[] sourceLayerIds, - @Nullable Filter.Statement filter) { + @Nullable Expression filter) { Feature[] features = querySourceFeatures( sourceLayerIds, filter != null ? filter.toArray() : null); diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/text/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/text/package-info.java new file mode 100644 index 0000000000..52c7014bce --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/text/package-info.java @@ -0,0 +1,4 @@ +/** + * Contains the Mapbox Maps Android Text API classes. + */ +package com.mapbox.mapboxsdk.text; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MapFragmentUtils.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MapFragmentUtils.java index 007880acd1..08d39d6b3b 100644 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MapFragmentUtils.java +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MapFragmentUtils.java @@ -1,11 +1,8 @@ package com.mapbox.mapboxsdk.utils; import android.content.Context; -import android.graphics.drawable.Drawable; import android.os.Bundle; -import android.support.v4.content.ContextCompat; -import com.mapbox.mapboxsdk.R; import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.maps.MapboxMapOptions; @@ -45,25 +42,6 @@ public class MapFragmentUtils { // load default options options = MapboxMapOptions.createFromAttributes(context, null); } - options = loadDefaultMyLocationViewDrawables(context, options); - return options; - } - - private static MapboxMapOptions loadDefaultMyLocationViewDrawables(Context context, MapboxMapOptions options) { - Drawable foregroundDrawable = options.getMyLocationForegroundDrawable(); - Drawable foregroundBearingDrawable = options.getMyLocationForegroundBearingDrawable(); - if (foregroundDrawable == null || foregroundBearingDrawable == null) { - if (foregroundDrawable == null) { - foregroundDrawable = ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_icon_default); - } - if (foregroundBearingDrawable == null) { - foregroundBearingDrawable = ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_icon_bearing); - } - options.myLocationForegroundDrawables(foregroundDrawable, foregroundBearingDrawable); - } - if (options.getMyLocationBackgroundDrawable() == null) { - options.myLocationBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.mapbox_mylocation_bg_shape)); - } return options; } } diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MathUtils.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MathUtils.java new file mode 100644 index 0000000000..0c90e4b244 --- /dev/null +++ b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/utils/MathUtils.java @@ -0,0 +1,49 @@ +package com.mapbox.mapboxsdk.utils; + +// TODO Remove this class if we finally include it within MAS 3.x (GeoJSON) +public class MathUtils { + + /** + * Test a value in specified range, returning minimum if it's below, and maximum if it's above + * + * @param value Value to test + * @param min Minimum value of range + * @param max Maximum value of range + * @return value if it's between min and max, min if it's below, max if it's above + */ + public static double clamp(double value, double min, double max) { + return Math.max(min, Math.min(max, value)); + } + + /** + * Test a value in specified range, returning minimum if it's below, and maximum if it's above + * + * @param value Value to test + * @param min Minimum value of range + * @param max Maximum value of range + * @return value if it's between min and max, min if it's below, max if it's above + */ + public static float clamp(float value, float min, float max) { + return Math.max(min, Math.min(max, value)); + } + + /** + * Constrains value to the given range (including min, excluding max) via modular arithmetic. + * <p> + * Same formula as used in Core GL (wrap.hpp) + * std::fmod((std::fmod((value - min), d) + d), d) + min; + * + * @param value Value to wrap + * @param min Minimum value + * @param max Maximum value + * @return Wrapped value + */ + public static double wrap(double value, double min, double max) { + double delta = max - min; + + double firstMod = (value - min) % delta; + double secondMod = (firstMod + delta) % delta; + + return secondMod + min; + } +} |