diff --git a/Makefile b/Makefile index 1c1199932..170ff866c 100644 --- a/Makefile +++ b/Makefile @@ -461,309 +461,6 @@ test-node: node npm run test-query npm run test-memory -#### Android targets ########################################################### - -MBGL_ANDROID_ABIS = arm-v7;armeabi-v7a -MBGL_ANDROID_ABIS += arm-v8;arm64-v8a -MBGL_ANDROID_ABIS += x86;x86 -MBGL_ANDROID_ABIS += x86-64;x86_64 - -MBGL_ANDROID_LOCAL_WORK_DIR = /data/local/tmp/core-tests -MBGL_ANDROID_LOCAL_BENCHMARK_DIR = /data/local/tmp/benchmark -MBGL_ANDROID_LIBDIR = lib$(if $(filter arm-v8 x86-64,$1),64) -MBGL_ANDROID_DALVIKVM = dalvikvm$(if $(filter arm-v8 x86-64,$1),64,32) -MBGL_ANDROID_APK_SUFFIX = $(if $(filter Release,$(BUILDTYPE)),release,debug) -MBGL_ANDROID_CORE_TEST_DIR = platform/android/MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/core-tests -MBGL_ANDROID_BENCHMARK_DIR = platform/android/MapboxGLAndroidSDK/.externalNativeBuild/cmake/$(buildtype)/$2/benchmark -MBGL_ANDROID_STL ?= c++_static -MBGL_ANDROID_GRADLE = ./gradlew --parallel --max-workers=$(JOBS) -Pmapbox.buildtype=$(buildtype) -Pmapbox.stl=$(MBGL_ANDROID_STL) - -# Lists all devices, and extracts the identifiers, then obtains the ABI for every one. -# Some devices return \r\n, so we'll have to remove the carriage return before concatenating. -MBGL_ANDROID_ACTIVE_ARCHS = $(shell adb devices | sed '1d;/^\*/d;s/[[:space:]].*//' | xargs -n 1 -I DEV `type -P adb` -s DEV shell getprop ro.product.cpu.abi | tr -d '\r') - -# Generate code based on the style specification -.PHONY: android-style-code -android-style-code: - node platform/android/scripts/generate-style-code.js -style-code: android-style-code - -# Configuration file for running CMake from Gradle within Android Studio. -platform/android/gradle/configuration.gradle: - @printf "ext {\n node = '`command -v node || command -v nodejs`'\n npm = '`command -v npm`'\n ccache = '`command -v ccache`'\n}" > $@ - -define ANDROID_RULES -# $1 = arm-v7 (short arch) -# $2 = armeabi-v7a (internal arch) - -.PHONY: android-test-lib-$1 -android-test-lib-$1: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_test=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) - -.PHONY: android-benchmark-$1 -android-benchmark-$1: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 -Pmapbox.with_benchmark=true :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) - -# Build SDK for for specified abi -.PHONY: android-lib-$1 -android-lib-$1: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDK:assemble$(BUILDTYPE) - -# Build test app and SDK for for specified abi -.PHONY: android-$1 -android-$1: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assemble$(BUILDTYPE) - -# Build the core test for specified abi -.PHONY: android-core-test-$1 -android-core-test-$1: android-test-lib-$1 - # Compile main sources and extract the classes (using the test app to get all transitive dependencies in one place) - mkdir -p $(MBGL_ANDROID_CORE_TEST_DIR) - unzip -o platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MBGL_ANDROID_APK_SUFFIX).apk classes.dex -d $(MBGL_ANDROID_CORE_TEST_DIR) - -run-android-core-test-$1-%: android-core-test-$1 - # Ensure clean state on the device - adb shell "rm -Rf $(MBGL_ANDROID_LOCAL_WORK_DIR) && mkdir -p $(MBGL_ANDROID_LOCAL_WORK_DIR)/test && mkdir -p $(MBGL_ANDROID_LOCAL_WORK_DIR)/mapbox-gl-js/src/style-spec/reference" - - # Push all needed files to the device - adb push $(MBGL_ANDROID_CORE_TEST_DIR)/classes.dex $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 - adb push platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 - adb push test/fixtures $(MBGL_ANDROID_LOCAL_WORK_DIR)/test > /dev/null 2>&1 - adb push mapbox-gl-js/src/style-spec/reference/v8.json $(MBGL_ANDROID_LOCAL_WORK_DIR)/mapbox-gl-js/src/style-spec/reference > /dev/null 2>&1 - adb push platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-test $(MBGL_ANDROID_LOCAL_WORK_DIR) > /dev/null 2>&1 - -# Create gtest filter for skipped tests. - $(eval SKIPPED_TESTS := -$(shell sed -n '/#\|^$$/!p' platform/android/tests/skipped.txt | sed ':a;$!N;s/\n/:/g;ta')) - - # Kick off the tests - adb shell "export LD_LIBRARY_PATH=$(MBGL_ANDROID_LOCAL_WORK_DIR) && cd $(MBGL_ANDROID_LOCAL_WORK_DIR) && chmod +x mbgl-test && ./mbgl-test --class_path=$(MBGL_ANDROID_LOCAL_WORK_DIR)/classes.dex --gtest_filter=$$*:$(SKIPPED_TESTS)" - - # Gather the results and unpack them - adb shell "cd $(MBGL_ANDROID_LOCAL_WORK_DIR) && tar -cvzf results.tgz test/fixtures/* > /dev/null 2>&1" - adb pull $(MBGL_ANDROID_LOCAL_WORK_DIR)/results.tgz $(MBGL_ANDROID_CORE_TEST_DIR)/ > /dev/null 2>&1 - rm -rf $(MBGL_ANDROID_CORE_TEST_DIR)/results && mkdir -p $(MBGL_ANDROID_CORE_TEST_DIR)/results - tar -xzf $(MBGL_ANDROID_CORE_TEST_DIR)/results.tgz --strip-components=2 -C $(MBGL_ANDROID_CORE_TEST_DIR)/results - -# Run the core test for specified abi -.PHONY: run-android-core-test-$1 -run-android-core-test-$1: run-android-core-test-$1-* - -# Run benchmarks for specified abi -.PHONY: run-android-benchmark-$1 -run-android-benchmark-$1: run-android-benchmark-$1-* - -run-android-benchmark-$1-%: android-benchmark-$1 - mkdir -p $(MBGL_ANDROID_BENCHMARK_DIR) - unzip -o platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/$(buildtype)/MapboxGLAndroidSDKTestApp-$(MBGL_ANDROID_APK_SUFFIX).apk classes.dex -d $(MBGL_ANDROID_BENCHMARK_DIR) - - # Delete old test folder and create new one - adb shell "rm -Rf $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && mkdir -p $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark && mkdir -p $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/test" - - # Push compiled java sources, test data and executable to device - adb push $(MBGL_ANDROID_BENCHMARK_DIR)/classes.dex $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 - adb push platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/$(buildtype)/jni/$2/libmapbox-gl.so $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 - adb push benchmark/fixtures $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/benchmark > /dev/null 2>&1 - adb push test/fixtures $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/test > /dev/null 2>&1 - adb push platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/$(buildtype)/obj/$2/mbgl-benchmark $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) > /dev/null 2>&1 - - # Run benchmark. Number of benchmark iterations can be set by run-android-benchmark-N parameter. - adb shell "export LD_LIBRARY_PATH=$(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && cd $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR) && chmod +x mbgl-benchmark && ./mbgl-benchmark --class_path=$(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/classes.dex --benchmark_repetitions=$$* --benchmark_format=json --benchmark_out=results.json" - - # Pull results.json from the device - rm -rf $(MBGL_ANDROID_BENCHMARK_DIR)/results && mkdir -p $(MBGL_ANDROID_BENCHMARK_DIR)/results - adb pull $(MBGL_ANDROID_LOCAL_BENCHMARK_DIR)/results.json $(MBGL_ANDROID_BENCHMARK_DIR)/results > /dev/null 2>&1 - -# Run the test app on connected android device with specified abi -.PHONY: run-android-$1 -run-android-$1: platform/android/gradle/configuration.gradle - -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:install$(BUILDTYPE) && adb shell am start -n com.mapbox.mapboxsdk.testapp/.activity.FeatureOverviewActivity - -# Build test app instrumentation tests apk and test app apk for specified abi -.PHONY: android-ui-test-$1 -android-ui-test-$1: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest - -# Run test app instrumentation tests on a connected android device or emulator with specified abi -.PHONY: run-android-ui-test-$1 -run-android-ui-test-$1: platform/android/gradle/configuration.gradle - -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest - -# Run Java Instrumentation tests on a connected android device or emulator with specified abi and test filter -run-android-ui-test-$1-%: platform/android/gradle/configuration.gradle - -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="$$*" - -# Symbolicate native stack trace with the specified abi -.PHONY: android-ndk-stack-$1 -android-ndk-stack-$1: platform/android/gradle/configuration.gradle - adb logcat | ndk-stack -sym platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/debug/obj/$2/ - -# Run render tests with pixelmatch -.PHONY: run-android-render-test-$1 -run-android-render-test-$1: $(BUILD_DEPS) platform/android/gradle/configuration.gradle - -adb uninstall com.mapbox.mapboxsdk.testapp 2> /dev/null - # delete old test results - rm -rf platform/android/build/render-test/mapbox/ - # copy test definitions & ignore file to test app assets folder, clear old ones first - rm -rf platform/android/MapboxGLAndroidSDKTestApp/src/main/assets/integration - cp -r mapbox-gl-js/test/integration platform/android/MapboxGLAndroidSDKTestApp/src/main/assets - cp platform/node/test/ignores.json platform/android/MapboxGLAndroidSDKTestApp/src/main/assets/integration/ignores.json - # run RenderTest.java to generate static map images - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=$2 :MapboxGLAndroidSDKTestApp:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class="com.mapbox.mapboxsdk.testapp.render.RenderTest" - # pull generated images from the device - adb pull "`adb shell 'printenv EXTERNAL_STORAGE' | tr -d '\r'`/mapbox/render" platform/android/build/render-test - # copy expected result and run pixelmatch - python platform/android/scripts/run-render-test.py - # remove test definitions from assets - rm -rf platform/android/MapboxGLAndroidSDKTestApp/src/main/assets/integration - -endef - -# Explodes the arguments into individual variables -define ANDROID_RULES_INVOKER -$(call ANDROID_RULES,$(word 1,$1),$(word 2,$1)) -endef - -$(foreach abi,$(MBGL_ANDROID_ABIS),$(eval $(call ANDROID_RULES_INVOKER,$(subst ;, ,$(abi))))) - -# Build the Android SDK and test app with abi set to arm-v7 -.PHONY: android -android: android-arm-v7 - -# Build the Android SDK with abi set to arm-v7 -.PHONY: android-lib -android-lib: android-lib-arm-v7 - -# Run the test app on connected android device with abi set to arm-v7 -.PHONY: run-android -run-android: run-android-arm-v7 - -# Run Java Instrumentation tests on a connected android device or emulator with abi set to arm-v7 -.PHONY: run-android-ui-test -run-android-ui-test: run-android-ui-test-arm-v7 -run-android-ui-test-%: run-android-ui-test-arm-v7-% - -# Run Java Unit tests on the JVM of the development machine executing this -.PHONY: run-android-unit-test -run-android-unit-test: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info -run-android-unit-test-%: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:testDebugUnitTest --info --tests "$*" - -# Run unit test and build a coverage report from .exec file generated by unit tests and .ec file generated by instrumentation tests -.PHONY: android-create-jacoco-report -android-create-jacoco-report: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:jacocoTestReport - -# Parse merged jacoco report and send it to S3 -.PHONY: android-parse-and-send-jacoco-report -android-parse-and-send-jacoco-report: - python platform/android/scripts/parse-jacoco-report.py - -# Builds a release package of the Android SDK -.PHONY: apackage -apackage: platform/android/gradle/configuration.gradle - make android-lib-arm-v7 && make android-lib-arm-v8 && make android-lib-x86 && make android-lib-x86-64 - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all assemble$(BUILDTYPE) - -# Build test app instrumentation tests apk and test app apk for all abi's -.PHONY: android-ui-test -android-ui-test: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all :MapboxGLAndroidSDKTestApp:assembleDebug :MapboxGLAndroidSDKTestApp:assembleAndroidTest - -#Run instrumentations tests on MicroSoft App Center -.PHONY: run-android-test-app-center -run-android-test-app-center: - cd platform/android && appcenter test run espresso --app "mapboxcn-outlook.com/MapsSdk" --devices "mapboxcn-outlook.com/china" --app-path MapboxGLAndroidSDKTestApp/build/outputs/apk/debug/MapboxGLAndroidSDKTestApp-debug.apk --test-series "master" --locale "en_US" --build-dir MapboxGLAndroidSDKTestApp/build/outputs/apk/androidTest/debug - -# Uploads the compiled Android SDK to Bintray -.PHONY: run-android-upload-to-bintray -run-android-upload-to-bintray: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all :MapboxGLAndroidSDK:bintrayUpload - -# Uploads the compiled Android SDK SNAPSHOT to oss.jfrog.org -.PHONY: run-android-upload-to-artifactory -run-android-upload-to-artifactory: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=all :MapboxGLAndroidSDK:artifactoryPublish - -# Dump system graphics information for the test app -.PHONY: android-gfxinfo -android-gfxinfo: - adb shell dumpsys gfxinfo com.mapbox.mapboxsdk.testapp reset - -# Generates Activity sanity tests -.PHONY: test-code-android -test-code-android: - node platform/android/scripts/generate-test-code.js - -# Runs checkstyle and lint on the java code -.PHONY: android-check -android-check : android-ktlint android-checkstyle android-lint-sdk android-lint-test-app run-android-nitpick - -# Runs checkstyle on the java code -.PHONY: android-checkstyle -android-checkstyle: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:checkstyle :MapboxGLAndroidSDKTestApp:checkstyle - -# Runs checkstyle on the kotlin code -.PHONY: android-ktlint -android-ktlint: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none ktlint - -# Runs lint on the Android SDK java code -.PHONY: android-lint-sdk -android-lint-sdk: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:lint - -# Runs lint on the Android test app java code -.PHONY: android-lint-test-app -android-lint-test-app: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDKTestApp:lint - -# Generates javadoc from the Android SDK -.PHONY: android-javadoc -android-javadoc: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:javadocrelease - -# Generates platform/android/LICENSE.md file based on all Android project dependencies -.PHONY: android-license -android-license: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:licenseReleaseReport - python platform/android/scripts/generate-license.py - -# Symbolicate ndk stack traces for the arm-v7 abi -.PHONY: android-ndk-stack -android-ndk-stack: android-ndk-stack-arm-v7 - -# Open Android Studio if machine is macos -ifeq ($(HOST_PLATFORM), macos) -.PHONY: aproj -aproj: platform/android/gradle/configuration.gradle - open -b com.google.android.studio platform/android -endif - -# Creates the configuration needed to build with Android Studio -.PHONY: android-configuration -android-configuration: platform/android/gradle/configuration.gradle - cat platform/android/gradle/configuration.gradle - -# Updates Android's vendor submodules -.PHONY: android-update-vendor -android-update-vendor: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none updateVendorSubmodules - -# Run android nitpick script -.PHONY: run-android-nitpick -run-android-nitpick: android-update-vendor - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none androidNitpick - -# Creates a dependency graph using Graphviz -.PHONY: android-graph -android-graph: platform/android/gradle/configuration.gradle - cd platform/android && $(MBGL_ANDROID_GRADLE) -Pmapbox.abis=none :MapboxGLAndroidSDK:generateDependencyGraphMapboxLibraries - #### Miscellaneous targets ##################################################### .PHONY: style-code diff --git a/circle.yml b/circle.yml index 27cdf7c0e..129033809 100644 --- a/circle.yml +++ b/circle.yml @@ -137,20 +137,6 @@ workflows: # unique aspect of the build environment. # - {build type} is typically "debug" or "release". # - - android-debug-arm-v7-buck - - android-arm-template: - name: android-debug-arm-v8 - - android-arm-template: - name: android-gnustl-arm-v7 - stl: gnustl_shared - firebase_device_id: "flo" - firebase_device_os: "21" - image: android-ndk-r17c:1d5db0eb34 - abi: arm-v7 - - android-release: - filters: - tags: - only: /android-v.*/ - node-linux-release: filters: tags: @@ -405,21 +391,6 @@ commands: - 'ccache/v1/{{ arch }}/{{ .Environment.CIRCLE_JOB }}/{{ checksum ".circle-target-branch" }}/{{ checksum ".circle-merge-base" }}' - 'ccache/v1/{{ arch }}/{{ .Environment.CIRCLE_JOB }}/{{ checksum ".circle-target-branch" }}' - 'ccache/v1/{{ arch }}/{{ .Environment.CIRCLE_JOB }}' - save-gradle-cache: - steps: - - save_cache: - name: Save gradle cache - key: 'gradle/v1/{{ checksum "platform/android/gradle/dependencies.gradle" }}/{{ checksum "platform/android/build.gradle" }}/{{ checksum "platform/android/gradle/wrapper/gradle-wrapper.properties" }}' - paths: [ "/root/.gradle" ] - restore-gradle-cache: - steps: - - restore_cache: - name: Restore gradle cache - keys: - - 'gradle/v1/{{ checksum "platform/android/gradle/dependencies.gradle" }}/{{ checksum "platform/android/build.gradle" }}/{{ checksum "platform/android/gradle/wrapper/gradle-wrapper.properties" }}' - - 'gradle/v1' - - install-dependencies: parameters: node_modules: @@ -431,9 +402,6 @@ commands: mason: type: boolean default: true - gradle: - type: boolean - default: false steps: - checkout - when: @@ -446,9 +414,6 @@ commands: - when: condition: << parameters.mason >> steps: [ restore-mason_packages-cache ] - - when: - condition: << parameters.gradle >> - steps: [ restore-gradle-cache ] save-dependencies: parameters: node_modules: @@ -460,9 +425,6 @@ commands: mason: type: boolean default: true - gradle: - type: boolean - default: false steps: - when: condition: << parameters.node_modules >> @@ -473,10 +435,6 @@ commands: - when: condition: << parameters.mason >> steps: [ save-mason_packages-cache ] - - when: - condition: << parameters.gradle >> - steps: [ save-gradle-cache ] - setup-llvm-symbolizer: steps: @@ -722,7 +680,6 @@ jobs: - run: name: Code Generators command: | - platform/android/scripts/generate-style-code.js platform/default/include/mbgl/storage/offline_schema.js scripts/generate-file-lists.js scripts/generate-shaders.js @@ -822,216 +779,6 @@ jobs: runtime_wrapper: 'xvfb-run -s -noreset' metrics_params: '-p metrics/binary-size.json' - next-save - -# ------------------------------------------------------------------------------ - android-arm-template: - parameters: - stl: - type: string - default: "c++_static" - image: - type: string - default: android-ndk-r20:7b7c4b42cf - firebase_device_id: - type: string - default: sailfish - firebase_device_os: - type: string - default: "26" - abi: - type: string - default: "arm-v8" - docker: - - image: mbgl/<< parameters.image >> - resource_class: xlarge - working_directory: /src - environment: - LIBSYSCONFCPUS: 8 - JOBS: 8 - BUILDTYPE: Debug - IS_LOCAL_DEVELOPMENT: false - MBGL_ANDROID_STL: << parameters.stl >> - steps: - - install-dependencies: { gradle: true } - - check-if-this-job-can-be-skipped - - run: - name: Initialize vendor submodules - command: git submodule update --init platform/android/vendor - - run: - name: Check code style - command: make android-check - - run: - name: Run Android unit tests - command: make run-android-unit-test - - run: - name: Build libmapbox-gl.so for << parameters.abi >> - command: make android-lib-<< parameters.abi >> - - run: - name: Generate Espresso sanity tests - command: make test-code-android - - run: - name: Build Test APK - command: | - if [ -n "${MAPBOX_DEVELOPER_CONFIG_XML}" ]; then - echo "${MAPBOX_DEVELOPER_CONFIG_XML}" > platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/developer-config.xml - make android-ui-test-<< parameters.abi >> - fi - - save-dependencies: { gradle: true } - - conditionally-skip-firebase - - login-google-cloud-platform - - run: - name: Run instrumentation tests on Firebase - no_output_timeout: 20m - command: | - if [[ -n "${GCLOUD_SERVICE_ACCOUNT_JSON}" && -z "${SKIP_FIREBASE:-}" ]]; then - gcloud firebase test android models list - gcloud firebase test android run --type instrumentation \ - --app platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/debug/MapboxGLAndroidSDKTestApp-debug.apk \ - --test platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/androidTest/debug/MapboxGLAndroidSDKTestApp-debug-androidTest.apk \ - --device-ids << parameters.firebase_device_id >> --os-version-ids << parameters.firebase_device_os >> --locales en --orientations portrait --timeout 20m \ - --environment-variables coverage=true,coverageFile="/sdcard/coverage.ec" --directories-to-pull /sdcard --results-dir mapbox-android-sdk-${CIRCLE_BUILD_NUM} - coverageFile=`gsutil ls gs://test-lab-186672a0qp5bq-ycr70axads3nc/mapbox-android-sdk-${CIRCLE_BUILD_NUM}/**/*.ec | tail -1` - gsutil cp $coverageFile $PWD/platform/android/MapboxGLAndroidSDK/build/jacoco | true - fi - - run: - name: Parse and send Jacoco reports - command: | - if [[ $CIRCLE_BRANCH == master ]]; then - make android-create-jacoco-report && make android-parse-and-send-jacoco-report - fi - - store_artifacts: - path: platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/debug - destination: . - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/reports/lint-results.html - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/reports/lint-results.xml - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/lint-baseline.xml - - store_artifacts: - path: platform/android/MapboxGLAndroidSDKTestApp/build/reports/lint-results.html - - store_artifacts: - path: platform/android/MapboxGLAndroidSDKTestApp/build/reports/lint-results.xml - - store_artifacts: - path: platform/android/MapboxGLAndroidSDKTestApp/lint-baseline.xml - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/debug/obj - -# ------------------------------------------------------------------------------ - android-release: - docker: - - image: mbgl/android-ndk-r20:7b7c4b42cf - resource_class: xlarge - working_directory: /src - environment: - LIBSYSCONFCPUS: 8 - JOBS: 8 - BUILDTYPE: Release - IS_LOCAL_DEVELOPMENT: false - steps: - - install-dependencies: { gradle: true } - - check-if-this-job-can-be-skipped - - run: - name: Initialize vendor submodules - command: git submodule update --init platform/android/vendor - - run: - name: Android nitpick - command: make run-android-nitpick - - run: - name: Trigger core benchmark run - command: | - if [ -n "${MOBILE_METRICS_TOKEN}" ]; then - if [[ $CIRCLE_BRANCH == master ]]; then - curl -u ${MOBILE_METRICS_TOKEN}: -d build_parameters[CIRCLE_JOB]=android-core-benchmark https://circleci.com/api/v1.1/project/github/mapbox/mobile-metrics/tree/master - fi - fi - - run: - name: Trigger android benchmark run - command: | - if [ -n "${MOBILE_METRICS_TOKEN}" ]; then - if [[ $CIRCLE_BRANCH == master ]]; then - curl -u ${MOBILE_METRICS_TOKEN}: -d build_parameters[CIRCLE_JOB]=android-benchmark https://circleci.com/api/v1.1/project/github/mapbox/mobile-metrics/tree/master - fi - fi - - run: - name: Generate Maven credentials - command: | - if [ -n "${BINTRAY_USER}" ]; then - echo "BINTRAY_USER=$BINTRAY_USER - BINTRAY_API_KEY=$BINTRAY_API_KEY - GPG_PASSPHRASE=$GPG_PASSPHRASE" - fi - - run: - name: Update version name - command: | - if [[ $CIRCLE_TAG == android-v* ]]; then - sed -i -e "s/^VERSION_NAME=.*/VERSION_NAME=${CIRCLE_TAG:9}/" platform/android/MapboxGLAndroidSDK/gradle.properties - fi - - run: - name: Build package - command: make apackage - - run: - name: Build release Test App - command: make android - - run: - name: Generate javadoc - command: make android-javadoc - - save-dependencies: { gradle: true } - - run: - name: gzip debugable .so files - command: | - gzip platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/arm64-v8a/libmapbox-gl.so && \ - gzip platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/armeabi-v7a/libmapbox-gl.so && \ - gzip platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/x86/libmapbox-gl.so && \ - gzip platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/x86_64/libmapbox-gl.so - - store_artifacts: - path: platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/release - destination: . - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/arm64-v8a/libmapbox-gl.so.gz - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/armeabi-v7a/libmapbox-gl.so.gz - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/x86/libmapbox-gl.so.gz - - store_artifacts: - path: platform/android/MapboxGLAndroidSDK/build/intermediates/cmake/release/obj/x86_64/libmapbox-gl.so.gz - - run: - name: Trigger external deploy steps - command: | - export VERSION_TAG=${CIRCLE_TAG} - export GITHUB_TOKEN=${DANGER_GITHUB_API_TOKEN} - export DOCS_REPO="android-docs" - scripts/trigger-maps-documentation-deploy-steps.sh - background: true -# - run: -# name: Record size -# command: platform/android/scripts/metrics.sh -# ------------------------------------------------------------------------------ - android-debug-arm-v7-buck: - docker: - - image: mbgl/android-ndk-r17c-buck:07c5ef2e71 - working_directory: /src - environment: - LIBSYSCONFCPUS: 2 - JOBS: 2 - BUILDTYPE: Debug - ANDROID_NDK: /android/sdk/ndk-bundle - steps: - - checkout - - npm-install - - prepare-environment - - check-if-this-job-can-be-skipped - - run: - name: Checkout submodules - command: | - git submodule update --init - git submodule foreach git submodule update --init - - run: - name: Build Android library - command: | - cd misc/buck - buck build mapbox-gl-native:android-core - # ------------------------------------------------------------------------------ node-linux-release: docker: diff --git a/platform/android/.editorconfig b/platform/android/.editorconfig deleted file mode 100644 index 8a6c90a0d..000000000 --- a/platform/android/.editorconfig +++ /dev/null @@ -1,4 +0,0 @@ -[*.{kt,kts}] -indent_size=2 -insert_final_newline=false -disabled_rules=no-wildcard-imports \ No newline at end of file diff --git a/platform/android/.project b/platform/android/.project deleted file mode 100644 index 3964dd3f5..000000000 --- a/platform/android/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - android - Project android created by Buildship. - - - - - org.eclipse.buildship.core.gradleprojectbuilder - - - - - - org.eclipse.buildship.core.gradleprojectnature - - diff --git a/platform/android/.settings/org.eclipse.buildship.core.prefs b/platform/android/.settings/org.eclipse.buildship.core.prefs deleted file mode 100644 index e8895216f..000000000 --- a/platform/android/.settings/org.eclipse.buildship.core.prefs +++ /dev/null @@ -1,2 +0,0 @@ -connection.project.dir= -eclipse.preferences.version=1 diff --git a/platform/android/CHANGELOG.md b/platform/android/CHANGELOG.md index c1649eef0..b9a7a05ac 100644 --- a/platform/android/CHANGELOG.md +++ b/platform/android/CHANGELOG.md @@ -1,7 +1,10 @@ # Changelog for the Mapbox Maps SDK for Android - Mapbox welcomes participation and contributions from everyone. If you'd like to do so please see the [`Contributing Guide`](https://github.com/mapbox/mapbox-gl-native/blob/master/CONTRIBUTING.md) first to get started. +## Notice +**Work on the Mapbox Maps SDK for Android is now happening at https://github.com/mapbox/mapbox-gl-native-android.** +Please see the README at https://github.com/mapbox/mapbox-gl-native-android for the most up-to-date information on the Maps SDK for Android. + ## master - Added support for [image expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-types-image) in core library. Runtime APIs for image expression will be implemented separately. [#15877](https://github.com/mapbox/mapbox-gl-native/pull/15877) - Make network requests for expired resources lower priority than requests for new resources. ([#15950](https://github.com/mapbox/mapbox-gl-native/pull/15950)) diff --git a/platform/android/DISTRIBUTE.md b/platform/android/DISTRIBUTE.md deleted file mode 100644 index 8f2bec19d..000000000 --- a/platform/android/DISTRIBUTE.md +++ /dev/null @@ -1,57 +0,0 @@ -# Distributing Mapbox GL Native for Android - -Depending on your use case, you may want to support all or just a subset of [Android ABIs](http://developer.android.com/ndk/guides/abis.html). This document covers building an `.aar` file from the Mapbox Maps SDK for Android and building `.so` files for specific ABIs. In normal circumstances an application developer will use [APK splits](https://developer.android.com/studio/build/configure-apk-splits.html) to optimize this at application level. - -##### Build types - -With a `BUILDTYPE` var you can specify the build type for the `.so` and `.aar` files: - -```bash -BUILDTYPE=Debug or BUILDTYPE=Release -``` - -##### Creating an Android Archive file that supports all ABIs - -```sh -BUILDTYPE=Release make apackage -``` - -This will build native libraries to support following ABIs: -- armeabi -- armeabi-v7a -- arm64-v8a -- x86 -- x86_64 -- mips - -After succesfully finish building the native libraries, gradle will build the MapboxAndroidSDK module and generate an Android Archive file in `MapboxAndroidSDK/build/outputs/aar `. The packaged native libraries can be found in `MapboxAndroidSDK/src/main/jniLibs/`. - -##### Build native libraries for a specific ABI - -```sh -make android-lib-%% -``` - -In the command above you'll need to replace `%%` with an ABI key listed below: - -| ABI Key | Android ABI | -| ------- | ----------- | -| arm-v5 | armeabi | -| arm-v7 | armeabi-v7a | -| arm-v8 | arm64-v8a | -| x86 | x86 | -| x86-64 | x86_64 | -| mips | mips | - -For example, to build the arm64-v8a ABI the Makefile target would be: - -```sh -make android-lib-arm-v8 -``` - -It's also possible to build multiple ABI (without having to build them all) by running the Makefile multiple times. For example to build arm64-v8a and x86_64 in the same project the commands would be: - -```sh -make android-lib-arm-v8 -make android-lib-arm-x86-64 -``` diff --git a/platform/android/LICENSE.md b/platform/android/LICENSE.md deleted file mode 100644 index 8423a34a6..000000000 --- a/platform/android/LICENSE.md +++ /dev/null @@ -1,227 +0,0 @@ - -## Additional Mapbox GL licenses -Mapbox GL uses portions of the Android Arch-Common. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Arch-Runtime. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Lifecycle LiveData. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Lifecycle LiveData Core. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Lifecycle Runtime. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Lifecycle ViewModel. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Lifecycle-Common. -URL: [https://developer.android.com/topic/libraries/architecture/index.html](https://developer.android.com/topic/libraries/architecture/index.html) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Annotations. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Async Layout Inflater. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library collections. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library compat. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Coordinator Layout. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library core UI. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library core utils. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Cursor Adapter. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Custom View. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Custom View. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Document File. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Drawer Layout. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library fragment. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Interpolators. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library loader. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Local Broadcast Manager. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Print. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library Sliding Pane Layout. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Android Support Library View Pager. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Gson. -License: [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Accounts SDK for Android. -URL: [https://github.com/mapbox/mapbox-accounts-android](https://github.com/mapbox/mapbox-accounts-android) -License: [Mapbox Terms of Service](https://www.mapbox.com/tos/) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Android Core Library. -URL: [https://github.com/mapbox/mapbox-events-android](https://github.com/mapbox/mapbox-events-android) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Android Gestures Library. -URL: [https://github.com/mapbox/mapbox-gestures-android](https://github.com/mapbox/mapbox-gestures-android) -License: [BSD](https://opensource.org/licenses/BSD-2-Clause) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Android Telemetry Library. -URL: [https://github.com/mapbox/mapbox-events-android](https://github.com/mapbox/mapbox-events-android) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Java SDK. -URL: [https://github.com/mapbox/mapbox-java](https://github.com/mapbox/mapbox-java) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Mapbox Java SDK. -URL: [https://github.com/mapbox/mapbox-java](https://github.com/mapbox/mapbox-java) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the OkHttp. -License: [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Okio. -License: [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the SoLoader. -URL: [https://github.com/facebook/soloader](https://github.com/facebook/soloader) -License: [Apache-2](https://github.com/facebook/soloader/blob/master/LICENSE) - -=========================================================================== - -Mapbox GL uses portions of the VersionedParcelable and friends. -URL: [http://developer.android.com/tools/extras/support-library.html](http://developer.android.com/tools/extras/support-library.html) -License: [The Apache Software License](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - -Mapbox GL uses portions of the Gradle License Plugin. -URL: [https://github.com/jaredsburrows/gradle-license-plugin](https://github.com/jaredsburrows/gradle-license-plugin) -License: [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) - -=========================================================================== - diff --git a/platform/android/MapboxGLAndroidSDK/.gitignore b/platform/android/MapboxGLAndroidSDK/.gitignore deleted file mode 100644 index e44384742..000000000 --- a/platform/android/MapboxGLAndroidSDK/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -dependency-graph-mapbox-libraries.png -src/test/resources/mobile-event* diff --git a/platform/android/MapboxGLAndroidSDK/build.gradle b/platform/android/MapboxGLAndroidSDK/build.gradle deleted file mode 100644 index 5ee3af61e..000000000 --- a/platform/android/MapboxGLAndroidSDK/build.gradle +++ /dev/null @@ -1,105 +0,0 @@ -apply plugin: 'com.android.library' -apply plugin: "com.jaredsburrows.license" -apply plugin: 'kotlin-android' -apply from: "${rootDir}/gradle/native-build.gradle" - -dependencies { - lintChecks project(":MapboxGLAndroidSDKLint") - api dependenciesList.mapboxAndroidTelemetry - api dependenciesList.mapboxJavaGeoJSON - api dependenciesList.mapboxAndroidGestures - api dependenciesList.mapboxAndroidAccounts - implementation dependenciesList.mapboxJavaTurf - implementation dependenciesList.supportAnnotations - implementation dependenciesList.supportFragmentV4 - implementation dependenciesList.okhttp3 - implementation dependenciesList.soLoader - testImplementation dependenciesList.junit - testImplementation dependenciesList.mockito - testImplementation dependenciesList.mockk - testImplementation dependenciesList.robolectric - testImplementation dependenciesList.kotlinLib - testImplementation dependenciesList.commonsIO -} - -android { - compileSdkVersion androidVersions.compileSdkVersion - - defaultConfig { - minSdkVersion androidVersions.minSdkVersion - targetSdkVersion androidVersions.targetSdkVersion - buildConfigField "String", "GIT_REVISION_SHORT", String.format("\"%s\"", getGitRevision()) - buildConfigField "String", "MAPBOX_SDK_IDENTIFIER", String.format("\"%s\"", "mapbox-maps-android") - buildConfigField "String", "MAPBOX_SDK_VERSION", String.format("\"%s\"", project.VERSION_NAME) - buildConfigField "String", "MAPBOX_VERSION_STRING", String.format("\"Mapbox/%s\"", project.VERSION_NAME) - buildConfigField "String", "MAPBOX_EVENTS_USER_AGENT", String.format("\"mapbox-maps-android/%s\"", project.VERSION_NAME) - consumerProguardFiles 'proguard-rules.pro' - } - - // build native libraries - List nativeTargets = ["mapbox-gl"] - if (project.hasProperty("mapbox.with_test")) { - nativeTargets.add("mbgl-test") - } - if (project.hasProperty("mapbox.with_benchmark")) { - nativeTargets.add("mbgl-benchmark") - } - nativeBuild(nativeTargets) - - // avoid naming conflicts, force usage of prefix - resourcePrefix 'mapbox_' - - sourceSets { - // limit amount of exposed library resources - main.res.srcDirs += 'src/main/res-public' - } - - lintOptions { - disable 'MissingTranslation', 'TypographyQuotes', 'ObsoleteLintCustomCheck', 'MissingPermission', 'WrongThreadInterprocedural' - checkAllWarnings true - warningsAsErrors false - } - - testOptions { - unitTests { - returnDefaultValues true - - // Roboelectric 4.0 required config - // http://robolectric.org/migrating/#migrating-to-40 - includeAndroidResources = true - } - } - - buildTypes { - debug { - testCoverageEnabled true - jniDebuggable true - } - } -} - -licenseReport { - generateHtmlReport = false - generateJsonReport = true - copyHtmlReportToAssets = false - copyJsonReportToAssets = false -} - -def static getGitRevision() { - def cmd = "git rev-parse --short HEAD" - def proc = cmd.execute() - def ref = proc.text.trim() - return ref -} - -configurations { - all*.exclude group: 'commons-logging', module: 'commons-logging' - all*.exclude group: 'commons-collections', module: 'commons-collections' -} -apply from: "${rootDir}/gradle/gradle-javadoc.gradle" -apply from: "${rootDir}/gradle/gradle-checkstyle.gradle" -apply from: "${rootDir}/gradle/gradle-dependencies-graph.gradle" -apply from: "${rootDir}/gradle/gradle-update-vendor-modules.gradle" -apply from: "${rootDir}/gradle/android-nitpick.gradle" -apply from: "${rootDir}/gradle/gradle-bintray.gradle" -apply from: "${rootDir}/gradle/jacoco-report.gradle" \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/gradle.properties b/platform/android/MapboxGLAndroidSDK/gradle.properties deleted file mode 100644 index e3fedcde0..000000000 --- a/platform/android/MapboxGLAndroidSDK/gradle.properties +++ /dev/null @@ -1,9 +0,0 @@ -VERSION_NAME=8.5.0-SNAPSHOT - -# Only build native dependencies for the current ABI -# See https://code.google.com/p/android/issues/detail?id=221098#c20 -android.buildOnlyTargetAbi=true - -# Roboelectric 4.0 required config for < Android Studio v3.3.0 -# http://robolectric.org/migrating/#migrating-to-40 -android.enableUnitTestBinaryResources=true \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/lint.xml b/platform/android/MapboxGLAndroidSDK/lint.xml deleted file mode 100644 index 3a244199a..000000000 --- a/platform/android/MapboxGLAndroidSDK/lint.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/platform/android/MapboxGLAndroidSDK/proguard-rules.pro b/platform/android/MapboxGLAndroidSDK/proguard-rules.pro deleted file mode 100644 index f592efa6b..000000000 --- a/platform/android/MapboxGLAndroidSDK/proguard-rules.pro +++ /dev/null @@ -1,41 +0,0 @@ -# By default, the flags in this file are appended to flags specified -# in ../sdk/tools/proguard/proguard-android.txt, -# contents of this file will be appended into proguard-android.txt --keepattributes Signature, *Annotation*, EnclosingMethod - -# Reflection on classes from native code --keep class com.google.gson.JsonArray { *; } --keep class com.google.gson.JsonElement { *; } --keep class com.google.gson.JsonObject { *; } --keep class com.google.gson.JsonPrimitive { *; } --dontnote com.google.gson.** - -# dontnote for keeps the entry point x but not the descriptor class y --dontnote com.mapbox.mapboxsdk.maps.MapboxMap$OnFpsChangedListener --dontnote com.mapbox.mapboxsdk.style.layers.PropertyValue --dontnote com.mapbox.mapboxsdk.maps.MapboxMap --dontnote com.mapbox.mapboxsdk.maps.MapboxMapOptions --dontnote com.mapbox.mapboxsdk.log.LoggerDefinition --dontnote com.mapbox.android.core.location.LocationEnginePriority - -# config for okhttp 3.11.0, https://github.com/square/okhttp/pull/3354 --dontwarn javax.annotation.** --dontnote okhttp3.internal.** --dontwarn org.codehaus.** - -# config for mapbox-sdk-geojson:3.0.1 --keep class com.mapbox.geojson.** { *; } --dontwarn com.google.auto.value.** - -# config for additional notes --dontnote org.robolectric.Robolectric --dontnote libcore.io.Memory --dontnote com.google.protobuf.** --dontnote android.net.** --dontnote org.apache.http.** - -# config for mapbox-sdk-services -# while we don't include this dependency directly -# a large amount of users combine it with our SDK -# we aren't able to provide a proguard config in that project (jar vs aar) --dontwarn com.sun.xml.internal.ws.spi.db.* \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/AndroidManifest.xml b/platform/android/MapboxGLAndroidSDK/src/main/AndroidManifest.xml deleted file mode 100644 index dcbec69bf..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/AndroidManifest.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/AccountsManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/AccountsManager.java deleted file mode 100644 index 5b8f10e01..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/AccountsManager.java +++ /dev/null @@ -1,170 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.support.annotation.NonNull; -import android.support.annotation.VisibleForTesting; -import android.text.TextUtils; -import android.text.format.DateUtils; - -import com.mapbox.android.accounts.v1.MapboxAccounts; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.log.Logger; - -import static com.mapbox.mapboxsdk.constants.MapboxConstants.KEY_PREFERENCE_SKU_TOKEN; - -/** - * REMOVAL OR MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS - * OF SERVICE - *

- * The following code is used to access Mapbox's Mapping APIs. - *

- * Removal or modification of this code when used with Mapbox's Mapping APIs - * can result in termination of your agreement and/or your account with - * Mapbox. - *

- * Using this code to access Mapbox Mapping APIs from outside the Mapbox Maps - * SDK also violates the Mapbox Terms of Service. On Android, Mapping APIs - * should be accessed using the methods documented at - * https://www.mapbox.com/android. - *

- * You can access the Mapbox Terms of Service at https://www.mapbox.com/tos/ - */ -class AccountsManager { - private static final String TAG = "Mbgl-AccountsManager"; - private static final String PREFERENCE_USER_ID = "com.mapbox.mapboxsdk.accounts.userid"; - private static final String PREFERENCE_TIMESTAMP = "com.mapbox.mapboxsdk.accounts.timestamp"; - - private SharedPreferences sharedPreferences; - private String skuToken; - private long timestamp; - private boolean isManaged; - - AccountsManager() { - isManaged = isSkuTokenManaged(); - initialize(); - } - - @VisibleForTesting - AccountsManager(SharedPreferences sharedPreferences, boolean isManaged) { - this.sharedPreferences = sharedPreferences; - this.isManaged = isManaged; - initialize(); - } - - private void initialize() { - retrieveSkuTokenAndTimestamp(); - if (isManaged) { - String userId = validateUserId(); - validateRotation(userId); - } - } - - private boolean isSkuTokenManaged() { - boolean value = MapboxConstants.DEFAULT_MANAGE_SKU_TOKEN; - try { - // Try getting a custom value from the app Manifest - ApplicationInfo appInfo = retrieveApplicationInfo(); - if (appInfo.metaData != null) { - value = appInfo.metaData.getBoolean( - MapboxConstants.KEY_META_DATA_MANAGE_SKU_TOKEN, - MapboxConstants.DEFAULT_MANAGE_SKU_TOKEN - ); - } - } catch (Exception exception) { - Logger.e(TAG, "Failed to read the package metadata: ", exception); - } - - return value; - } - - private ApplicationInfo retrieveApplicationInfo() throws PackageManager.NameNotFoundException { - return Mapbox.getApplicationContext().getPackageManager().getApplicationInfo( - Mapbox.getApplicationContext().getPackageName(), - PackageManager.GET_META_DATA); - } - - private void retrieveSkuTokenAndTimestamp() { - SharedPreferences sharedPreferences = getSharedPreferences(); - skuToken = sharedPreferences.getString(KEY_PREFERENCE_SKU_TOKEN, ""); - timestamp = sharedPreferences.getLong(PREFERENCE_TIMESTAMP, 0L); - } - - private String validateUserId() { - SharedPreferences sharedPreferences = getSharedPreferences(); - String userId = sharedPreferences.getString(PREFERENCE_USER_ID, ""); - if (TextUtils.isEmpty(userId)) { - userId = generateUserId(); - SharedPreferences.Editor editor = getSharedPreferences().edit(); - editor.putString(PREFERENCE_USER_ID, userId); - editor.apply(); - } - - return userId; - } - - private void validateRotation(String userId) { - if (TextUtils.isEmpty(skuToken) || timestamp == 0L) { - skuToken = generateSkuToken(userId); - timestamp = persistRotation(skuToken); - } - } - - String getSkuToken() { - if (isManaged) { - if (isExpired()) { - SharedPreferences sharedPreferences = getSharedPreferences(); - String userId = sharedPreferences.getString(PREFERENCE_USER_ID, ""); - skuToken = generateSkuToken(userId); - timestamp = persistRotation(skuToken); - } - } else { - SharedPreferences sharedPreferences = getSharedPreferences(); - String notManagedSkuToken = sharedPreferences.getString(KEY_PREFERENCE_SKU_TOKEN, ""); - skuToken = notManagedSkuToken; - } - return skuToken; - } - - private boolean isExpired() { - return isExpired(getNow(), timestamp); - } - - static boolean isExpired(long now, long then) { - return ((now - then) > DateUtils.HOUR_IN_MILLIS); - } - - private long persistRotation(String skuToken) { - long now = getNow(); - SharedPreferences.Editor editor = getSharedPreferences().edit(); - editor.putLong(PREFERENCE_TIMESTAMP, now); - editor.putString(KEY_PREFERENCE_SKU_TOKEN, skuToken); - editor.apply(); - return now; - } - - @NonNull - private SharedPreferences getSharedPreferences() { - if (sharedPreferences == null) { - sharedPreferences = Mapbox.getApplicationContext() - .getSharedPreferences(MapboxConstants.MAPBOX_SHARED_PREFERENCES, Context.MODE_PRIVATE); - } - return sharedPreferences; - } - - static long getNow() { - return System.currentTimeMillis(); - } - - @NonNull - private String generateUserId() { - return MapboxAccounts.obtainEndUserId(); - } - - @NonNull - private String generateSkuToken(String userId) { - return MapboxAccounts.obtainMapsSkuUserToken(userId); - } -} 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 deleted file mode 100644 index ee9f4b3b6..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.mapbox.mapboxsdk; - -import com.mapbox.mapboxsdk.log.Logger; - -/** - * Loads the mapbox-gl shared library - *

- * By default uses the {@link System#loadLibrary(String)}, - * use {@link #setLibraryLoader(LibraryLoader)} to provide an alternative library loading hook. - *

- */ -public abstract class LibraryLoader { - - private static final String TAG = "Mbgl-LibraryLoader"; - - private static final LibraryLoader DEFAULT = Mapbox.getModuleProvider() - .createLibraryLoaderProvider() - .getDefaultLibraryLoader(); - - private static volatile LibraryLoader loader = DEFAULT; - - private static boolean loaded; - - /** - * 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. - *

- * Catches UnsatisfiedLinkErrors and prints a warning to logcat. - *

- */ - public static void load() { - try { - if (!loaded) { - loaded = true; - loader.load("mapbox-gl"); - } - } catch (UnsatisfiedLinkError error) { - loaded = false; - String message = "Failed to load native shared library."; - Logger.e(TAG, message, error); - MapStrictMode.strictModeViolation(message, error); - } - } - - public abstract void load(String name); -} - diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoaderProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoaderProvider.java deleted file mode 100644 index c9d98bf76..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/LibraryLoaderProvider.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.mapbox.mapboxsdk; - -/** - * Injects the default library loader. - */ -public interface LibraryLoaderProvider { - - /** - * Creates and returns a the default Library Loader. - * - * @return the default library loader - */ - LibraryLoader getDefaultLibraryLoader(); - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictMode.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictMode.java deleted file mode 100644 index c7f995964..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictMode.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.mapbox.mapboxsdk; - -/** - * Using this class you can enable a strict mode that will throw the {@link MapStrictModeException} - * whenever the map would fail silently otherwise. - */ -public class MapStrictMode { - private static volatile boolean strictModeEnabled; - - /** - * Set the strict mode that will throw the {@link MapStrictModeException} - * whenever the map would fail silently otherwise. - * - * @param strictModeEnabled true to enable the strict mode, false otherwise - */ - public static synchronized void setStrictModeEnabled(boolean strictModeEnabled) { - MapStrictMode.strictModeEnabled = strictModeEnabled; - } - - /** - * Internal use. Called whenever the strict mode violation occurs. - */ - public static void strictModeViolation(String message) { - if (strictModeEnabled) { - throw new MapStrictModeException(message); - } - } - - /** - * Internal use. Called whenever the strict mode violation occurs. - */ - public static void strictModeViolation(String message, Throwable throwable) { - if (strictModeEnabled) { - throw new MapStrictModeException(String.format("%s - %s", message, throwable)); - } - } - - /** - * Internal use. Called whenever the strict mode violation occurs. - */ - public static void strictModeViolation(Throwable throwable) { - if (strictModeEnabled) { - throw new MapStrictModeException(String.format("%s", throwable)); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictModeException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictModeException.java deleted file mode 100644 index 5bfddabf9..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/MapStrictModeException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.mapbox.mapboxsdk; - -class MapStrictModeException extends RuntimeException { - MapStrictModeException(String message) { - super(String.format("Map detected an error that would fail silently otherwise: %s", message)); - } -} 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 deleted file mode 100644 index 35f7a5975..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/Mapbox.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.res.AssetManager; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.UiThread; - -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.exceptions.MapboxConfigurationException; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.maps.TelemetryDefinition; -import com.mapbox.mapboxsdk.net.ConnectivityReceiver; -import com.mapbox.mapboxsdk.storage.FileSource; -import com.mapbox.mapboxsdk.utils.ThreadUtils; - -/** - * The entry point to initialize the Mapbox Android SDK. - *

- * Obtain a reference by calling {@link #getInstance(Context, String)}. Usually this class is configured in - * Application#onCreate() and is responsible for the active access token, application context, and - * connectivity state. - *

- */ -@UiThread -@SuppressLint("StaticFieldLeak") -@Keep -public final class Mapbox { - - private static final String TAG = "Mbgl-Mapbox"; - private static ModuleProvider moduleProvider; - private static Mapbox INSTANCE; - - private Context context; - @Nullable - private String accessToken; - @Nullable - private TelemetryDefinition telemetry; - @Nullable - private AccountsManager accounts; - - /** - * Get an instance of Mapbox. - *

- * This class manages the Mapbox access token, application context, and connectivity state. - *

- * - * @param context Android context which holds or is an application context - * @param accessToken Mapbox access token - * @return the single instance of Mapbox - */ - @UiThread - @NonNull - public static synchronized Mapbox getInstance(@NonNull Context context, @Nullable String accessToken) { - ThreadUtils.init(context); - ThreadUtils.checkThread(TAG); - if (INSTANCE == null) { - Context appContext = context.getApplicationContext(); - FileSource.initializeFileDirsPaths(appContext); - INSTANCE = new Mapbox(appContext, accessToken); - if (isAccessTokenValid(accessToken)) { - initializeTelemetry(); - INSTANCE.accounts = new AccountsManager(); - } - ConnectivityReceiver.instance(appContext); - } - return INSTANCE; - } - - Mapbox(@NonNull Context context, @Nullable String accessToken) { - this.context = context; - this.accessToken = accessToken; - } - - /** - * Get the current active access token for this application. - * - * @return Mapbox access token - */ - @Nullable - public static String getAccessToken() { - validateMapbox(); - return INSTANCE.accessToken; - } - - /** - * Set the current active accessToken. - */ - public static void setAccessToken(String accessToken) { - validateMapbox(); - INSTANCE.accessToken = accessToken; - - // cleanup telemetry which is dependent on an access token - if (INSTANCE.telemetry != null) { - INSTANCE.telemetry.disableTelemetrySession(); - INSTANCE.telemetry = null; - } - - // initialize components dependent on a token - if (isAccessTokenValid(accessToken)) { - initializeTelemetry(); - INSTANCE.accounts = new AccountsManager(); - } else { - INSTANCE.accounts = null; - } - FileSource.getInstance(getApplicationContext()).setAccessToken(accessToken); - } - - /** - * Returns a SKU token, refreshed if necessary. This method is meant for internal SDK - * usage only. - * - * @return the SKU token - */ - public static String getSkuToken() { - if (INSTANCE.accounts == null) { - throw new MapboxConfigurationException( - "A valid access token parameter is required when using a Mapbox service." - + "\nPlease see https://www.mapbox.com/help/create-api-access-token/ to learn how to create one." - + "\nMore information in this guide https://www.mapbox.com/help/first-steps-android-sdk/#access-tokens." - + "Currently provided token is: " + INSTANCE.accessToken); - } - return INSTANCE.accounts.getSkuToken(); - } - - /** - * Application context - * - * @return the application context - */ - @NonNull - public static Context getApplicationContext() { - validateMapbox(); - return INSTANCE.context; - } - - /** - * Manually sets the connectivity state of the app. This is useful for apps which control their - * own connectivity state and want to bypass any checks to the ConnectivityManager. - * - * @param connected flag to determine the connectivity state, true for connected, false for - * disconnected, and null for ConnectivityManager to determine. - */ - public static synchronized void setConnected(Boolean connected) { - validateMapbox(); - ConnectivityReceiver.instance(INSTANCE.context).setConnected(connected); - } - - /** - * Determines whether we have an internet connection available. Please do not rely on this - * method in your apps. This method is used internally by the SDK. - * - * @return true if there is an internet connection, false otherwise - */ - public static synchronized Boolean isConnected() { - validateMapbox(); - return ConnectivityReceiver.instance(INSTANCE.context).isConnected(); - } - - /** - * Initializes telemetry - */ - private static void initializeTelemetry() { - try { - INSTANCE.telemetry = getModuleProvider().obtainTelemetry(); - } catch (Exception exception) { - String message = "Error occurred while initializing telemetry"; - Logger.e(TAG, message, exception); - MapStrictMode.strictModeViolation(message, exception); - } - } - - /** - * Get an instance of Telemetry if initialised - * - * @return instance of telemetry - */ - @Nullable - public static TelemetryDefinition getTelemetry() { - return INSTANCE.telemetry; - } - - /** - * Get the module provider - * - * @return moduleProvider - */ - @NonNull - public static ModuleProvider getModuleProvider() { - if (moduleProvider == null) { - moduleProvider = new ModuleProviderImpl(); - } - return moduleProvider; - } - - /** - * Runtime validation of Mapbox creation. - */ - private static void validateMapbox() { - if (INSTANCE == null) { - throw new MapboxConfigurationException(); - } - } - - /** - * Runtime validation of Mapbox access token - * - * @param accessToken the access token to validate - * @return true is valid, false otherwise - */ - static boolean isAccessTokenValid(@Nullable String accessToken) { - if (accessToken == null) { - return false; - } - - accessToken = accessToken.trim().toLowerCase(MapboxConstants.MAPBOX_LOCALE); - return accessToken.length() != 0 && (accessToken.startsWith("pk.") || accessToken.startsWith("sk.")); - } - - /** - * Internal use. Check if the {@link Mapbox#INSTANCE} is present. - */ - public static boolean hasInstance() { - return INSTANCE != null; - } - - /** - * Internal use. Returns AssetManager. - * - * @return the asset manager - */ - private static AssetManager getAssetManager() { - return getApplicationContext().getResources().getAssets(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProvider.java deleted file mode 100644 index 9749290eb..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.http.HttpRequest; -import com.mapbox.mapboxsdk.maps.TelemetryDefinition; - -/** - * Injects concrete instances of configurable abstractions - */ -public interface ModuleProvider { - - /** - * Create a new concrete implementation of HttpRequest. - * - * @return a new instance of an HttpRequest - */ - @NonNull - HttpRequest createHttpRequest(); - - /** - * Get the concrete implementation of TelemetryDefinition - * - * @return a single instance of Telemetry - */ - @Nullable - TelemetryDefinition obtainTelemetry(); - - - /** - * Get the concrete implementation of LibraryLoaderProvider - * - * @return a new instance of LibraryLoaderProvider - */ - @NonNull - LibraryLoaderProvider createLibraryLoaderProvider(); - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProviderImpl.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProviderImpl.java deleted file mode 100644 index 2de111c97..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/ModuleProviderImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.http.HttpRequest; -import com.mapbox.mapboxsdk.maps.TelemetryDefinition; -import com.mapbox.mapboxsdk.module.http.HttpRequestImpl; -import com.mapbox.mapboxsdk.module.loader.LibraryLoaderProviderImpl; -import com.mapbox.mapboxsdk.module.telemetry.TelemetryImpl; - -public class ModuleProviderImpl implements ModuleProvider { - - @Override - @NonNull - public HttpRequest createHttpRequest() { - return new HttpRequestImpl(); - } - - @Override - @Nullable - public TelemetryDefinition obtainTelemetry() { - return new TelemetryImpl(); - } - - @NonNull - @Override - public LibraryLoaderProvider createLibraryLoaderProvider() { - return new LibraryLoaderProviderImpl(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Annotation.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Annotation.java deleted file mode 100644 index 8ea226649..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Annotation.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.support.annotation.NonNull; - -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -/** - * Annotation is an overlay on top of a Map. - *

- * Known subclasses are {@link Polygon}, {@link Polyline} and {@link Marker}. - *

- *

- * This class manages attachment to a map and identification, but does not require - * content to be placed at a geographical point. - *

- * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public abstract class Annotation implements Comparable { - - /** - *

- * The annotation id - *

- * Internal C++ id is stored as unsigned int. - */ - private long id = -1; // -1 unless added to a MapView - protected MapboxMap mapboxMap; - protected MapView mapView; - - protected Annotation() { - } - - /** - *

- * Gets the annotation's unique ID. - *

- * This ID is unique for a MapView instance and is suitable for associating your own extra - * data with. - * - * @return the assigned id. - */ - public long getId() { - return id; - } - - /** - * Do not use this method, used internally by the SDK. - */ - public void remove() { - if (mapboxMap == null) { - return; - } - mapboxMap.removeAnnotation(this); - } - - /** - * Do not use this method, used internally by the SDK. - * - * @param id the assigned id - */ - public void setId(long id) { - this.id = id; - } - - /** - * Do not use this method, used internally by the SDK. - * - * @param mapboxMap the hosting mapbox map - */ - public void setMapboxMap(MapboxMap mapboxMap) { - this.mapboxMap = mapboxMap; - } - - /** - * Gets the hosting mapbox map. - * - * @return the MapboxMap - */ - protected MapboxMap getMapboxMap() { - return mapboxMap; - } - - /** - * Do not use this method, used internally by the SDK. - * - * @param mapView the hosting map view - */ - public void setMapView(MapView mapView) { - this.mapView = mapView; - } - - /** - * Gets the hosting map view. - * - * @return The MapView - */ - protected MapView getMapView() { - return mapView; - } - - /** - * Compares this Annotation object with another Annotation. - * - * @param annotation Another Annotation to compare with this object. - * @return returns 0 if id's match, 1 if id is lower, -1 if id is higher of another Annotation - */ - @Override - public int compareTo(@NonNull Annotation annotation) { - if (id < annotation.getId()) { - return 1; - } else if (id > annotation.getId()) { - return -1; - } - return 0; - } - - /** - * Checks if this Annotation object is equal to another Annotation. - * - * @param object Another Annotation to check equality with this object. - * @return returns true both id's match else returns false. - */ - @Override - public boolean equals(@Nullable Object object) { - if (this == object) { - return true; - } - if (object == null || !(object instanceof Annotation)) { - return false; - } - Annotation that = (Annotation) object; - return id == that.getId(); - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - return (int) (getId() ^ (getId() >>> 32)); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/ArrowDirection.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/ArrowDirection.java deleted file mode 100644 index 220544815..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/ArrowDirection.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.support.annotation.IntDef; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Deprecated -class ArrowDirection { - @IntDef( {LEFT, RIGHT, TOP, BOTTOM}) - @Retention(RetentionPolicy.SOURCE) - @interface Value { - } - - static final int LEFT = 0; - static final int RIGHT = 1; - static final int TOP = 2; - static final int BOTTOM = 3; - - @Value - private final int value; - - ArrowDirection(@Value int value) { - this.value = value; - } - - @Value - public int getValue() { - return value; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BaseMarkerOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BaseMarkerOptions.java deleted file mode 100644 index 384ff8c0a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BaseMarkerOptions.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -/** - * Abstract builder class for composing custom Marker objects. - *

- * Extending this class requires implementing Parceable interface. - * - * @param Type of the marker to be composed - * @param Type of the builder to be used for composing a custom Marker - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public abstract class BaseMarkerOptions> implements Parcelable { - - protected LatLng position; - protected String snippet; - protected String title; - protected Icon icon; - - /** - * Set the geographical location of the Marker. - * - * @param position the location to position the {@link Marker}. - * @return the object for which the method was called. - */ - public T position(LatLng position) { - this.position = position; - return getThis(); - } - - /** - * Set the snippet of the Marker. - * - * @param snippet the snippet of the {@link Marker}. - * @return the object for which the method was called. - */ - public T snippet(String snippet) { - this.snippet = snippet; - return getThis(); - } - - /** - * Set the title of the Marker. - * - * @param title the title of the {@link Marker}. - * @return the object for which the method was called. - */ - public T title(String title) { - this.title = title; - return getThis(); - } - - /** - * Set the icon of the Marker. - * - * @param icon the icon of the {@link Marker}. - * @return the object for which the method was called. - */ - public T icon(Icon icon) { - this.icon = icon; - return getThis(); - } - - /** - * Set the icon of the Marker. - * - * @param icon the icon of the {@link Marker}. - * @return the object for which the method was called. - */ - public T setIcon(Icon icon) { - return icon(icon); - } - - /** - * Set the geographical location of the Marker. - * - * @param position the location to position the {@link Marker}. - * @return the object for which the method was called. - */ - public T setPosition(LatLng position) { - return position(position); - } - - /** - * Set the snippet of the Marker. - * - * @param snippet the snippet of the {@link Marker}. - * @return the object for which the method was called. - */ - public T setSnippet(String snippet) { - return snippet(snippet); - } - - /** - * Set the title of the Marker. - * - * @param title the title of the {@link Marker}. - * @return the object for which the method was called. - */ - public T setTitle(String title) { - return title(title); - } - - /** - * Get the instance of the object for which this method was called. - * - * @return the object for which the this method was called. - */ - public abstract T getThis(); - - /** - * Get the Marker. - * - * @return the Marker created from this builder. - */ - public abstract U getMarker(); - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BasePointCollection.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BasePointCollection.java deleted file mode 100644 index b94721a80..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BasePointCollection.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.support.annotation.Keep; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import java.util.ArrayList; -import java.util.List; - -/** - * Multipoint is an abstract annotation for combining geographical locations. - * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public abstract class BasePointCollection extends Annotation { - - @Keep - private List points; - @Keep - private float alpha = 1.0f; - - protected BasePointCollection() { - super(); - points = new ArrayList<>(); - } - - /** - * Returns a copy of the points. - * - * @return A {@link List} of points. - */ - @NonNull - public List getPoints() { - return new ArrayList<>(points); - } - - /** - * Sets the points of this polyline. This method will take a copy of the points, so further - * mutations to points will have no effect on this polyline. - * - * @param points A {@link List} of {@link LatLng} points making up the polyline. - */ - public void setPoints(@NonNull List points) { - this.points = new ArrayList<>(points); - update(); - } - - /** - * Add a point to the polyline. - * - * @param point A {@link LatLng} point to be added. - */ - public void addPoint(LatLng point) { - points.add(point); - update(); - } - - /** - * Value between 0 and 1 defining the polyline alpha. - * - * @return float value between 0 and 1. - */ - public float getAlpha() { - return alpha; - } - - /** - * Set this {@link BasePointCollection}s alpha. - * - * @param alpha float value between 0 and 1. - */ - public void setAlpha(float alpha) { - this.alpha = alpha; - update(); - } - - abstract void update(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Bubble.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Bubble.java deleted file mode 100644 index 0768f9c2e..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Bubble.java +++ /dev/null @@ -1,315 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Canvas; -import android.graphics.ColorFilter; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.PixelFormat; -import android.graphics.Rect; -import android.graphics.RectF; -import android.graphics.drawable.Drawable; -import android.support.annotation.NonNull; - -@Deprecated -class Bubble extends Drawable { - - private RectF rect; - private float arrowWidth; - private float arrowHeight; - private float arrowPosition; - private float cornersRadius; - @NonNull - private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); - private float strokeWidth; - private Paint strokePaint; - private Path strokePath; - @NonNull - private Path path = new Path(); - - Bubble(@NonNull RectF rect, @NonNull ArrowDirection arrowDirection, float arrowWidth, float arrowHeight, - float arrowPosition, float cornersRadius, int bubbleColor, float strokeWidth, int strokeColor) { - this.rect = rect; - this.arrowWidth = arrowWidth; - this.arrowHeight = arrowHeight; - this.arrowPosition = arrowPosition; - this.cornersRadius = cornersRadius; - paint.setColor(bubbleColor); - this.strokeWidth = strokeWidth; - - if (strokeWidth > 0) { - strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); - strokePaint.setColor(strokeColor); - strokePath = new Path(); - initPath(arrowDirection, path, strokeWidth); - initPath(arrowDirection, strokePath, 0); - } else { - initPath(arrowDirection, path, 0); - } - } - - @Override - protected void onBoundsChange(Rect bounds) { - super.onBoundsChange(bounds); - } - - @Override - public void draw(@NonNull Canvas canvas) { - if (strokeWidth > 0) { - canvas.drawPath(strokePath, strokePaint); - } - canvas.drawPath(path, paint); - } - - @Override - public int getOpacity() { - return PixelFormat.TRANSLUCENT; - } - - @Override - public void setAlpha(int alpha) { - paint.setAlpha(alpha); - } - - @Override - public void setColorFilter(ColorFilter cf) { - paint.setColorFilter(cf); - } - - @Override - public int getIntrinsicWidth() { - return (int) rect.width(); - } - - @Override - public int getIntrinsicHeight() { - return (int) rect.height(); - } - - private void initPath(@NonNull ArrowDirection arrowDirection, @NonNull Path path, float strokeWidth) { - switch (arrowDirection.getValue()) { - case ArrowDirection.LEFT: - if (cornersRadius <= 0) { - initLeftSquarePath(rect, path, strokeWidth); - break; - } - - if (strokeWidth > 0 && strokeWidth > cornersRadius) { - initLeftSquarePath(rect, path, strokeWidth); - break; - } - - initLeftRoundedPath(rect, path, strokeWidth); - break; - case ArrowDirection.TOP: - if (cornersRadius <= 0) { - initTopSquarePath(rect, path, strokeWidth); - break; - } - - if (strokeWidth > 0 && strokeWidth > cornersRadius) { - initTopSquarePath(rect, path, strokeWidth); - break; - } - - initTopRoundedPath(rect, path, strokeWidth); - break; - case ArrowDirection.RIGHT: - if (cornersRadius <= 0) { - initRightSquarePath(rect, path, strokeWidth); - break; - } - - if (strokeWidth > 0 && strokeWidth > cornersRadius) { - initRightSquarePath(rect, path, strokeWidth); - break; - } - - initRightRoundedPath(rect, path, strokeWidth); - break; - case ArrowDirection.BOTTOM: - if (cornersRadius <= 0) { - initBottomSquarePath(rect, path, strokeWidth); - break; - } - - if (strokeWidth > 0 && strokeWidth > cornersRadius) { - initBottomSquarePath(rect, path, strokeWidth); - break; - } - - initBottomRoundedPath(rect, path, strokeWidth); - break; - } - } - - private void initLeftSquarePath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(arrowWidth + rect.left + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.width() - strokeWidth, rect.top + strokeWidth); - - path.lineTo(rect.right - strokeWidth, rect.bottom - strokeWidth); - - path.lineTo(rect.left + arrowWidth + strokeWidth, rect.bottom - strokeWidth); - - path.lineTo(rect.left + arrowWidth + strokeWidth, arrowHeight + arrowPosition - (strokeWidth / 2)); - path.lineTo(rect.left + strokeWidth + strokeWidth, arrowPosition + arrowHeight / 2); - path.lineTo(rect.left + arrowWidth + strokeWidth, arrowPosition + (strokeWidth / 2)); - - path.lineTo(rect.left + arrowWidth + strokeWidth, rect.top + strokeWidth); - - path.close(); - } - - private void initLeftRoundedPath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(arrowWidth + rect.left + cornersRadius + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.width() - cornersRadius - strokeWidth, rect.top + strokeWidth); - path.arcTo(new RectF(rect.right - cornersRadius, rect.top + strokeWidth, rect.right - strokeWidth, - cornersRadius + rect.top), 270, 90); - - path.lineTo(rect.right - strokeWidth, rect.bottom - cornersRadius - strokeWidth); - path.arcTo(new RectF(rect.right - cornersRadius, rect.bottom - cornersRadius, - rect.right - strokeWidth, rect.bottom - strokeWidth), 0, 90); - - path.lineTo(rect.left + arrowWidth + cornersRadius + strokeWidth, rect.bottom - strokeWidth); - - path.arcTo(new RectF(rect.left + arrowWidth + strokeWidth, rect.bottom - cornersRadius, - cornersRadius + rect.left + arrowWidth, rect.bottom - strokeWidth), 90, 90); - - path.lineTo(rect.left + arrowWidth + strokeWidth, arrowHeight + arrowPosition - (strokeWidth / 2)); - - path.lineTo(rect.left + strokeWidth + strokeWidth, arrowPosition + arrowHeight / 2); - - path.lineTo(rect.left + arrowWidth + strokeWidth, arrowPosition + (strokeWidth / 2)); - - path.lineTo(rect.left + arrowWidth + strokeWidth, rect.top + cornersRadius + strokeWidth); - - path.arcTo(new RectF(rect.left + arrowWidth + strokeWidth, rect.top + strokeWidth, cornersRadius - + rect.left + arrowWidth, cornersRadius + rect.top), 180, 90); - - path.close(); - } - - private void initTopSquarePath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + arrowPosition + strokeWidth, rect.top + arrowHeight + strokeWidth); - - path.lineTo(rect.left + arrowPosition + (strokeWidth / 2), rect.top + arrowHeight + strokeWidth); - path.lineTo(rect.left + arrowWidth / 2 + arrowPosition, rect.top + strokeWidth + strokeWidth); - path.lineTo(rect.left + arrowWidth + arrowPosition - (strokeWidth / 2), rect.top + arrowHeight + strokeWidth); - path.lineTo(rect.right - strokeWidth, rect.top + arrowHeight + strokeWidth); - - path.lineTo(rect.right - strokeWidth, rect.bottom - strokeWidth); - - path.lineTo(rect.left + strokeWidth, rect.bottom - strokeWidth); - - path.lineTo(rect.left + strokeWidth, rect.top + arrowHeight + strokeWidth); - - path.lineTo(rect.left + arrowPosition + strokeWidth, rect.top + arrowHeight + strokeWidth); - - path.close(); - } - - private void initTopRoundedPath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + Math.min(arrowPosition, cornersRadius) + strokeWidth, rect.top + arrowHeight - + strokeWidth); - path.lineTo(rect.left + arrowPosition + (strokeWidth / 2), rect.top + arrowHeight + strokeWidth); - path.lineTo(rect.left + arrowWidth / 2 + arrowPosition, rect.top + strokeWidth + strokeWidth); - path.lineTo(rect.left + arrowWidth + arrowPosition - (strokeWidth / 2), rect.top + arrowHeight + strokeWidth); - path.lineTo(rect.right - cornersRadius - strokeWidth, rect.top + arrowHeight + strokeWidth); - - path.arcTo(new RectF(rect.right - cornersRadius, - rect.top + arrowHeight + strokeWidth, rect.right - strokeWidth, cornersRadius + rect.top + arrowHeight), - 270, 90); - path.lineTo(rect.right - strokeWidth, rect.bottom - cornersRadius - strokeWidth); - - path.arcTo(new RectF(rect.right - cornersRadius, rect.bottom - cornersRadius, - rect.right - strokeWidth, rect.bottom - strokeWidth), 0, 90); - path.lineTo(rect.left + cornersRadius + strokeWidth, rect.bottom - strokeWidth); - - path.arcTo(new RectF(rect.left + strokeWidth, rect.bottom - cornersRadius, - cornersRadius + rect.left, rect.bottom - strokeWidth), 90, 90); - - path.lineTo(rect.left + strokeWidth, rect.top + arrowHeight + cornersRadius + strokeWidth); - - path.arcTo(new RectF(rect.left + strokeWidth, rect.top + arrowHeight + strokeWidth, cornersRadius - + rect.left, cornersRadius + rect.top + arrowHeight), 180, 90); - - path.close(); - } - - private void initRightSquarePath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.width() - arrowWidth - strokeWidth, rect.top + strokeWidth); - - path.lineTo(rect.right - arrowWidth - strokeWidth, arrowPosition + (strokeWidth / 2)); - path.lineTo(rect.right - strokeWidth - strokeWidth, arrowPosition + arrowHeight / 2); - path.lineTo(rect.right - arrowWidth - strokeWidth, arrowPosition + arrowHeight - (strokeWidth / 2)); - - path.lineTo(rect.right - arrowWidth - strokeWidth, rect.bottom - strokeWidth); - - path.lineTo(rect.left + strokeWidth, rect.bottom - strokeWidth); - path.lineTo(rect.left + strokeWidth, rect.top + strokeWidth); - - path.close(); - } - - private void initRightRoundedPath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + cornersRadius + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.width() - cornersRadius - arrowWidth - strokeWidth, rect.top + strokeWidth); - path.arcTo(new RectF(rect.right - cornersRadius - arrowWidth, - rect.top + strokeWidth, rect.right - arrowWidth - strokeWidth, cornersRadius + rect.top), 270, 90); - - path.lineTo(rect.right - arrowWidth - strokeWidth, arrowPosition + (strokeWidth / 2)); - path.lineTo(rect.right - strokeWidth - strokeWidth, arrowPosition + arrowHeight / 2); - path.lineTo(rect.right - arrowWidth - strokeWidth, arrowPosition + arrowHeight - (strokeWidth / 2)); - path.lineTo(rect.right - arrowWidth - strokeWidth, rect.bottom - cornersRadius - strokeWidth); - - path.arcTo(new RectF(rect.right - cornersRadius - arrowWidth, rect.bottom - cornersRadius, - rect.right - arrowWidth - strokeWidth, rect.bottom - strokeWidth), 0, 90); - path.lineTo(rect.left + arrowWidth + strokeWidth, rect.bottom - strokeWidth); - - path.arcTo(new RectF(rect.left + strokeWidth, rect.bottom - cornersRadius, - cornersRadius + rect.left, rect.bottom - strokeWidth), 90, 90); - - path.arcTo(new RectF(rect.left + strokeWidth, rect.top + strokeWidth, cornersRadius - + rect.left, cornersRadius + rect.top), 180, 90); - path.close(); - } - - private void initBottomSquarePath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.right - strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.right - strokeWidth, rect.bottom - arrowHeight - strokeWidth); - - path.lineTo(rect.left + arrowWidth + arrowPosition - (strokeWidth / 2), rect.bottom - arrowHeight - strokeWidth); - path.lineTo(rect.left + arrowPosition + arrowWidth / 2, rect.bottom - strokeWidth - strokeWidth); - path.lineTo(rect.left + arrowPosition + (strokeWidth / 2), rect.bottom - arrowHeight - strokeWidth); - path.lineTo(rect.left + arrowPosition + strokeWidth, rect.bottom - arrowHeight - strokeWidth); - - path.lineTo(rect.left + strokeWidth, rect.bottom - arrowHeight - strokeWidth); - path.lineTo(rect.left + strokeWidth, rect.top + strokeWidth); - path.close(); - } - - private void initBottomRoundedPath(@NonNull RectF rect, @NonNull Path path, float strokeWidth) { - path.moveTo(rect.left + cornersRadius + strokeWidth, rect.top + strokeWidth); - path.lineTo(rect.width() - cornersRadius - strokeWidth, rect.top + strokeWidth); - path.arcTo(new RectF(rect.right - cornersRadius, - rect.top + strokeWidth, rect.right - strokeWidth, cornersRadius + rect.top), 270, 90); - - path.lineTo(rect.right - strokeWidth, rect.bottom - arrowHeight - cornersRadius - strokeWidth); - path.arcTo(new RectF(rect.right - cornersRadius, rect.bottom - cornersRadius - arrowHeight, - rect.right - strokeWidth, rect.bottom - arrowHeight - strokeWidth), 0, 90); - - path.lineTo(rect.left + arrowWidth + arrowPosition - (strokeWidth / 2), rect.bottom - arrowHeight - strokeWidth); - path.lineTo(rect.left + arrowPosition + arrowWidth / 2, rect.bottom - strokeWidth - strokeWidth); - path.lineTo(rect.left + arrowPosition + (strokeWidth / 2), rect.bottom - arrowHeight - strokeWidth); - path.lineTo(rect.left + Math.min(cornersRadius, arrowPosition) + strokeWidth, rect.bottom - arrowHeight - - strokeWidth); - - path.arcTo(new RectF(rect.left + strokeWidth, rect.bottom - cornersRadius - arrowHeight, - cornersRadius + rect.left, rect.bottom - arrowHeight - strokeWidth), 90, 90); - path.lineTo(rect.left + strokeWidth, rect.top + cornersRadius + strokeWidth); - path.arcTo(new RectF(rect.left + strokeWidth, rect.top + strokeWidth, cornersRadius - + rect.left, cornersRadius + rect.top), 180, 90); - path.close(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubbleLayout.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubbleLayout.java deleted file mode 100644 index f4a1484f8..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubbleLayout.java +++ /dev/null @@ -1,350 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.RectF; -import android.support.annotation.NonNull; -import android.util.AttributeSet; -import android.util.DisplayMetrics; -import android.widget.LinearLayout; - -import com.mapbox.mapboxsdk.R; - -/** - * Bubble View for Android with custom stroke width and color, arrow size, position and direction. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public class BubbleLayout extends LinearLayout { - - public static final float DEFAULT_STROKE_WIDTH = -1; - private ArrowDirection arrowDirection; - private float arrowWidth; - private float arrowHeight; - private float arrowPosition; - private float cornersRadius; - private Bubble bubble; - private int bubbleColor; - private float strokeWidth; - private int strokeColor; - - /** - * Creates an instance of bubble layout. - * - * @param context The context used to inflate this bubble layout - */ - public BubbleLayout(@NonNull Context context) { - this(context, null, 0); - } - - /** - * Creates an instance of bubble layout. - * - * @param context The context used to inflate this bubble layout - * @param attrs The attribute set to initialise this bubble layout from - */ - public BubbleLayout(@NonNull Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - /** - * Creates an instance of bubble layout. - * - * @param context The context used to inflate this bubble layout - * @param attrs The attribute set to initialise this bubble layout from - * @param defStyleAttr The default style to apply this bubble layout with - */ - public BubbleLayout(@NonNull Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - - TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.mapbox_BubbleLayout); - @ArrowDirection.Value - int location = a.getInt(R.styleable.mapbox_BubbleLayout_mapbox_bl_arrowDirection, - ArrowDirection.LEFT); - arrowDirection = new ArrowDirection(location); - arrowWidth = a.getDimension(R.styleable.mapbox_BubbleLayout_mapbox_bl_arrowWidth, - convertDpToPixel(8, context)); - arrowHeight = a.getDimension(R.styleable.mapbox_BubbleLayout_mapbox_bl_arrowHeight, - convertDpToPixel(8, context)); - arrowPosition = a.getDimension(R.styleable.mapbox_BubbleLayout_mapbox_bl_arrowPosition, - convertDpToPixel(12, context)); - cornersRadius = a.getDimension(R.styleable.mapbox_BubbleLayout_mapbox_bl_cornersRadius, 0); - bubbleColor = a.getColor(R.styleable.mapbox_BubbleLayout_mapbox_bl_bubbleColor, Color.WHITE); - strokeWidth = - a.getDimension(R.styleable.mapbox_BubbleLayout_mapbox_bl_strokeWidth, DEFAULT_STROKE_WIDTH); - strokeColor = a.getColor(R.styleable.mapbox_BubbleLayout_mapbox_bl_strokeColor, Color.GRAY); - - a.recycle(); - initPadding(); - } - - @Override - protected void onLayout(boolean changed, int left, int top, int right, int bottom) { - super.onLayout(changed, left, top, right, bottom); - initDrawable(0, getWidth(), 0, getHeight()); - } - - @Override - protected void dispatchDraw(@NonNull Canvas canvas) { - if (bubble != null) { - bubble.draw(canvas); - } - super.dispatchDraw(canvas); - } - - static float convertDpToPixel(float dp, Context context) { - DisplayMetrics metrics = context.getResources().getDisplayMetrics(); - return dp * (metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); - } - - /** - * Get the arrow direction. - * - * @return the arrow direction - */ - public ArrowDirection getArrowDirection() { - return arrowDirection; - } - - /** - * Set the arrow direction. - * - * @param arrowDirection The direction of the arrow - * @return this - */ - @NonNull - public BubbleLayout setArrowDirection(ArrowDirection arrowDirection) { - resetPadding(); - this.arrowDirection = arrowDirection; - initPadding(); - return this; - } - - /** - * Get the arrow width. - * - * @return the width of the arrow - */ - public float getArrowWidth() { - return arrowWidth; - } - - /** - * Set the arrow width. - * - * @param arrowWidth The width of the arrow - * @return this - */ - @NonNull - public BubbleLayout setArrowWidth(float arrowWidth) { - resetPadding(); - this.arrowWidth = arrowWidth; - initPadding(); - return this; - } - - /** - * Get the arrow height - * - * @return the height of the arrow - */ - public float getArrowHeight() { - return arrowHeight; - } - - /** - * Set the arrow height. - * - * @param arrowHeight The height of the arrow - * @return this - */ - @NonNull - public BubbleLayout setArrowHeight(float arrowHeight) { - resetPadding(); - this.arrowHeight = arrowHeight; - initPadding(); - return this; - } - - /** - * Get the arrow position. - * - * @return the arrow position - */ - public float getArrowPosition() { - return arrowPosition; - } - - /** - * Get the arrow position. - * - * @param arrowPosition The arrow position - * @return this - */ - @NonNull - public BubbleLayout setArrowPosition(float arrowPosition) { - resetPadding(); - this.arrowPosition = arrowPosition; - initPadding(); - return this; - } - - /** - * Get the corner radius - * - * @return the corner radius - */ - public float getCornersRadius() { - return cornersRadius; - } - - /** - * Set the corner radius - * - * @param cornersRadius The corner radius - * @return this - */ - @NonNull - public BubbleLayout setCornersRadius(float cornersRadius) { - this.cornersRadius = cornersRadius; - requestLayout(); - return this; - } - - /** - * Get the bubble color. - * - * @return the bubble color - */ - public int getBubbleColor() { - return bubbleColor; - } - - /** - * Set the bubble color. - * - * @param bubbleColor The buble color - * @return this - */ - @NonNull - public BubbleLayout setBubbleColor(int bubbleColor) { - this.bubbleColor = bubbleColor; - requestLayout(); - return this; - } - - /** - * Get stroke width. - * - * @return the stroke width - */ - public float getStrokeWidth() { - return strokeWidth; - } - - /** - * Set the stroke width. - * - * @param strokeWidth The stroke width - * @return this - */ - @NonNull - public BubbleLayout setStrokeWidth(float strokeWidth) { - resetPadding(); - this.strokeWidth = strokeWidth; - initPadding(); - return this; - } - - /** - * Get the stroke color. - * - * @return the stroke color - */ - public int getStrokeColor() { - return strokeColor; - } - - /** - * Set the stroke color. - * - * @param strokeColor The stroke color - * @return this - */ - @NonNull - public BubbleLayout setStrokeColor(int strokeColor) { - this.strokeColor = strokeColor; - requestLayout(); - return this; - } - - private void initPadding() { - int paddingLeft = getPaddingLeft(); - int paddingRight = getPaddingRight(); - int paddingTop = getPaddingTop(); - int paddingBottom = getPaddingBottom(); - switch (arrowDirection.getValue()) { - case ArrowDirection.LEFT: - paddingLeft += arrowWidth; - break; - case ArrowDirection.RIGHT: - paddingRight += arrowWidth; - break; - case ArrowDirection.TOP: - paddingTop += arrowHeight; - break; - case ArrowDirection.BOTTOM: - paddingBottom += arrowHeight; - break; - } - if (strokeWidth > 0) { - paddingLeft += strokeWidth; - paddingRight += strokeWidth; - paddingTop += strokeWidth; - paddingBottom += strokeWidth; - } - setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); - } - - private void initDrawable(int left, int right, int top, int bottom) { - if (right < left || bottom < top) { - return; - } - - RectF rectF = new RectF(left, top, right, bottom); - bubble = new Bubble(rectF, arrowDirection, arrowWidth, arrowHeight, arrowPosition, cornersRadius, - bubbleColor, strokeWidth, strokeColor); - } - - private void resetPadding() { - int paddingLeft = getPaddingLeft(); - int paddingRight = getPaddingRight(); - int paddingTop = getPaddingTop(); - int paddingBottom = getPaddingBottom(); - switch (arrowDirection.getValue()) { - case ArrowDirection.LEFT: - paddingLeft -= arrowWidth; - break; - case ArrowDirection.RIGHT: - paddingRight -= arrowWidth; - break; - case ArrowDirection.TOP: - paddingTop -= arrowHeight; - break; - case ArrowDirection.BOTTOM: - paddingBottom -= arrowHeight; - break; - } - if (strokeWidth > 0) { - paddingLeft -= strokeWidth; - paddingRight -= strokeWidth; - paddingTop -= strokeWidth; - paddingBottom -= strokeWidth; - } - setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubblePopupHelper.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubblePopupHelper.java deleted file mode 100644 index 055bfe536..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/BubblePopupHelper.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.content.Context; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.support.annotation.NonNull; -import android.view.ViewGroup; -import android.widget.PopupWindow; - -import com.mapbox.mapboxsdk.R; - -@Deprecated -class BubblePopupHelper { - - @NonNull - static PopupWindow create(@NonNull Context context, @NonNull BubbleLayout bubbleLayout) { - PopupWindow popupWindow = new PopupWindow(context); - - popupWindow.setContentView(bubbleLayout); - popupWindow.setOutsideTouchable(true); - popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); - popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); - popupWindow.setAnimationStyle(android.R.style.Animation_Dialog); - // change background color to transparent - Drawable drawable; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - drawable = context.getDrawable(R.drawable.mapbox_popup_window_transparent); - } else { - drawable = context.getResources().getDrawable(R.drawable.mapbox_popup_window_transparent); - } - popupWindow.setBackgroundDrawable(drawable); - - return popupWindow; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Icon.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Icon.java deleted file mode 100644 index 7ace11350..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Icon.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.util.DisplayMetrics; - -import java.nio.ByteBuffer; - -/** - * Icon is the visual representation of a Marker on a MapView. - * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public class Icon { - - private Bitmap mBitmap; - private String mId; - - Icon(String id, Bitmap bitmap) { - mId = id; - mBitmap = bitmap; - } - - /** - * String identifier for this icon. - * - * @return String identifier for this icon. - */ - public String getId() { - return mId; - } - - /** - * Get the bitmap being used for this icon. - * - * @return The bitmap being used for the icon. - */ - public Bitmap getBitmap() { - if (mBitmap != null && mBitmap.getConfig() != Bitmap.Config.ARGB_8888) { - mBitmap = mBitmap.copy(Bitmap.Config.ARGB_8888, false); - } - return mBitmap; - } - - /** - * Get the icon bitmap scale. - *

- * Requires the bitmap to be set before calling this method. - *

- * - * @return the scale of the bitmap - */ - public float getScale() { - if (mBitmap == null) { - throw new IllegalStateException("Required to set a Icon before calling getScale"); - } - float density = mBitmap.getDensity(); - if (density == Bitmap.DENSITY_NONE) { - density = DisplayMetrics.DENSITY_DEFAULT; - } - return density / DisplayMetrics.DENSITY_DEFAULT; - } - - /** - * Get the icon bitmap bytes. - *

- * Requires the bitmap to be set before calling this method. - *

- * - * @return the bytes of the bitmap - */ - @NonNull - public byte[] toBytes() { - if (mBitmap == null) { - throw new IllegalStateException("Required to set a Icon before calling toBytes"); - } - ByteBuffer buffer = ByteBuffer.allocate(mBitmap.getRowBytes() * mBitmap.getHeight()); - mBitmap.copyPixelsToBuffer(buffer); - return buffer.array(); - } - - /** - * Compares this icon object with another icon and determines if they match. - * - * @param object Another iconi to compare with this object. - * @return True if the icon being passed in matches this icon object. Else, false. - */ - @Override - public boolean equals(@Nullable Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - - Icon icon = (Icon) object; - return mBitmap.equals(icon.mBitmap) && mId.equals(icon.mId); - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - int result = 0; - if (mBitmap != null) { - result = mBitmap.hashCode(); - } - if (mId != null) { - result = 31 * result + mId.hashCode(); - } - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/IconFactory.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/IconFactory.java deleted file mode 100644 index 9f0fa62cd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/IconFactory.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.support.annotation.DrawableRes; -import android.support.annotation.NonNull; -import android.util.DisplayMetrics; -import android.view.WindowManager; - -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.exceptions.TooManyIconsException; -import com.mapbox.mapboxsdk.utils.BitmapUtils; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -/** - * Factory for creating Icons from bitmap images. - *

- * icon is used to display bitmaps on top of the map using {@link Marker}. - *

- * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class IconFactory { - - private static final String ICON_ID_PREFIX = "com.mapbox.icons.icon_"; - - private Context context; - @SuppressLint("StaticFieldLeak") - private static IconFactory instance; - private Icon defaultMarker; - private BitmapFactory.Options options; - - private int nextId = 0; - - /** - * Get a single instance of IconFactory. - * - * @param context the context to derive the application context from - * @return the single instance of IconFactory - */ - public static synchronized IconFactory getInstance(@NonNull Context context) { - if (instance == null) { - instance = new IconFactory(context.getApplicationContext()); - } - return instance; - } - - private IconFactory(@NonNull Context context) { - this.context = context; - DisplayMetrics realMetrics = null; - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - realMetrics = new DisplayMetrics(); - wm.getDefaultDisplay().getRealMetrics(realMetrics); - } - wm.getDefaultDisplay().getMetrics(metrics); - - options = new BitmapFactory.Options(); - options.inScaled = true; - options.inDensity = DisplayMetrics.DENSITY_DEFAULT; - options.inTargetDensity = metrics.densityDpi; - if (realMetrics != null) { - options.inScreenDensity = realMetrics.densityDpi; - } - } - - /** - * Creates an icon from a given Bitmap image. - * - * @param bitmap image used for creating the Icon. - * @return The icon using the given Bitmap image. - */ - public Icon fromBitmap(@NonNull Bitmap bitmap) { - if (nextId < 0) { - throw new TooManyIconsException(); - } - String id = ICON_ID_PREFIX + ++nextId; - return new Icon(id, bitmap); - } - - /** - * Creates an icon using the resource ID of a Bitmap image. - * - * @param resourceId The resource ID of a Bitmap image. - * @return The icon that was loaded from the asset or {@code null} if failed to load. - */ - public Icon fromResource(@DrawableRes int resourceId) { - Drawable drawable = BitmapUtils.getDrawableFromRes(context, resourceId); - if (drawable instanceof BitmapDrawable) { - BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; - return fromBitmap(bitmapDrawable.getBitmap()); - } else { - throw new IllegalArgumentException("Failed to decode image. The resource provided must be a Bitmap."); - } - } - - /** - * Provides an icon using the default marker icon used for {@link Marker}. - * - * @return An icon with the default {@link Marker} icon. - */ - public Icon defaultMarker() { - if (defaultMarker == null) { - defaultMarker = fromResource(R.drawable.mapbox_marker_icon_default); - } - return defaultMarker; - } - - private Icon fromInputStream(@NonNull InputStream is) { - Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); - return fromBitmap(bitmap); - } - - /** - * Creates an Icon using the name of a Bitmap image in the assets directory. - * - * @param assetName The name of a Bitmap image in the assets directory. - * @return The Icon that was loaded from the asset or null if failed to load. - */ - public Icon fromAsset(@NonNull String assetName) { - InputStream is; - try { - is = context.getAssets().open(assetName); - } catch (IOException ioException) { - MapStrictMode.strictModeViolation(ioException); - return null; - } - return fromInputStream(is); - } - - /** - * Creates an Icon using the absolute file path of a Bitmap image. - * - * @param absolutePath The absolute path of the Bitmap image. - * @return The Icon that was loaded from the absolute path or null if failed to load. - */ - public Icon fromPath(@NonNull String absolutePath) { - Bitmap bitmap = BitmapFactory.decodeFile(absolutePath, options); - return fromBitmap(bitmap); - } - - /** - * Create an Icon using the name of a Bitmap image file located in the internal storage. - * In particular, this calls Context#openFileInput(String). - * - * @param fileName The name of the Bitmap image file. - * @return The Icon that was loaded from the asset or null if failed to load. - * @see - * Using the Internal Storage - */ - public Icon fromFile(@NonNull String fileName) { - FileInputStream is; - try { - is = context.openFileInput(fileName); - } catch (FileNotFoundException fileNotFoundException) { - MapStrictMode.strictModeViolation(fileNotFoundException); - return null; - } - return fromInputStream(is); - } - - /** - * Create an Icon using a previously created icon identifier along with a provided Bitmap. - * - * @param iconId The Icon identifier you'd like to recreate. - * @param bitmap a Bitmap used to replace the current one. - * @return The Icon using the new Bitmap. - */ - public static Icon recreate(@NonNull String iconId, @NonNull Bitmap bitmap) { - return new Icon(iconId, bitmap); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/InfoWindow.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/InfoWindow.java deleted file mode 100644 index 5bd9aaef1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/InfoWindow.java +++ /dev/null @@ -1,351 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.content.res.Resources; -import android.graphics.PointF; -import android.os.Build; -import android.support.annotation.LayoutRes; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.widget.TextView; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -import java.lang.ref.WeakReference; - -/** - * {@code InfoWindow} is a tooltip shown when a {@link Marker} is tapped. Only - * one info window is displayed at a time. When the user clicks on a marker, the currently open info - * window will be closed and the new info window will be displayed. If the user clicks the same - * marker while its info window is currently open, the info window will be closed. - *

- * The info window is drawn oriented against the device's screen, centered above its associated - * marker by default. The default info window contains the title in bold and snippet text below the title. - * While either the title and - * snippet are optional, at least one is required to open the info window. - *

- * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public class InfoWindow { - - private WeakReference boundMarker; - private WeakReference mapboxMap; - protected WeakReference view; - - private float markerHeightOffset; - private float markerWidthOffset; - private float viewWidthOffset; - private float viewHeightOffset; - private PointF coordinates; - private boolean isVisible; - - @LayoutRes - private int layoutRes; - - InfoWindow(MapView mapView, int layoutResId, MapboxMap mapboxMap) { - layoutRes = layoutResId; - View view = LayoutInflater.from(mapView.getContext()).inflate(layoutResId, mapView, false); - initialize(view, mapboxMap); - } - - InfoWindow(@NonNull View view, MapboxMap mapboxMap) { - initialize(view, mapboxMap); - } - - private void initialize(@NonNull View view, MapboxMap mapboxMap) { - this.mapboxMap = new WeakReference<>(mapboxMap); - isVisible = false; - this.view = new WeakReference<>(view); - - view.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - MapboxMap mapboxMap = InfoWindow.this.mapboxMap.get(); - if (mapboxMap != null) { - MapboxMap.OnInfoWindowClickListener onInfoWindowClickListener = mapboxMap.getOnInfoWindowClickListener(); - boolean handledDefaultClick = false; - if (onInfoWindowClickListener != null) { - handledDefaultClick = onInfoWindowClickListener.onInfoWindowClick(getBoundMarker()); - } - - if (!handledDefaultClick) { - // default behavior: close it when clicking on the tooltip: - closeInfoWindow(); - } - } - } - }); - - view.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - MapboxMap mapboxMap = InfoWindow.this.mapboxMap.get(); - if (mapboxMap != null) { - MapboxMap.OnInfoWindowLongClickListener listener = mapboxMap.getOnInfoWindowLongClickListener(); - if (listener != null) { - listener.onInfoWindowLongClick(getBoundMarker()); - } - } - return true; - } - }); - } - - private void closeInfoWindow() { - MapboxMap mapbox = mapboxMap.get(); - Marker marker = boundMarker.get(); - if (marker != null && mapbox != null) { - mapbox.deselectMarker(marker); - } - close(); - } - - /** - * Open the info window at the specified position. - * - * @param boundMarker The marker on which is hooked the view. - * @param position to place the window on the map. - * @param offsetX The offset of the view to the position, in pixels. This allows to offset - * the view from the object position. - * @param offsetY The offset of the view to the position, in pixels. This allows to offset - * the view from the object position. - * @return this {@link InfoWindow}. - */ - @NonNull - InfoWindow open(@NonNull MapView mapView, Marker boundMarker, @NonNull LatLng position, int offsetX, int offsetY) { - setBoundMarker(boundMarker); - - MapView.LayoutParams lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, - MapView.LayoutParams.WRAP_CONTENT); - - MapboxMap mapboxMap = this.mapboxMap.get(); - View view = this.view.get(); - if (view != null && mapboxMap != null) { - view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); - - markerHeightOffset = offsetY; - markerWidthOffset = -offsetX; - - // Calculate default Android x,y coordinate - coordinates = mapboxMap.getProjection().toScreenLocation(position); - float x = coordinates.x - (view.getMeasuredWidth() / 2) + offsetX; - float y = coordinates.y - view.getMeasuredHeight() + offsetY; - - if (view instanceof BubbleLayout) { - // only apply repositioning/margin for InfoWindowView - Resources resources = mapView.getContext().getResources(); - - // get right/left popup window - float rightSideInfowWindow = x + view.getMeasuredWidth(); - float leftSideInfoWindow = x; - - // get right/left map view - final float mapRight = mapView.getRight(); - final float mapLeft = mapView.getLeft(); - - float marginHorizontal = resources.getDimension(R.dimen.mapbox_infowindow_margin); - float tipViewOffset = resources.getDimension(R.dimen.mapbox_infowindow_tipview_width) / 2; - float tipViewMarginLeft = view.getMeasuredWidth() / 2 - tipViewOffset; - - boolean outOfBoundsLeft = false; - boolean outOfBoundsRight = false; - - // only optimise margins if view is inside current viewport - if (coordinates.x >= 0 && coordinates.x <= mapView.getWidth() - && coordinates.y >= 0 && coordinates.y <= mapView.getHeight()) { - - // if out of bounds right - if (rightSideInfowWindow > mapRight) { - outOfBoundsRight = true; - x -= rightSideInfowWindow - mapRight; - tipViewMarginLeft += rightSideInfowWindow - mapRight + tipViewOffset; - rightSideInfowWindow = x + view.getMeasuredWidth(); - } - - // fit screen left - if (leftSideInfoWindow < mapLeft) { - outOfBoundsLeft = true; - x += mapLeft - leftSideInfoWindow; - tipViewMarginLeft -= mapLeft - leftSideInfoWindow + tipViewOffset; - leftSideInfoWindow = x; - } - - // Add margin right - if (outOfBoundsRight && mapRight - rightSideInfowWindow < marginHorizontal) { - x -= marginHorizontal - (mapRight - rightSideInfowWindow); - tipViewMarginLeft += marginHorizontal - (mapRight - rightSideInfowWindow) - tipViewOffset; - leftSideInfoWindow = x; - } - - // Add margin left - if (outOfBoundsLeft && leftSideInfoWindow - mapLeft < marginHorizontal) { - x += marginHorizontal - (leftSideInfoWindow - mapLeft); - tipViewMarginLeft -= (marginHorizontal - (leftSideInfoWindow - mapLeft)) - tipViewOffset; - } - } - - // Adjust tipView - ((BubbleLayout) view).setArrowPosition(tipViewMarginLeft); - } - - // set anchor popupwindowview - view.setX(x); - view.setY(y); - - // Calculate x-offset and y-offset for update method - viewWidthOffset = x - coordinates.x - offsetX; - viewHeightOffset = -view.getMeasuredHeight() + offsetY; - - - close(); // if it was already opened - mapView.addView(view, lp); - isVisible = true; - } - return this; - } - - /** - * Close this {@link InfoWindow} if it is visible, otherwise calling this will do nothing. - * - * @return This {@link InfoWindow} - */ - @NonNull - InfoWindow close() { - MapboxMap mapboxMap = this.mapboxMap.get(); - if (isVisible && mapboxMap != null) { - isVisible = false; - View view = this.view.get(); - if (view != null && view.getParent() != null) { - ((ViewGroup) view.getParent()).removeView(view); - } - - Marker marker = getBoundMarker(); - MapboxMap.OnInfoWindowCloseListener listener = mapboxMap.getOnInfoWindowCloseListener(); - if (listener != null) { - listener.onInfoWindowClose(marker); - } - - setBoundMarker(null); - } - return this; - } - - /** - * Constructs the view that is displayed when the InfoWindow opens. This retrieves data from - * overlayItem and shows it in the tooltip. - * - * @param overlayItem the tapped overlay item - */ - void adaptDefaultMarker(@NonNull Marker overlayItem, MapboxMap mapboxMap, @NonNull MapView mapView) { - View view = this.view.get(); - if (view == null) { - view = LayoutInflater.from(mapView.getContext()).inflate(layoutRes, mapView, false); - initialize(view, mapboxMap); - } - this.mapboxMap = new WeakReference<>(mapboxMap); - String title = overlayItem.getTitle(); - TextView titleTextView = ((TextView) view.findViewById(R.id.infowindow_title)); - if (!TextUtils.isEmpty(title)) { - titleTextView.setText(title); - titleTextView.setVisibility(View.VISIBLE); - } else { - titleTextView.setVisibility(View.GONE); - } - - String snippet = overlayItem.getSnippet(); - TextView snippetTextView = ((TextView) view.findViewById(R.id.infowindow_description)); - if (!TextUtils.isEmpty(snippet)) { - snippetTextView.setText(snippet); - snippetTextView.setVisibility(View.VISIBLE); - } else { - snippetTextView.setVisibility(View.GONE); - } - } - - @NonNull - InfoWindow setBoundMarker(Marker boundMarker) { - this.boundMarker = new WeakReference<>(boundMarker); - return this; - } - - @Nullable - Marker getBoundMarker() { - if (boundMarker == null) { - return null; - } - return boundMarker.get(); - } - - /** - * Will result in getting this {@link InfoWindow} and updating the view being displayed. - */ - public void update() { - MapboxMap mapboxMap = this.mapboxMap.get(); - Marker marker = boundMarker.get(); - View view = this.view.get(); - if (mapboxMap != null && marker != null && view != null) { - coordinates = mapboxMap.getProjection().toScreenLocation(marker.getPosition()); - - if (view instanceof BubbleLayout) { - view.setX(coordinates.x + viewWidthOffset - markerWidthOffset); - } else { - view.setX(coordinates.x - (view.getMeasuredWidth() / 2) - markerWidthOffset); - } - view.setY(coordinates.y + viewHeightOffset); - } - } - - void onContentUpdate() { - //recalculate y-offset and update position - View view = this.view.get(); - if (view != null) { - ViewTreeObserver viewTreeObserver = view.getViewTreeObserver(); - if (viewTreeObserver.isAlive()) { - viewTreeObserver.addOnGlobalLayoutListener(contentUpdateListener); - } - } - } - - @Nullable - private final ViewTreeObserver.OnGlobalLayoutListener contentUpdateListener = - new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - View view = InfoWindow.this.view.get(); - if (view != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - view.getViewTreeObserver().removeOnGlobalLayoutListener(this); - } else { - view.getViewTreeObserver().removeGlobalOnLayoutListener(this); - } - viewHeightOffset = -view.getMeasuredHeight() + markerHeightOffset; - update(); - } - } - }; - - /** - * Retrieve this {@link InfoWindow}'s current view being used. - * - * @return This {@link InfoWindow}'s current View. - */ - @Nullable - public View getView() { - return view != null ? view.get() : null; - } - - boolean isVisible() { - return isVisible; - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Marker.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Marker.java deleted file mode 100644 index c26af9436..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Marker.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.View; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -/** - * Marker is an annotation that shows an icon image at a geographical location. The default marker - * uses a provided icon. This icon can be customized using {@link IconFactory} to generate an - * {@link Icon} using a provided image. Markers are added to the map by first giving a - * {@link LatLng} and using {@link MapboxMap#addMarker(MarkerOptions)}. The marker icon will be - * centered at this position so it is common to add padding to the icon image before usage. - *

- * Markers are designed to be interactive. They receive click events by default, and are often used - * with event listeners to bring up info windows. An {@link InfoWindow} is displayed by default when - * either a title or snippet is provided. - *

- * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public class Marker extends Annotation { - - @Keep - private LatLng position; - private String snippet; - @Nullable - private Icon icon; - //Redundantly stored for JNI access - @Nullable - @Keep - private String iconId; - private String title; - - @Nullable - private InfoWindow infoWindow; - private boolean infoWindowShown; - - private int topOffsetPixels; - private int rightOffsetPixels; - - /** - * Constructor - */ - Marker() { - super(); - } - - /** - * Creates a instance of {@link Marker} using the builder of Marker. - * - * @param baseMarkerOptions The builder used to construct the Marker. - */ - public Marker(BaseMarkerOptions baseMarkerOptions) { - this(baseMarkerOptions.position, baseMarkerOptions.icon, baseMarkerOptions.title, baseMarkerOptions.snippet); - } - - Marker(LatLng position, Icon icon, String title, String snippet) { - this.position = position; - this.title = title; - this.snippet = snippet; - setIcon(icon); - } - - /** - * Returns the position of the marker. - * - * @return A {@link LatLng} object specifying the marker's current position. - */ - public LatLng getPosition() { - return position; - } - - /** - * Gets the snippet of the marker. - * - * @return A string containing the marker's snippet. - */ - public String getSnippet() { - return snippet; - } - - /** - * Gets the snippet of the marker. - * - * @return A string containing the marker's snippet. - */ - public String getTitle() { - return title; - } - - /** - * Do not use this method, used internally by the SDK. - */ - public void hideInfoWindow() { - if (infoWindow != null) { - infoWindow.close(); - } - infoWindowShown = false; - } - - /** - * Do not use this method, used internally by the SDK. - * - * @return true if the infoWindow is shown - */ - public boolean isInfoWindowShown() { - return infoWindowShown; - } - - /** - * Sets the location of the marker. - * - * @param position A {@link LatLng} defining the marker position. - */ - public void setPosition(LatLng position) { - this.position = position; - MapboxMap map = getMapboxMap(); - if (map != null) { - map.updateMarker(this); - } - } - - /** - * Sets the snippet of the marker. - * - * @param snippet A String used in the marker info window. If {@code null}, the snippet is - * cleared. - */ - public void setSnippet(String snippet) { - this.snippet = snippet; - refreshInfoWindowContent(); - } - - /** - * Sets the icon of the marker. - * - * @param icon The {@link Icon} to be used as Marker image - */ - public void setIcon(@Nullable Icon icon) { - this.icon = icon; - this.iconId = icon != null ? icon.getId() : null; - MapboxMap map = getMapboxMap(); - if (map != null) { - map.updateMarker(this); - } - } - - /** - * Gets the {@link Icon} currently used for the marker. If no Icon was set for the marker, the - * default icon will be returned. - * - * @return The {@link Icon} the marker is using. - */ - @Nullable - public Icon getIcon() { - return icon; - } - - /** - * Sets the title of the marker. - * - * @param title A String used in the marker info window. If {@code null}, the title is - * cleared. - */ - public void setTitle(String title) { - this.title = title; - refreshInfoWindowContent(); - } - - /** - * Gets the {@link InfoWindow} the marker is using. If the marker hasn't had an info window - * defined, this will return {@code null}. - * - * @return The info window the marker is using. - */ - @Nullable - public InfoWindow getInfoWindow() { - return infoWindow; - } - - /** - * Update only for default Marker's InfoWindow content for Title and Snippet - */ - private void refreshInfoWindowContent() { - if (isInfoWindowShown() && mapView != null && mapboxMap != null && mapboxMap.getInfoWindowAdapter() == null) { - InfoWindow infoWindow = getInfoWindow(mapView); - if (mapView.getContext() != null) { - infoWindow.adaptDefaultMarker(this, mapboxMap, mapView); - } - MapboxMap map = getMapboxMap(); - if (map != null) { - map.updateMarker(this); - } - infoWindow.onContentUpdate(); - } - } - - /** - * Do not use this method, used internally by the SDK. Use {@link MapboxMap#selectMarker(Marker)} - * if you want to programmatically display the markers info window. - * - * @param mapboxMap The hosting mapbox map. - * @param mapView The hosting map view. - * @return The info window that was shown. - */ - @Nullable - public InfoWindow showInfoWindow(@NonNull MapboxMap mapboxMap, @NonNull MapView mapView) { - setMapboxMap(mapboxMap); - setMapView(mapView); - MapboxMap.InfoWindowAdapter infoWindowAdapter = getMapboxMap().getInfoWindowAdapter(); - if (infoWindowAdapter != null) { - // end developer is using a custom InfoWindowAdapter - View content = infoWindowAdapter.getInfoWindow(this); - if (content != null) { - infoWindow = new InfoWindow(content, mapboxMap); - showInfoWindow(infoWindow, mapView); - return infoWindow; - } - } - - InfoWindow infoWindow = getInfoWindow(mapView); - if (mapView.getContext() != null) { - infoWindow.adaptDefaultMarker(this, mapboxMap, mapView); - } - return showInfoWindow(infoWindow, mapView); - } - - @NonNull - private InfoWindow showInfoWindow(InfoWindow iw, MapView mapView) { - iw.open(mapView, this, getPosition(), rightOffsetPixels, topOffsetPixels); - infoWindowShown = true; - return iw; - } - - @Nullable - private InfoWindow getInfoWindow(@NonNull MapView mapView) { - if (infoWindow == null && mapView.getContext() != null) { - infoWindow = new InfoWindow(mapView, R.layout.mapbox_infowindow_content, getMapboxMap()); - } - return infoWindow; - } - - /** - * Do not use this method, used internally by the SDK. - * - * @param topOffsetPixels the top offset pixels. - */ - public void setTopOffsetPixels(int topOffsetPixels) { - this.topOffsetPixels = topOffsetPixels; - } - - /** - * Do not use this method, used internally by the SDK. - * - * @param rightOffsetPixels the right offset pixels. - */ - public void setRightOffsetPixels(int rightOffsetPixels) { - this.rightOffsetPixels = rightOffsetPixels; - } - - /** - * Returns a String with the marker position. - * - * @return A String with the marker position. - */ - @Override - public String toString() { - return "Marker [position[" + getPosition() + "]]"; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/MarkerOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/MarkerOptions.java deleted file mode 100644 index 62c3d378e..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/MarkerOptions.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; -import android.os.Parcel; -import android.os.Parcelable; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.exceptions.InvalidMarkerPositionException; -import com.mapbox.mapboxsdk.geometry.LatLng; - -/** - *

- * Builder for composing {@link Marker} objects. See {@link Marker} for additional information. - *

- *

Example

- *
- * mapView.addMarker(new MarkerOptions()
- *   .title("Intersection")
- *   .snippet("H St NW with 15th St NW")
- *   .position(new LatLng(38.9002073, -77.03364419)));
- * 
- * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class MarkerOptions extends BaseMarkerOptions implements Parcelable { - - /** - * Defines options for a Marker. - */ - public MarkerOptions() { - } - - protected MarkerOptions(Parcel in) { - position((LatLng) in.readParcelable(LatLng.class.getClassLoader())); - snippet(in.readString()); - title(in.readString()); - if (in.readByte() != 0) { - // this means we have an icon - String iconId = in.readString(); - Bitmap iconBitmap = in.readParcelable(Bitmap.class.getClassLoader()); - Icon icon = new Icon(iconId, iconBitmap); - icon(icon); - } - } - - @NonNull - @Override - public MarkerOptions getThis() { - return this; - } - - /** - * Describe the kinds of special objects contained in this Parcelable's - * marshalled representation. - * - * @return integer 0. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written. May be 0 or - * {@link #PARCELABLE_WRITE_RETURN_VALUE}. - */ - @Override - public void writeToParcel(Parcel out, int flags) { - out.writeParcelable(getPosition(), flags); - out.writeString(getSnippet()); - out.writeString(getTitle()); - Icon icon = getIcon(); - out.writeByte((byte) (icon != null ? 1 : 0)); - if (icon != null) { - out.writeString(getIcon().getId()); - out.writeParcelable(getIcon().getBitmap(), flags); - } - } - - /** - * Do not use this method. Used internally by the SDK. - * - * @return Marker The build marker - */ - public Marker getMarker() { - if (position == null) { - throw new InvalidMarkerPositionException(); - } - - return new Marker(position, icon, title, snippet); - } - - /** - * Returns the position set for this {@link MarkerOptions} object. - * - * @return A {@link LatLng} object specifying the marker's current position. - */ - public LatLng getPosition() { - return position; - } - - /** - * Gets the snippet set for this {@link MarkerOptions} object. - * - * @return A string containing the marker's snippet. - */ - public String getSnippet() { - return snippet; - } - - /** - * Gets the title set for this {@link MarkerOptions} object. - * - * @return A string containing the marker's title. - */ - public String getTitle() { - return title; - } - - /** - * Gets the custom icon set for this {@link MarkerOptions} object. - * - * @return A {@link Icon} object that the marker is using. If the icon wasn't set, default icon - * will return. - */ - public Icon getIcon() { - return icon; - } - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public MarkerOptions createFromParcel(@NonNull Parcel in) { - return new MarkerOptions(in); - } - - public MarkerOptions[] newArray(int size) { - return new MarkerOptions[size]; - } - }; - - /** - * Compares this {@link MarkerOptions} object with another {@link MarkerOptions} and - * determines if their properties match. - * - * @param o Another {@link MarkerOptions} to compare with this object. - * @return True if marker properties match this {@link MarkerOptions} object. - * Else, false. - */ - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - MarkerOptions marker = (MarkerOptions) o; - - if (getPosition() != null ? !getPosition().equals(marker.getPosition()) : marker.getPosition() != null) { - return false; - } - if (getSnippet() != null ? !getSnippet().equals(marker.getSnippet()) : marker.getSnippet() != null) { - return false; - } - if (getIcon() != null ? !getIcon().equals(marker.getIcon()) : marker.getIcon() != null) { - return false; - } - return !(getTitle() != null ? !getTitle().equals(marker.getTitle()) : marker.getTitle() != null); - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - int result = 1; - result = 31 * result + (getPosition() != null ? getPosition().hashCode() : 0); - result = 31 * result + (getSnippet() != null ? getSnippet().hashCode() : 0); - result = 31 * result + (getIcon() != null ? getIcon().hashCode() : 0); - result = 31 * result + (getTitle() != null ? getTitle().hashCode() : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polygon.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polygon.java deleted file mode 100644 index 5f6cef8d4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polygon.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Color; -import android.support.annotation.Keep; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -import java.util.ArrayList; -import java.util.List; - -/** - * Polygon is a geometry annotation that's a closed loop of coordinates. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class Polygon extends BasePointCollection { - - @Keep - private int fillColor = Color.BLACK; // default fillColor is black - @Keep - private int strokeColor = Color.BLACK; // default strokeColor is black - @Keep - private List> holes; - - Polygon() { - super(); - holes = new ArrayList<>(); - } - - /** - * Get the color of the fill region of the polygon. - * - * @return The color of the fill. - */ - public int getFillColor() { - return fillColor; - } - - /** - * Get the color of the stroke of the polygon. - * - * @return The color of the stroke. - */ - public int getStrokeColor() { - return strokeColor; - } - - /** - * Returns a copy of the holes. - * - * @return A {@link List} of {@link List} of {@link LatLng} points making up the holes. - */ - public List> getHoles() { - return new ArrayList<>(holes); - } - - /** - * Sets the color of the fill region of the polygon. - * - * @param color The color in ARGB format. - */ - public void setFillColor(int color) { - fillColor = color; - update(); - } - - /** - * Sets the color of the stroke of the polygon. - * - * @param color The color in ARGB format. - */ - public void setStrokeColor(int color) { - strokeColor = color; - update(); - } - - /** - * Sets the holes of this polygon. This method will take a copy of the holes, so further - * mutations to holes will have no effect on this polygon. - * - * @param holes A {@link List} of {@link List} of {@link LatLng} points making up the holes. - */ - public void setHoles(@NonNull List> holes) { - this.holes = new ArrayList<>(holes); - update(); - } - - /** - * Add a hole to the polygon. - * - * @param hole A {@link List} of {@link List} of {@link LatLng} points making up the hole to be added. - */ - void addHole(List hole) { - holes.add(hole); - update(); - } - - @Override - void update() { - MapboxMap mapboxMap = getMapboxMap(); - if (mapboxMap != null) { - mapboxMap.updatePolygon(this); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolygonOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolygonOptions.java deleted file mode 100644 index 452420fcb..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolygonOptions.java +++ /dev/null @@ -1,308 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - - -import android.os.Parcel; -import android.os.Parcelable; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import java.util.ArrayList; -import java.util.List; - -/** - * Builder for composing {@link Polygon} objects. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class PolygonOptions implements Parcelable { - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public PolygonOptions createFromParcel(@NonNull Parcel in) { - return new PolygonOptions(in); - } - - public PolygonOptions[] newArray(int size) { - return new PolygonOptions[size]; - } - }; - - private PolygonOptions(Parcel in) { - polygon = new Polygon(); - List pointsList = new ArrayList<>(); - in.readList(pointsList, LatLng.class.getClassLoader()); - addAll(pointsList); - List> holes = new ArrayList<>(); - in.readList(holes, LatLng.class.getClassLoader()); - addAllHoles(holes); - alpha(in.readFloat()); - fillColor(in.readInt()); - strokeColor(in.readInt()); - } - - /** - * Describe the kinds of special objects contained in this Parcelable's - * marshalled representation. - * - * @return integer 0. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written. May be 0 or - * {@link #PARCELABLE_WRITE_RETURN_VALUE}. - */ - @Override - public void writeToParcel(Parcel out, int flags) { - out.writeList(getPoints()); - out.writeList(getHoles()); - out.writeFloat(getAlpha()); - out.writeInt(getFillColor()); - out.writeInt(getStrokeColor()); - } - - private Polygon polygon; - - /** - * Defines options for a polygon. - */ - public PolygonOptions() { - polygon = new Polygon(); - } - - /** - * Adds a vertex to the outline of the polygon being built. - * - * @param point {@link LatLng} point to be added to polygon geometry. - * @return This {@link PolygonOptions} object with the given point added to the outline. - */ - @NonNull - public PolygonOptions add(LatLng point) { - polygon.addPoint(point); - return this; - } - - /** - * Adds vertices to the outline of the polygon being built. - * - * @param points {@link LatLng} points to be added to polygon geometry. - * @return This {@link PolygonOptions} object with the given points added to the outline. - */ - @NonNull - public PolygonOptions add(LatLng... points) { - for (LatLng point : points) { - add(point); - } - return this; - } - - /** - * Adds vertices to the outline of the polygon being built. - * - * @param points {@link Iterable} list made up of {@link LatLng} points defining the polygon - * geometry - * @return This {@link PolygonOptions} object with the given points added to the outline. - */ - @NonNull - public PolygonOptions addAll(Iterable points) { - for (LatLng point : points) { - add(point); - } - return this; - } - - /** - * Adds a hole to the outline of the polygon being built. - * - * @param hole {@link List} list made up of {@link LatLng} points defining the hole - * @return This {@link PolygonOptions} object with the given hole added to the outline. - */ - @NonNull - public PolygonOptions addHole(List hole) { - polygon.addHole(hole); - return this; - } - - /** - * Adds holes to the outline of the polygon being built. - * - * @param holes {@link List} list made up of {@link LatLng} holes to be added to polygon geometry - * @return This {@link PolygonOptions} object with the given holes added to the outline. - */ - @NonNull - public PolygonOptions addHole(List... holes) { - for (List hole : holes) { - addHole(hole); - } - return this; - } - - /** - * Adds holes to the outline of the polygon being built. - * - * @param holes {@link Iterable} list made up of {@link List} list of {@link LatLng} holes defining the hole geometry - * @return This {@link PolygonOptions} object with the given holes added to the outline. - */ - @NonNull - public PolygonOptions addAllHoles(Iterable> holes) { - for (List hole : holes) { - addHole(hole); - } - return this; - } - - /** - * Set the alpha value of the polyline. - * - * @param alpha float value between 0 (not visible) and 1. - * @return This {@link PolygonOptions} object with the given polygon alpha value. - */ - @NonNull - public PolygonOptions alpha(float alpha) { - polygon.setAlpha(alpha); - return this; - } - - /** - * Gets the alpha set for this {@link PolygonOptions} object. - * - * @return float value between 0 and 1 defining the alpha. - */ - public float getAlpha() { - return polygon.getAlpha(); - } - - /** - * Specifies the polygon's fill color, as 32-bit ARGB. The default color is black. - * - * @param color 32-bit ARGB color. - * @return This {@link PolylineOptions} object with a new color set. - */ - @NonNull - public PolygonOptions fillColor(int color) { - polygon.setFillColor(color); - return this; - } - - /** - * Gets the fill color set for this {@link PolygonOptions} object. - * - * @return The fill color of the polygon in ARGB format. - */ - public int getFillColor() { - return polygon.getFillColor(); - } - - /** - * Do not use this method. Used internally by the SDK. - * - * @return Polygon the Polygon to return - */ - public Polygon getPolygon() { - return polygon; - } - - /** - * Specifies the polygon's stroke color, as 32-bit ARGB. The default color is black. - * - * @param color 32-bit ARGB color. - * @return This {@link PolygonOptions} object with a new stroke color set. - */ - @NonNull - public PolygonOptions strokeColor(int color) { - polygon.setStrokeColor(color); - return this; - } - - /** - * Gets the stroke color set for this {@link PolygonOptions} object. - * - * @return The stroke color of the polygon in ARGB format. - */ - public int getStrokeColor() { - return polygon.getStrokeColor(); - } - - /** - * Gets the points set for this {@link PolygonOptions} object. - * - * @return The list made up of {@link LatLng} points defining the polygon. - */ - public List getPoints() { - // the getter gives us a copy, which is the safe thing to do... - return polygon.getPoints(); - } - - /** - * Gets the holes set for this {@link PolygonOptions} object. - * - * @return The list made up of {@link List} of {@link List} of {@link LatLng} points defining the holes. - */ - public List> getHoles() { - return polygon.getHoles(); - } - - - /** - * Compares this {@link PolygonOptions} object with another {@link PolygonOptions} and - * determines if their color, alpha, stroke color, and vertices match. - * - * @param o Another {@link PolygonOptions} to compare with this object. - * @return True if color, alpha, stroke color, vertices and holes match this {@link PolygonOptions} - * {@link PolygonOptions} object. Else, false. - */ - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - PolygonOptions polygon = (PolygonOptions) o; - - if (Float.compare(polygon.getAlpha(), getAlpha()) != 0) { - return false; - } - if (getFillColor() != polygon.getFillColor()) { - return false; - } - if (getStrokeColor() != polygon.getStrokeColor()) { - return false; - } - if (getPoints() != null ? !getPoints().equals(polygon.getPoints()) : polygon.getPoints() != null) { - return false; - } - return !(getHoles() != null ? !getHoles().equals(polygon.getHoles()) : polygon.getHoles() != null); - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - int result = 1; - result = 31 * result + (getAlpha() != +0.0f ? Float.floatToIntBits(getAlpha()) : 0); - result = 31 * result + getFillColor(); - result = 31 * result + getStrokeColor(); - result = 31 * result + (getPoints() != null ? getPoints().hashCode() : 0); - result = 31 * result + (getHoles() != null ? getHoles().hashCode() : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polyline.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polyline.java deleted file mode 100644 index 76ea15215..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/Polyline.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Color; -import android.support.annotation.Keep; - -import com.mapbox.mapboxsdk.maps.MapboxMap; - -/** - * Polyline is a geometry feature with an unclosed list of coordinates drawn as a line - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class Polyline extends BasePointCollection { - - @Keep - private int color = Color.BLACK; // default color is black - @Keep - private float width = 10; // As specified by Google API Docs (in pixels) - - Polyline() { - super(); - } - - /** - * Gets the color of this polyline. - * - * @return The color in ARGB format. - */ - public int getColor() { - return color; - } - - /** - * Gets the width of this polyline. - * - * @return The width in screen pixels. - */ - public float getWidth() { - return width; - } - - /** - * Sets the color of the polyline. - * - * @param color - the color in ARGB format - */ - public void setColor(int color) { - this.color = color; - update(); - } - - /** - * Sets the width of the polyline. - * - * @param width in pixels - */ - public void setWidth(float width) { - this.width = width; - update(); - } - - @Override - void update() { - MapboxMap mapboxMap = getMapboxMap(); - if (mapboxMap != null) { - mapboxMap.updatePolyline(this); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolylineOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolylineOptions.java deleted file mode 100644 index 6a54f948b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/PolylineOptions.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.os.Parcel; -import android.os.Parcelable; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import java.util.ArrayList; -import java.util.List; - -/** - * Builder for composing {@link Polyline} objects. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ -@Deprecated -public final class PolylineOptions implements Parcelable { - - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public PolylineOptions createFromParcel(@NonNull Parcel in) { - return new PolylineOptions(in); - } - - public PolylineOptions[] newArray(int size) { - return new PolylineOptions[size]; - } - }; - - private PolylineOptions(Parcel in) { - polyline = new Polyline(); - ArrayList pointsList = new ArrayList<>(); - in.readList(pointsList, LatLng.class.getClassLoader()); - addAll(pointsList); - alpha(in.readFloat()); - color(in.readInt()); - width(in.readFloat()); - } - - /** - * Describe the kinds of special objects contained in this Parcelable's - * marshalled representation. - * - * @return integer 0. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written. May be 0 or - * {@link #PARCELABLE_WRITE_RETURN_VALUE}. - */ - @Override - public void writeToParcel(Parcel out, int flags) { - out.writeList(getPoints()); - out.writeFloat(getAlpha()); - out.writeInt(getColor()); - out.writeFloat(getWidth()); - } - - private Polyline polyline; - - /** - * Defines options for a polyline. - */ - public PolylineOptions() { - polyline = new Polyline(); - } - - /** - * Adds a vertex to the end of the polyline being built. - * - * @param point {@link LatLng} point to be added to polyline geometry. - * @return This {@link PolylineOptions} object with the given point on the end. - */ - @NonNull - public PolylineOptions add(LatLng point) { - polyline.addPoint(point); - return this; - } - - /** - * Adds vertices to the end of the polyline being built. - * - * @param points {@link LatLng} points defining the polyline geometry. - * @return This {@link PolylineOptions} object with the given point on the end. - */ - @NonNull - public PolylineOptions add(LatLng... points) { - for (LatLng point : points) { - add(point); - } - return this; - } - - /** - * Adds vertices to the end of the polyline being built. - * - * @param points {@link Iterable} list made up of {@link LatLng} points defining the polyline - * geometry - * @return This {@link PolylineOptions} object with the given points on the end. - */ - @NonNull - public PolylineOptions addAll(Iterable points) { - for (LatLng point : points) { - add(point); - } - return this; - } - - /** - * Set the alpha value of the polyline. - * - * @param alpha float value between 0 (not visible) and 1. - * @return This {@link PolylineOptions} object with the given polyline alpha value. - */ - @NonNull - public PolylineOptions alpha(float alpha) { - polyline.setAlpha(alpha); - return this; - } - - /** - * Gets the alpha set for this {@link PolylineOptions} object. - * - * @return float value between 0 and 1 defining the alpha. - */ - public float getAlpha() { - return polyline.getAlpha(); - } - - /** - * Sets the color of the polyline as a 32-bit ARGB color. The default color is black. - * - * @param color 32-bit ARGB color. - * @return This {@link PolylineOptions} object with a new color set. - */ - @NonNull - public PolylineOptions color(int color) { - polyline.setColor(color); - return this; - } - - /** - * Gets the color set for this {@link PolylineOptions} object. - * - * @return The color of the polyline in ARGB format. - */ - public int getColor() { - return polyline.getColor(); - } - - /** - * Do not use this method. Used internally by the SDK. - * - * @return PolyLine The polyline build by this class. - */ - public Polyline getPolyline() { - return polyline; - } - - /** - * Gets the width set for this {@link PolylineOptions} object. - * - * @return The width of the polyline in screen pixels. - */ - public float getWidth() { - return polyline.getWidth(); - } - - /** - * Sets the width of the polyline in screen pixels. The default is 10. - * - * @param width float value defining width of polyline using unit pixels. - * @return This {@link PolylineOptions} object with a new width set. - */ - @NonNull - public PolylineOptions width(float width) { - polyline.setWidth(width); - return this; - } - - /** - * Gets the points set for this {@link PolylineOptions} object. - * - * @return a {@link List} of {@link LatLng}s specifying the vertices of the polyline. - */ - public List getPoints() { - // the getter gives us a copy, which is the safe thing to do... - return polyline.getPoints(); - } - - /** - * Compares this {@link PolylineOptions} object with another {@link PolylineOptions} and - * determines if their color, alpha, width, and vertices match. - * - * @param o Another {@link PolylineOptions} to compare with this object. - * @return True if color, alpha, width, and vertices match this {@link PolylineOptions} object. - * Else, false. - */ - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - PolylineOptions polyline = (PolylineOptions) o; - - if (Float.compare(polyline.getAlpha(), getAlpha()) != 0) { - return false; - } - if (getColor() != polyline.getColor()) { - return false; - } - if (Float.compare(polyline.getWidth(), getWidth()) != 0) { - return false; - } - return !(getPoints() != null ? !getPoints().equals(polyline.getPoints()) : polyline.getPoints() != null); - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - int result = 1; - result = 31 * result + (getAlpha() != +0.0f ? Float.floatToIntBits(getAlpha()) : 0); - result = 31 * result + getColor(); - result = 31 * result + (getWidth() != +0.0f ? Float.floatToIntBits(getWidth()) : 0); - result = 31 * result + (getPoints() != null ? getPoints().hashCode() : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/package-info.java deleted file mode 100644 index 1e2dc542f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/annotations/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Annotation API classes. - */ -package com.mapbox.mapboxsdk.annotations; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/Attribution.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/Attribution.java deleted file mode 100644 index 035614a90..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/Attribution.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import android.support.annotation.Nullable; - -import java.util.ArrayList; -import java.util.List; - -public class Attribution { - - private static final String OPENSTREETMAP = "OpenStreetMap"; - private static final String OPENSTREETMAP_ABBR = "OSM"; - static final String TELEMETRY = "Telemetry Settings"; - static final String MAPBOX_URL = "https://www.mapbox.com/about/maps/"; - static final String TELEMETRY_URL = "https://www.mapbox.com/telemetry/"; - static final List IMPROVE_MAP_URLS = new ArrayList<>(); - - static { - // Using a List makes URL backwards compatible - IMPROVE_MAP_URLS.add("https://www.mapbox.com/feedback/"); - IMPROVE_MAP_URLS.add("https://www.mapbox.com/map-feedback/"); - IMPROVE_MAP_URLS.add("https://apps.mapbox.com/feedback/"); - } - - private String title; - private String url; - - Attribution(String title, String url) { - this.title = title; - this.url = url; - } - - public String getTitle() { - return title; - } - - public String getTitleAbbreviated() { - if (title.equals(OPENSTREETMAP)) { - return OPENSTREETMAP_ABBR; - } - return title; - } - - public String getUrl() { - return url; - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Attribution that = (Attribution) o; - - if (title != null ? !title.equals(that.title) : that.title != null) { - return false; - } - return url != null ? url.equals(that.url) : that.url == null; - } - - @Override - public int hashCode() { - int result = title != null ? title.hashCode() : 0; - result = 31 * result + (url != null ? url.hashCode() : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionLayout.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionLayout.java deleted file mode 100644 index 25d5de7ea..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionLayout.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -public class AttributionLayout { - - @Nullable - private Bitmap logo; - @Nullable - private PointF anchorPoint; - private boolean shortText; - - public AttributionLayout(@Nullable Bitmap logo, @Nullable PointF anchorPoint, boolean shortText) { - this.logo = logo; - this.anchorPoint = anchorPoint; - this.shortText = shortText; - } - - @Nullable - public Bitmap getLogo() { - return logo; - } - - @Nullable - public PointF getAnchorPoint() { - return anchorPoint; - } - - public boolean isShortText() { - return shortText; - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - AttributionLayout that = (AttributionLayout) o; - - if (logo != null ? !logo.equals(that.logo) : that.logo != null) { - return false; - } - return anchorPoint != null ? anchorPoint.equals(that.anchorPoint) : that.anchorPoint == null; - } - - @Override - public int hashCode() { - int result = logo != null ? logo.hashCode() : 0; - result = 31 * result + (anchorPoint != null ? anchorPoint.hashCode() : 0); - return result; - } - - @NonNull - @Override - public String toString() { - return "AttributionLayout{" - + "logo=" + logo - + ", anchorPoint=" + anchorPoint - + '}'; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionMeasure.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionMeasure.java deleted file mode 100644 index b40a7be24..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionMeasure.java +++ /dev/null @@ -1,249 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.widget.TextView; - -import java.util.Arrays; -import java.util.List; - -public class AttributionMeasure { - - private Bitmap logo; - private Bitmap logoSmall; - private Bitmap snapshot; - private TextView textView; - private TextView textViewShort; - private float margin; - - private boolean shorterText; - - AttributionMeasure(Bitmap snapshot, Bitmap logo, Bitmap logoSmall, TextView tv, TextView tvShort, float margin) { - this.snapshot = snapshot; - this.logo = logo; - this.logoSmall = logoSmall; - this.textView = tv; - this.textViewShort = tvShort; - this.margin = margin; - } - - @Nullable - public AttributionLayout measure() { - Chain chain = new Chain( - new FullLogoLongTextCommand(), - new FullLogoShortTextCommand(), - new SmallLogoLongTextCommand(), - new SmallLogoShortTextCommand(), - new LongTextCommand(), - new ShortTextCommand(), - new NoTextCommand() - ); - - AttributionLayout attributionLayout = chain.start(this); - shorterText = attributionLayout.isShortText(); - return attributionLayout; - } - - - private static class FullLogoLongTextCommand implements Command { - @Nullable - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getLogoContainerWidth() + measure.getTextViewContainerWidth(); - boolean fitBounds = width <= measure.getMaxSize(); - if (fitBounds) { - PointF anchor = calculateAnchor(measure.snapshot, measure.textView, measure.margin); - return new AttributionLayout(measure.logo, anchor, false); - } - return null; - } - } - - private static class FullLogoShortTextCommand implements Command { - @Nullable - @Override - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getLogoContainerWidth() + measure.getTextViewShortContainerWidth(); - boolean fitBounds = width <= measure.getMaxSizeShort(); - if (fitBounds) { - PointF anchor = calculateAnchor(measure.snapshot, measure.textViewShort, measure.margin); - return new AttributionLayout(measure.logo, anchor, true); - } - return null; - } - } - - private static class SmallLogoLongTextCommand implements Command { - @Nullable - @Override - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getLogoSmallContainerWidth() + measure.getTextViewContainerWidth(); - boolean fitBounds = width <= measure.getMaxSize(); - if (fitBounds) { - PointF anchor = calculateAnchor(measure.snapshot, measure.textView, measure.margin); - return new AttributionLayout(measure.logoSmall, anchor, false); - } - return null; - } - } - - private static class SmallLogoShortTextCommand implements Command { - @Nullable - @Override - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getLogoContainerWidth() + measure.getTextViewShortContainerWidth(); - boolean fitBounds = width <= measure.getMaxSizeShort(); - if (fitBounds) { - PointF anchor = calculateAnchor(measure.snapshot, measure.textViewShort, measure.margin); - return new AttributionLayout(measure.logoSmall, anchor, true); - } - return null; - } - } - - private static class LongTextCommand implements Command { - @Nullable - @Override - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getTextViewContainerWidth() + measure.margin; - boolean fitBounds = width <= measure.getMaxSize(); - if (fitBounds) { - return new AttributionLayout(null, calculateAnchor(measure.snapshot, measure.textView, measure.margin), false); - } - return null; - } - } - - private static class ShortTextCommand implements Command { - @Nullable - @Override - public AttributionLayout execute(@NonNull AttributionMeasure measure) { - float width = measure.getTextViewShortContainerWidth() + measure.margin; - boolean fitBounds = width <= measure.getMaxSizeShort(); - if (fitBounds) { - PointF anchor = calculateAnchor(measure.snapshot, measure.textViewShort, measure.margin); - return new AttributionLayout(null, anchor, true); - } - return null; - } - } - - private static class NoTextCommand implements Command { - @NonNull - @Override - public AttributionLayout execute(AttributionMeasure measure) { - return new AttributionLayout(null, null, false); - } - } - - private static PointF calculateAnchor(Bitmap snapshot, TextView textView, float margin) { - return new PointF( - snapshot.getWidth() - textView.getMeasuredWidth() - margin, - snapshot.getHeight() - margin - textView.getMeasuredHeight() - ); - } - - public TextView getTextView() { - return shorterText ? textViewShort : textView; - } - - private class Chain { - public List commands; - - Chain(Command... commands) { - this.commands = Arrays.asList(commands); - } - - @Nullable - public AttributionLayout start(AttributionMeasure measure) { - AttributionLayout attributionLayout = null; - for (Command command : commands) { - attributionLayout = command.execute(measure); - if (attributionLayout != null) { - break; - } - } - return attributionLayout; - } - } - - public interface Command { - @Nullable - AttributionLayout execute(AttributionMeasure measure); - } - - private float getTextViewContainerWidth() { - return textView.getMeasuredWidth() + margin; - } - - private float getLogoContainerWidth() { - return logo.getWidth() + (2 * margin); - } - - private float getTextViewShortContainerWidth() { - return textViewShort.getMeasuredWidth() + margin; - } - - private float getLogoSmallContainerWidth() { - return logoSmall.getWidth() + (2 * margin); - } - - private float getMaxSize() { - return snapshot.getWidth() * 8 / 10; - } - - private float getMaxSizeShort() { - return snapshot.getWidth(); - } - - public static class Builder { - private Bitmap snapshot; - private Bitmap logo; - private Bitmap logoSmall; - private TextView textView; - private TextView textViewShort; - private float marginPadding; - - @NonNull - public Builder setSnapshot(Bitmap snapshot) { - this.snapshot = snapshot; - return this; - } - - @NonNull - public Builder setLogo(Bitmap logo) { - this.logo = logo; - return this; - } - - @NonNull - public Builder setLogoSmall(Bitmap logoSmall) { - this.logoSmall = logoSmall; - return this; - } - - @NonNull - public Builder setTextView(TextView textView) { - this.textView = textView; - return this; - } - - @NonNull - public Builder setTextViewShort(TextView textViewShort) { - this.textViewShort = textViewShort; - return this; - } - - @NonNull - public Builder setMarginPadding(float marginPadding) { - this.marginPadding = marginPadding; - return this; - } - - @NonNull - public AttributionMeasure build() { - return new AttributionMeasure(snapshot, logo, logoSmall, textView, textViewShort, marginPadding); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionParser.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionParser.java deleted file mode 100644 index ff59dbdf9..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/AttributionParser.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import android.content.Context; -import android.support.annotation.NonNull; -import android.text.Html; -import android.text.SpannableStringBuilder; -import android.text.Spanned; -import android.text.style.URLSpan; -import com.mapbox.mapboxsdk.R; - -import java.lang.ref.WeakReference; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * Responsible for parsing attribution data coming from Sources and MapSnapshot. - *

- * Exposes multiple configuration options to manipulate data being parsed. - * Use the Options object to build these configurations. - *

- */ -public class AttributionParser { - - private static final String IMPROVE_THIS_MAP = "Improve this map"; - private final WeakReference context; - private final Set attributions = new LinkedHashSet<>(); - private final String attributionData; - private final boolean withImproveMap; - private final boolean withCopyrightSign; - private final boolean withTelemetryAttribution; - private final boolean withMapboxAttribution; - - AttributionParser(WeakReference context, String attributionData, boolean withImproveMap, - boolean withCopyrightSign, boolean withTelemetryAttribution, boolean withMapboxAttribution) { - this.context = context; - this.attributionData = attributionData; - this.withImproveMap = withImproveMap; - this.withCopyrightSign = withCopyrightSign; - this.withTelemetryAttribution = withTelemetryAttribution; - this.withMapboxAttribution = withMapboxAttribution; - } - - /** - * Get parsed attributions. - * - * @return the attributions - */ - @NonNull - public Set getAttributions() { - return attributions; - } - - /** - * Get parsed attribution string. - * - * @return the parsed attribution string - */ - @NonNull - public String createAttributionString() { - return createAttributionString(false); - } - - /** - * Get parsed attribution string. - * - * @param shortenedOutput if attribution string should contain shortened output - * @return the parsed attribution string - */ - @NonNull - public String createAttributionString(boolean shortenedOutput) { - StringBuilder stringBuilder = new StringBuilder(withCopyrightSign ? "" : "© "); - int counter = 0; - for (Attribution attribution : attributions) { - counter++; - stringBuilder.append(!shortenedOutput ? attribution.getTitle() : attribution.getTitleAbbreviated()); - if (counter != attributions.size()) { - stringBuilder.append(" / "); - } - } - return stringBuilder.toString(); - } - - /** - * Main attribution for configuration - */ - protected void parse() { - parseAttributions(); - addAdditionalAttributions(); - } - - /** - * Parse attributions - */ - private void parseAttributions() { - SpannableStringBuilder htmlBuilder = (SpannableStringBuilder) fromHtml(attributionData); - URLSpan[] urlSpans = htmlBuilder.getSpans(0, htmlBuilder.length(), URLSpan.class); - for (URLSpan urlSpan : urlSpans) { - parseUrlSpan(htmlBuilder, urlSpan); - } - } - - /** - * Parse an URLSpan containing an attribution. - * - * @param htmlBuilder the html builder - * @param urlSpan the url span to be parsed - */ - private void parseUrlSpan(@NonNull SpannableStringBuilder htmlBuilder, @NonNull URLSpan urlSpan) { - String url = urlSpan.getURL(); - if (isUrlValid(url)) { - String anchor = parseAnchorValue(htmlBuilder, urlSpan); - if (isImproveThisMapAnchor(anchor)) { - anchor = translateImproveThisMapAnchor(anchor); - } - attributions.add(new Attribution(anchor, url)); - } - } - - /** - * Invoked to validate if an url is valid to be included in the final attribution. - * - * @param url the url to be validated - * @return if the url is valid - */ - private boolean isUrlValid(@NonNull String url) { - return isValidForImproveThisMap(url) && isValidForMapbox(url); - } - - /** - * Invoked to validate if an anchor is equal to Improve this map coming from tilesets. - * - * @param anchor the anchor to be validated - * @return if the url is valid - */ - private boolean isImproveThisMapAnchor(String anchor) { - return anchor.equals(IMPROVE_THIS_MAP); - } - - /** - * Invoked to replace the english Improve this map with localized variant. - * - * @param anchor the anchor to be translated - * @return the translated anchor - */ - private String translateImproveThisMapAnchor(String anchor) { - Context context = this.context.get(); - if (context != null) { - anchor = context.getString(R.string.mapbox_telemetryImproveMap); - } - return anchor; - } - - /** - * Invoked to validate if an url is valid for the improve map configuration. - * - * @param url the url to be validated - * @return if the url is valid for improve this map - */ - private boolean isValidForImproveThisMap(@NonNull String url) { - return withImproveMap || !(Attribution.IMPROVE_MAP_URLS.contains(url)); - } - - /** - * Invoked to validate if an url is valid for the Mapbox configuration. - * - * @param url the url to be validated - * @return if the url is valid for Mapbox - */ - private boolean isValidForMapbox(@NonNull String url) { - return withMapboxAttribution || !url.equals(Attribution.MAPBOX_URL); - } - - /** - * Parse the attribution by parsing the anchor value of html href tag. - * - * @param htmlBuilder the html builder - * @param urlSpan the current urlSpan - * @return the parsed anchor value - */ - @NonNull - private String parseAnchorValue(SpannableStringBuilder htmlBuilder, URLSpan urlSpan) { - int start = htmlBuilder.getSpanStart(urlSpan); - int end = htmlBuilder.getSpanEnd(urlSpan); - int length = end - start; - char[] charKey = new char[length]; - htmlBuilder.getChars(start, end, charKey, 0); - return stripCopyright(String.valueOf(charKey)); - } - - /** - * Utility to strip the copyright sign from an attribution - * - * @param anchor the attribution string to strip - * @return the stripped attribution string without the copyright sign - */ - @NonNull - private String stripCopyright(@NonNull String anchor) { - if (!withCopyrightSign && anchor.startsWith("© ")) { - anchor = anchor.substring(2, anchor.length()); - } - return anchor; - } - - /** - * Invoked to manually add attributions - */ - private void addAdditionalAttributions() { - if (withTelemetryAttribution) { - Context context = this.context.get(); - attributions.add( - new Attribution( - context != null ? context.getString(R.string.mapbox_telemetrySettings) : Attribution.TELEMETRY, - Attribution.TELEMETRY_URL - ) - ); - } - } - - /** - * Convert a string to a spanned html representation. - * - * @param html the string to convert - * @return the spanned html representation - */ - private static Spanned fromHtml(String html) { - Spanned result; - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { - result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); - } else { - result = Html.fromHtml(html); - } - return result; - } - - /** - * Builder to configure using an AttributionParser. - *

- * AttributionData, set with {@link #withAttributionData(String...)}, is the only required property to build - * the underlying AttributionParser. Other properties include trimming the copyright sign, adding telemetry - * attribution or hiding attribution as improve this map and Mapbox. - *

- */ - public static class Options { - private final WeakReference context; - private boolean withImproveMap = true; - private boolean withCopyrightSign = true; - private boolean withTelemetryAttribution = false; - private boolean withMapboxAttribution = true; - private String[] attributionDataStringArray; - - public Options(@NonNull Context context) { - this.context = new WeakReference<>(context); - } - - @NonNull - public Options withAttributionData(String... attributionData) { - this.attributionDataStringArray = attributionData; - return this; - } - - @NonNull - public Options withImproveMap(boolean withImproveMap) { - this.withImproveMap = withImproveMap; - return this; - } - - @NonNull - public Options withCopyrightSign(boolean withCopyrightSign) { - this.withCopyrightSign = withCopyrightSign; - return this; - } - - @NonNull - public Options withTelemetryAttribution(boolean withTelemetryAttribution) { - this.withTelemetryAttribution = withTelemetryAttribution; - return this; - } - - @NonNull - public Options withMapboxAttribution(boolean withMapboxAttribution) { - this.withMapboxAttribution = withMapboxAttribution; - return this; - } - - @NonNull - public AttributionParser build() { - if (attributionDataStringArray == null) { - throw new IllegalStateException("Using builder without providing attribution data"); - } - - String fullAttributionString = parseAttribution(attributionDataStringArray); - AttributionParser attributionParser = new AttributionParser( - context, - fullAttributionString, - withImproveMap, - withCopyrightSign, - withTelemetryAttribution, - withMapboxAttribution - ); - attributionParser.parse(); - return attributionParser; - } - - private String parseAttribution(String[] attribution) { - StringBuilder builder = new StringBuilder(); - for (String attr : attribution) { - if (!attr.isEmpty()) { - builder.append(attr); - } - } - return builder.toString(); - } - } -} 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 deleted file mode 100644 index 57d840af5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/attribution/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * 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 deleted file mode 100644 index fb89688e2..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraPosition.java +++ /dev/null @@ -1,414 +0,0 @@ -package com.mapbox.mapboxsdk.camera; - -import android.content.res.TypedArray; -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.FloatRange; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.Size; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.utils.MathUtils; - -import java.util.Arrays; - -/** - * Resembles the position, angle, zoom and tilt of the user's viewpoint. - */ -public final class CameraPosition implements Parcelable { - - public static final CameraPosition DEFAULT = new CameraPosition(new LatLng(), 0, 0, 0, new double[] {0, 0, 0, 0}); - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public CameraPosition createFromParcel(Parcel in) { - double bearing = in.readDouble(); - LatLng target = in.readParcelable(LatLng.class.getClassLoader()); - double tilt = in.readDouble(); - double zoom = in.readDouble(); - - double[] padding = null; - int paddingSize = in.readInt(); - if (paddingSize > 0) { - padding = new double[paddingSize]; - for (int i = 0; i < paddingSize; i++) { - padding[i] = in.readDouble(); - } - } - - return new CameraPosition(target, zoom, tilt, bearing, padding); - } - - public CameraPosition[] newArray(int size) { - return new CameraPosition[size]; - } - }; - - /** - * Direction that the camera is pointing in, in degrees clockwise from north. - */ - @Keep - public final double bearing; - - /** - * The location that the camera is pointing at. - */ - @Keep - public final LatLng target; - - /** - * The angle, in degrees, of the camera angle from the nadir (directly facing the Earth). - * See {@link Builder#tilt(double)} for details of restrictions on the range of values. - */ - @Keep - public final double tilt; - - /** - * Zoom level near the center of the screen. See {@link Builder#zoom(double)} for the definition of the camera's - * zoom level. - */ - @Keep - public final double zoom; - - /** - * Padding in pixels. Specified in left, top, right, bottom order. - * See {@link Builder#padding(double[])} for the definition of the camera's padding. - */ - @Keep - public final double[] padding; - - /** - * Constructs a CameraPosition. - * - * @param target The target location to align with the center of the screen. - * @param zoom Zoom level at target. See zoom(float) for details of restrictions. - * @param tilt The camera angle, in degrees, from the nadir (directly down). See tilt(float) - * for details of restrictions. - * @param bearing Direction that the camera is pointing in, in degrees clockwise from north. - * This value will be normalized to be within 0 degrees inclusive and 360 degrees - * exclusive. - * @throws NullPointerException if target is null - * @throws IllegalArgumentException if tilt is outside the range of 0 to 90 degrees inclusive. - * @deprecated use {@link CameraPosition#CameraPosition(LatLng, double, double, double, double[])} instead. - */ - @Deprecated - CameraPosition(LatLng target, double zoom, double tilt, double bearing) { - this(target, zoom, tilt, bearing, null); - } - - /** - * Constructs a CameraPosition. - * - * @param target The target location to align with the center of the screen. - * @param zoom Zoom level at target. See zoom(float) for details of restrictions. - * @param tilt The camera angle, in degrees, from the nadir (directly down). See tilt(float) - * for details of restrictions. - * @param bearing Direction that the camera is pointing in, in degrees clockwise from north. - * This value will be normalized to be within 0 degrees inclusive and 360 degrees - * exclusive. - * @param padding Padding in pixels. Specified in left, top, right, bottom order. - * @throws NullPointerException if target is null - * @throws IllegalArgumentException if tilt is outside the range of 0 to 90 degrees inclusive. - */ - @Keep - CameraPosition(LatLng target, double zoom, double tilt, double bearing, double[] padding) { - this.target = target; - this.bearing = bearing; - this.tilt = tilt; - this.zoom = zoom; - this.padding = padding; - } - - /** - * Describe the kinds of special objects contained in this Parcelable's - * marshalled representation. - * - * @return integer 0. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written. May be 0 or - * {@link #PARCELABLE_WRITE_RETURN_VALUE}. - */ - @Override - public void writeToParcel(Parcel out, int flags) { - out.writeDouble(bearing); - out.writeParcelable(target, flags); - out.writeDouble(tilt); - out.writeDouble(zoom); - - if (padding != null) { - int length = padding.length; - out.writeInt(length); - for (double v : padding) { - out.writeDouble(v); - } - } else { - out.writeInt(-1); - } - } - - /** - * Returns a String with the camera target, zoom, bearing and tilt. - * - * @return A String with CameraPosition information. - */ - @Override - public String toString() { - return "Target: " + target + ", Zoom:" + zoom + ", Bearing:" + bearing + ", Tilt:" + tilt - + ", Padding:" + Arrays.toString(padding); - } - - /** - * Compares this {@link CameraPosition} object with another {@link CameraPosition} and - * determines if their target, zoom, tilt, and bearing match. - * - * @param o Another {@link CameraPosition} to compare with this object. - * @return True if target, zoom, tilt, and bearing match this {@link CameraPosition} object. - * Else, false. - */ - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - CameraPosition cameraPosition = (CameraPosition) o; - if (target != null && !target.equals(cameraPosition.target)) { - return false; - } else if (zoom != cameraPosition.zoom) { - return false; - } else if (tilt != cameraPosition.tilt) { - return false; - } else if (bearing != cameraPosition.bearing) { - return false; - } else if (!Arrays.equals(padding, cameraPosition.padding)) { - return false; - } - return true; - } - - /** - * Gives an integer which can be used as the bucket number for storing elements of the set/map. - * This bucket number is the address of the element inside the set/map. There's no guarantee - * that this hash value will be consistent between different Java implementations, or even - * between different execution runs of the same program. - * - * @return integer value you can use for storing element. - */ - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(bearing); - result = (int) (temp ^ (temp >>> 32)); - result = 31 * result + (target != null ? target.hashCode() : 0); - temp = Double.doubleToLongBits(tilt); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(zoom); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - result = 31 * result + Arrays.hashCode(padding); - return result; - } - - /** - * Builder for composing CameraPosition objects. - */ - public static final class Builder { - - private double bearing = -1; - @Nullable - private LatLng target = null; - private double tilt = -1; - private double zoom = -1; - private double[] padding = null; - - /** - * Create an empty builder. - */ - public Builder() { - super(); - } - - /** - * Create a builder with an existing CameraPosition data. - * - * @param previous Existing CameraPosition values to use - */ - public Builder(@Nullable CameraPosition previous) { - super(); - if (previous != null) { - this.bearing = previous.bearing; - this.target = previous.target; - this.tilt = previous.tilt; - this.zoom = previous.zoom; - this.padding = previous.padding; - } - } - - /** - * Create a builder with an existing CameraPosition data. - * - * @param typedArray TypedArray containing attribute values - */ - public Builder(@Nullable TypedArray typedArray) { - super(); - if (typedArray != null) { - this.bearing = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraBearing, 0.0f); - double lat = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTargetLat, 0.0f); - double lng = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTargetLng, 0.0f); - this.target = new LatLng(lat, lng); - this.tilt = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTilt, 0.0f); - this.zoom = typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraZoom, 0.0f); - } - } - - /** - * Create a builder from an existing CameraPositionUpdate update. - * - * @param update Update containing camera options - */ - public Builder(@Nullable CameraUpdateFactory.CameraPositionUpdate update) { - super(); - if (update != null) { - bearing = update.getBearing(); - target = update.getTarget(); - tilt = update.getTilt(); - zoom = update.getZoom(); - padding = update.getPadding(); - } - } - - /** - * Create builder from an existing CameraPositionUpdate update. - * - * @param update Update containing camera options - */ - public Builder(@Nullable CameraUpdateFactory.ZoomUpdate update) { - super(); - if (update != null) { - this.zoom = update.getZoom(); - } - } - - /** - * Sets the direction that the camera is pointing in, in degrees clockwise from north. - * - * @param bearing Bearing - * @return this - */ - @NonNull - public Builder bearing(double bearing) { - double direction = bearing; - - while (direction >= 360) { - direction -= 360; - } - while (direction < 0) { - direction += 360; - } - - this.bearing = direction; - return this; - } - - /** - * Sets the location where the camera is pointing at. - * - * @param location target of the camera - * @return this - */ - @NonNull - public Builder target(LatLng location) { - this.target = location; - return this; - } - - /** - * Set the tilt of the camera in degrees - *

- * value is clamped to {@link MapboxConstants#MINIMUM_TILT} and {@link MapboxConstants#MAXIMUM_TILT}. - *

- * - * @param tilt Tilt value of the camera - * @return this - */ - @NonNull - public Builder tilt(@FloatRange(from = MapboxConstants.MINIMUM_TILT, - to = MapboxConstants.MAXIMUM_TILT) double tilt) { - this.tilt = MathUtils.clamp(tilt, MapboxConstants.MINIMUM_TILT, MapboxConstants.MAXIMUM_TILT); - return this; - } - - /** - * Set the zoom of the camera - *

- * Zoom ranges from {@link MapboxConstants#MINIMUM_ZOOM} to {@link MapboxConstants#MAXIMUM_ZOOM} - *

- * - * @param zoom Zoom value of the camera - * @return this - */ - @NonNull - public Builder zoom(@FloatRange(from = MapboxConstants.MINIMUM_ZOOM, - to = MapboxConstants.MAXIMUM_ZOOM) double zoom) { - this.zoom = zoom; - return this; - } - - /** - * Padding in pixels that shifts the viewport by the specified amount. - * Applied padding is going to persist and impact following camera transformations. - *

- * Specified in left, top, right, bottom order. - *

- * - * @param padding Camera padding - * @return this - */ - @NonNull - public Builder padding(@Size(4) double[] padding) { - this.padding = padding; - return this; - } - - /** - * Padding in pixels that shifts the viewport by the specified amount. - * Applied padding is going to persist and impact following camera transformations. - *

- * Specified in left, top, right, bottom order. - *

- * - * @return this - */ - @NonNull - public Builder padding(double left, double top, double right, double bottom) { - this.padding = new double[] {left, top, right, bottom}; - return this; - } - - /** - * Builds the CameraPosition. - * - * @return CameraPosition - */ - public CameraPosition build() { - return new CameraPosition(target, zoom, tilt, bearing, padding); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdate.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdate.java deleted file mode 100644 index 39b937210..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdate.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.mapbox.mapboxsdk.camera; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.maps.MapboxMap; - -/** - * Interface definition for camera updates. - */ -public interface CameraUpdate { - - /** - * Get the camera position from the camera update. - * - * @param mapboxMap Map object to build the position from - * @return the camera position from the implementing camera update - */ - @Nullable - CameraPosition getCameraPosition(@NonNull MapboxMap mapboxMap); - -} - 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 deleted file mode 100644 index b611456f4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/CameraUpdateFactory.java +++ /dev/null @@ -1,637 +0,0 @@ -package com.mapbox.mapboxsdk.camera; - -import android.graphics.Point; -import android.graphics.PointF; -import android.support.annotation.IntDef; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.geometry.LatLngBounds; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; -import com.mapbox.mapboxsdk.maps.UiSettings; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.Arrays; - -/** - * Factory for creating CameraUpdate objects. - */ -public final class CameraUpdateFactory { - - /** - * Returns a CameraUpdate that moves the camera to a specified CameraPosition. - * - * @param cameraPosition Camera Position to change to - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newCameraPosition(@NonNull CameraPosition cameraPosition) { - return new CameraPositionUpdate(cameraPosition.bearing, cameraPosition.target, cameraPosition.tilt, - cameraPosition.zoom, cameraPosition.padding); - } - - /** - * Returns a CameraUpdate that 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 - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLng(@NonNull LatLng latLng) { - return new CameraPositionUpdate(-1, latLng, -1, -1, null); - } - - /** - * Returns a CameraUpdate that transforms the camera such that the specified - * latitude/longitude bounds are centered on screen at the greatest possible zoom level while maintaining - * current camera position bearing and tilt values. - *

- * You can specify padding, in order to inset the bounding box from the map view's edges. - * The padding will not persist and impact following camera transformations. - *

- * - * @param bounds Bounds to match Camera position with - * @param padding Padding added to the bounds - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngBounds(@NonNull LatLngBounds bounds, int padding) { - return newLatLngBounds(bounds, padding, padding, padding, padding); - } - - /** - * Returns a CameraUpdate that transforms the camera such that the specified - * latitude/longitude bounds are centered on screen at the greatest possible zoom level while using - * provided bearing and tilt values. - *

- * You can specify padding, in order to inset the bounding box from the map view's edges. - * The padding will not persist and impact following camera transformations. - *

- * - * @param bounds Bounds to match Camera position with - * @param bearing Bearing to take in account when generating the bounds - * @param tilt Tilt to take in account when generating the bounds - * @param padding Padding added to the bounds - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngBounds(@NonNull LatLngBounds bounds, double bearing, double tilt, int padding) { - return newLatLngBounds(bounds, bearing, tilt, padding, padding, padding, padding); - } - - /** - * Returns a CameraUpdate that transforms the camera such that the specified - * latitude/longitude bounds are centered on screen at the greatest possible zoom level while maintaining - * current camera position bearing and tilt values. - *

- * You can specify padding, in order to inset the bounding box from the map view's edges. - * The padding will not persist and impact following camera transformations. - *

- * - * @param bounds Bounds to base the Camera position out of - * @param paddingLeft Padding left of the bounds - * @param paddingTop Padding top of the bounds - * @param paddingRight Padding right of the bounds - * @param paddingBottom Padding bottom of the bounds - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngBounds(@NonNull LatLngBounds bounds, int paddingLeft, int paddingTop, - int paddingRight, int paddingBottom) { - return new CameraBoundsUpdate(bounds, null, null, paddingLeft, paddingTop, paddingRight, paddingBottom); - } - - /** - * Returns a CameraUpdate that transforms the camera such that the specified - * latitude/longitude bounds are centered on screen at the greatest possible zoom level while using - * provided bearing and tilt values. - *

- * You can specify padding, in order to inset the bounding box from the map view's edges. - * The padding will not persist and impact following camera transformations. - *

- * - * @param bounds Bounds to base the Camera position out of - * @param bearing Bearing to take in account when generating the bounds - * @param tilt Tilt to take in account when generating the bounds - * @param paddingLeft Padding left of the bounds - * @param paddingTop Padding top of the bounds - * @param paddingRight Padding right of the bounds - * @param paddingBottom Padding bottom of the bounds - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngBounds(@NonNull LatLngBounds bounds, double bearing, double tilt, - int paddingLeft, int paddingTop, int paddingRight, int paddingBottom) { - return new CameraBoundsUpdate(bounds, bearing, tilt, paddingLeft, paddingTop, paddingRight, paddingBottom); - } - - /** - * Returns a CameraUpdate that moves the center of the screen to a latitude and longitude - * specified by a LatLng object taking the specified padding into account. - * - * @param latLng Target location to change to - * @param zoom Zoom level to change to - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngZoom(@NonNull LatLng latLng, double zoom) { - return new CameraPositionUpdate(-1, latLng, -1, zoom, null); - } - - /** - * Returns a CameraUpdate that moves the center of the screen to a latitude and longitude - * specified by a LatLng object, and moves to the given zoom level. - * Applied padding is going to persist and impact following camera transformations. - * - * @param latLng Target location to change to - * @param left Left padding - * @param top Top padding - * @param right Right padding - * @param bottom Bottom padding - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate newLatLngPadding(@NonNull LatLng latLng, - double left, double top, double right, double bottom) { - return new CameraPositionUpdate(-1, latLng, -1, -1, new double[] {left, top, right, bottom}); - } - - /** - * Returns a CameraUpdate that shifts the zoom level of the current camera viewpoint. - * - * @param amount Amount of zoom level to change with - * @param focus Focus point of zoom - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate zoomBy(double amount, Point focus) { - return new ZoomUpdate(amount, focus.x, focus.y); - } - - /** - * Returns a CameraUpdate that shifts the zoom level of the current camera viewpoint. - * - * @param amount Amount of zoom level to change with - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate zoomBy(double amount) { - return new ZoomUpdate(ZoomUpdate.ZOOM_BY, amount); - } - - /** - * Returns a CameraUpdate that zooms in on the map by moving the viewpoint's height closer to - * the Earth's surface. The zoom increment is 1.0. - * - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate zoomIn() { - return new ZoomUpdate(ZoomUpdate.ZOOM_IN); - } - - /** - * Returns a CameraUpdate that zooms out on the map by moving the viewpoint's height farther - * away from the Earth's surface. The zoom increment is -1.0. - * - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate zoomOut() { - return new ZoomUpdate(ZoomUpdate.ZOOM_OUT); - } - - /** - * Returns a CameraUpdate that moves the camera viewpoint to a particular zoom level. - * - * @param zoom Zoom level to change to - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate zoomTo(double zoom) { - 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, null); - } - - /** - * 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, null); - } - - /** - * Returns a CameraUpdate that when animated changes the camera padding. - * Applied padding is going to persist and impact following camera transformations. - *

- * Specified in left, top, right, bottom order. - *

- * - * @param padding Padding to change to - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate paddingTo(double[] padding) { - return new CameraPositionUpdate(-1, null, -1, -1, padding); - } - - /** - * Returns a CameraUpdate that when animated changes the camera padding. - * Applied padding is going to persist and impact following camera transformations. - *

- * Specified in left, top, right, bottom order. - *

- * - * @return CameraUpdate Final Camera Position - */ - public static CameraUpdate paddingTo(double left, double top, double right, double bottom) { - return paddingTo(new double[] {left, top, right, bottom}); - } - - // - // CameraUpdate types - // - - static final class CameraPositionUpdate implements CameraUpdate { - - private final double bearing; - private final LatLng target; - private final double tilt; - private final double zoom; - private final double[] padding; - - CameraPositionUpdate(double bearing, LatLng target, double tilt, double zoom, double[] padding) { - this.bearing = bearing; - this.target = target; - this.tilt = tilt; - this.zoom = zoom; - this.padding = padding; - } - - public LatLng getTarget() { - return target; - } - - public double getBearing() { - return bearing; - } - - public double getTilt() { - return tilt; - } - - public double getZoom() { - return zoom; - } - - public double[] getPadding() { - return padding; - } - - @Override - public CameraPosition getCameraPosition(@NonNull MapboxMap mapboxMap) { - if (target == null) { - CameraPosition previousPosition = mapboxMap.getCameraPosition(); - return new CameraPosition.Builder(this) - .target(previousPosition.target) - .build(); - } - return new CameraPosition.Builder(this).build(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - CameraPositionUpdate that = (CameraPositionUpdate) o; - - if (Double.compare(that.bearing, bearing) != 0) { - return false; - } - if (Double.compare(that.tilt, tilt) != 0) { - return false; - } - if (Double.compare(that.zoom, zoom) != 0) { - return false; - } - if (target != null ? !target.equals(that.target) : that.target != null) { - return false; - } - return Arrays.equals(padding, that.padding); - } - - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(bearing); - result = (int) (temp ^ (temp >>> 32)); - result = 31 * result + (target != null ? target.hashCode() : 0); - temp = Double.doubleToLongBits(tilt); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(zoom); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - result = 31 * result + Arrays.hashCode(padding); - return result; - } - - @Override - public String toString() { - return "CameraPositionUpdate{" - + "bearing=" + bearing - + ", target=" + target - + ", tilt=" + tilt - + ", zoom=" + zoom - + ", padding=" + Arrays.toString(padding) - + '}'; - } - } - - static final class CameraBoundsUpdate implements CameraUpdate { - - private final LatLngBounds bounds; - private final int[] padding; - private final Double bearing; - private final Double tilt; - - CameraBoundsUpdate(LatLngBounds bounds, Double bearing, Double tilt, int[] padding) { - this.bounds = bounds; - this.padding = padding; - this.bearing = bearing; - this.tilt = tilt; - } - - CameraBoundsUpdate(LatLngBounds bounds, Double bearing, Double tilt, int paddingLeft, - int paddingTop, int paddingRight, int paddingBottom) { - this(bounds, bearing, tilt, new int[] {paddingLeft, paddingTop, paddingRight, paddingBottom}); - } - - public LatLngBounds getBounds() { - return bounds; - } - - public int[] getPadding() { - return padding; - } - - @Override - public CameraPosition getCameraPosition(@NonNull MapboxMap mapboxMap) { - if (bearing == null && tilt == null) { - // use current camera position tilt and bearing - return mapboxMap.getCameraForLatLngBounds(bounds, padding); - } else { - // use provided tilt and bearing - assert bearing != null; - assert tilt != null; - return mapboxMap.getCameraForLatLngBounds(bounds, padding, bearing, tilt); - } - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - CameraBoundsUpdate that = (CameraBoundsUpdate) o; - - if (!bounds.equals(that.bounds)) { - return false; - } - return Arrays.equals(padding, that.padding); - } - - @Override - public int hashCode() { - int result = bounds.hashCode(); - result = 31 * result + Arrays.hashCode(padding); - return result; - } - - @Override - public String toString() { - return "CameraBoundsUpdate{" - + "bounds=" + bounds - + ", padding=" + Arrays.toString(padding) - + '}'; - } - } - - static final class CameraMoveUpdate implements CameraUpdate { - - private float x; - private float y; - - CameraMoveUpdate(float x, float y) { - this.x = x; - this.y = y; - } - - @Override - public CameraPosition getCameraPosition(@NonNull MapboxMap mapboxMap) { - UiSettings uiSettings = mapboxMap.getUiSettings(); - Projection projection = mapboxMap.getProjection(); - // Calculate the new center point - float viewPortWidth = uiSettings.getWidth(); - float viewPortHeight = uiSettings.getHeight(); - int[] padding = mapboxMap.getPadding(); - - // we inverse the map padding, is reapplied when using moveTo/easeTo or animateTo - PointF targetPoint = new PointF( - (viewPortWidth - padding[0] + padding[1]) / 2 + x, - (viewPortHeight + padding[1] - padding[3]) / 2 + y - ); - - LatLng latLng = projection.fromScreenLocation(targetPoint); - CameraPosition previousPosition = mapboxMap.getCameraPosition(); - CameraPosition position = - new CameraPosition.Builder() - .target(latLng) - .zoom(previousPosition.zoom) - .tilt(previousPosition.tilt) - .bearing(previousPosition.bearing) - .build(); - return position; - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - CameraMoveUpdate that = (CameraMoveUpdate) o; - - if (Float.compare(that.x, x) != 0) { - return false; - } - return Float.compare(that.y, y) == 0; - } - - @Override - public int hashCode() { - int result = (x != +0.0f ? Float.floatToIntBits(x) : 0); - result = 31 * result + (y != +0.0f ? Float.floatToIntBits(y) : 0); - return result; - } - - @Override - public String toString() { - return "CameraMoveUpdate{" - + "x=" + x - + ", y=" + y - + '}'; - } - } - - static final class ZoomUpdate implements CameraUpdate { - - @IntDef( {ZOOM_IN, ZOOM_OUT, ZOOM_BY, ZOOM_TO, ZOOM_TO_POINT}) - @Retention(RetentionPolicy.SOURCE) - @interface Type { - } - - static final int ZOOM_IN = 0; - static final int ZOOM_OUT = 1; - static final int ZOOM_BY = 2; - static final int ZOOM_TO = 3; - static final int ZOOM_TO_POINT = 4; - - @Type - private final int type; - private final double zoom; - private float x; - private float y; - - ZoomUpdate(@Type int type) { - this.type = type; - this.zoom = 0; - } - - ZoomUpdate(@Type int type, double zoom) { - this.type = type; - this.zoom = zoom; - } - - ZoomUpdate(double zoom, float x, float y) { - this.type = ZOOM_TO_POINT; - this.zoom = zoom; - this.x = x; - this.y = y; - } - - public double getZoom() { - return zoom; - } - - @Type - public int getType() { - return type; - } - - public float getX() { - return x; - } - - public float getY() { - return y; - } - - double transformZoom(double currentZoom) { - switch (getType()) { - case CameraUpdateFactory.ZoomUpdate.ZOOM_IN: - currentZoom++; - break; - case CameraUpdateFactory.ZoomUpdate.ZOOM_OUT: - currentZoom--; - if (currentZoom < 0) { - currentZoom = 0; - } - break; - case CameraUpdateFactory.ZoomUpdate.ZOOM_TO: - currentZoom = getZoom(); - break; - case CameraUpdateFactory.ZoomUpdate.ZOOM_BY: - currentZoom = currentZoom + getZoom(); - break; - case CameraUpdateFactory.ZoomUpdate.ZOOM_TO_POINT: - currentZoom = currentZoom + getZoom(); - break; - } - return currentZoom; - } - - @Override - public CameraPosition getCameraPosition(@NonNull MapboxMap mapboxMap) { - CameraPosition cameraPosition = mapboxMap.getCameraPosition(); - if (getType() != CameraUpdateFactory.ZoomUpdate.ZOOM_TO_POINT) { - return new CameraPosition.Builder(cameraPosition) - .zoom(transformZoom(cameraPosition.zoom)) - .build(); - } else { - return new CameraPosition.Builder(cameraPosition) - .zoom(transformZoom(cameraPosition.zoom)) - .target(mapboxMap.getProjection().fromScreenLocation(new PointF(getX(), getY()))) - .build(); - } - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - ZoomUpdate that = (ZoomUpdate) o; - - if (type != that.type) { - return false; - } - if (Double.compare(that.zoom, zoom) != 0) { - return false; - } - if (Float.compare(that.x, x) != 0) { - return false; - } - return Float.compare(that.y, y) == 0; - } - - @Override - public int hashCode() { - int result; - long temp; - result = type; - temp = Double.doubleToLongBits(zoom); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - result = 31 * result + (x != +0.0f ? Float.floatToIntBits(x) : 0); - result = 31 * result + (y != +0.0f ? Float.floatToIntBits(y) : 0); - return result; - } - - @Override - public String toString() { - return "ZoomUpdate{" - + "type=" + type - + ", zoom=" + zoom - + ", x=" + x - + ", y=" + y - + '}'; - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/package-info.java deleted file mode 100644 index 04ef699c2..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/camera/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Camera API classes. - */ -package com.mapbox.mapboxsdk.camera; 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 deleted file mode 100644 index 6f6e77792..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/GeometryConstants.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -/** - * Contains constants used throughout the sdk classes. - */ -public class GeometryConstants { - - /** - * The equatorial radius - * value in meters - */ - public static final int RADIUS_EARTH_METERS = 6378137; - - /** - * This constant represents the lowest longitude value available to represent a wrapped geolocation. - */ - public static final double MIN_WRAP_LONGITUDE = -180; - - /** - * This constant represents the highest longitude value available to represent a wrapped geolocation. - */ - public static final double MAX_WRAP_LONGITUDE = 180; - - /** - * This constant represents the lowest longitude value available to represent a geolocation. - */ - public static final double MIN_LONGITUDE = -Double.MAX_VALUE; - - /** - * This constant represents the highest longitude value available to represent a geolocation. - */ - public static final double MAX_LONGITUDE = Double.MAX_VALUE; - - /** - * This constant represents the lowest latitude value available to represent a geolocation. - */ - public static final double MIN_LATITUDE = -90; - - /** - * This constant represents the latitude span when representing a geolocation. - */ - public static final double LATITUDE_SPAN = 180; - - /** - * This constant represents the longitude span when representing a geolocation. - */ - public static final double LONGITUDE_SPAN = 360; - - /** - * This constant represents the highest latitude value available to represent a geolocation. - */ - public static final double MAX_LATITUDE = 90; - - /** - * Maximum latitude value in Mercator projection. - */ - public static final double MAX_MERCATOR_LATITUDE = 85.05112877980659; - - /** - * Minimum latitude value in Mercator projection. - */ - 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 deleted file mode 100644 index 6156b3af7..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/MapboxConstants.java +++ /dev/null @@ -1,232 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -import java.util.Locale; - -/** - * MapboxConstants exposes Mapbox related constants - */ -public class MapboxConstants { - - /** - * Default Locale for data processing (ex: String.toLowerCase(MAPBOX_LOCALE, "foo")) - */ - public static final Locale MAPBOX_LOCALE = Locale.US; - - /** - * The name of the desired preferences file for Android's SharedPreferences. - */ - public static final String MAPBOX_SHARED_PREFERENCES = "MapboxSharedPreferences"; - - /** - * Key used to switch storage to external in AndroidManifest.xml - */ - public static final String KEY_META_DATA_SET_STORAGE_EXTERNAL = "com.mapbox.SetStorageExternal"; - - /** - * Default value for KEY_META_DATA_SET_STORAGE_EXTERNAL (default is internal storage) - */ - public static final boolean DEFAULT_SET_STORAGE_EXTERNAL = false; - - /** - * Key used to switch Tile Download Measuring on/off in AndroidManifest.xml - */ - public static final String KEY_META_DATA_MEASURE_TILE_DOWNLOAD_ON = "com.mapbox.MeasureTileDownloadOn"; - - /** - * Default value for KEY_META_DATA_MEASURE_TILE_DOWNLOAD_ON (default is off) - */ - public static final boolean DEFAULT_MEASURE_TILE_DOWNLOAD_ON = false; - - public static final String KEY_PREFERENCE_SKU_TOKEN = "com.mapbox.mapboxsdk.accounts.skutoken"; - - public static final String KEY_META_DATA_MANAGE_SKU_TOKEN = "com.mapbox.ManageSkuToken"; - - public static final boolean DEFAULT_MANAGE_SKU_TOKEN = true; - - /** - * Default value for font fallback for local ideograph fonts - */ - public static final String DEFAULT_FONT = "sans-serif"; - - /** - * Unmeasured state - */ - public static final float UNMEASURED = -1f; - - /** - * Default animation time - */ - public static final int ANIMATION_DURATION = 300; - - /** - * Default short animation time - */ - public static final int ANIMATION_DURATION_SHORT = 150; - - /** - * Animation time of a fling gesture - */ - public static final long ANIMATION_DURATION_FLING_BASE = ANIMATION_DURATION_SHORT; - - /** - * Velocity threshold for a fling gesture - */ - public static final long VELOCITY_THRESHOLD_IGNORE_FLING = 1000; - - /** - * Value by which the default rotation threshold will be increased when scaling - * - * @deprecated unused, see {@link com.mapbox.mapboxsdk.maps.UiSettings#setDisableRotateWhenScaling(boolean)} - */ - @Deprecated - public static final float ROTATION_THRESHOLD_INCREASE_WHEN_SCALING = 25f; - - /** - * Maximum absolute zoom change for multi-pointer scale velocity animation - */ - public static final double MAX_ABSOLUTE_SCALE_VELOCITY_CHANGE = 2.5; - - /** - * Maximum possible zoom change during the quick zoom gesture executed across the whole screen - */ - public static final double QUICK_ZOOM_MAX_ZOOM_CHANGE = 4.0; - - /** - * Scale velocity animation duration multiplier. - */ - public static final double SCALE_VELOCITY_ANIMATION_DURATION_MULTIPLIER = 150; - - /** - * Minimum angular velocity for rotation animation - * - * @deprecated unused, see {@link #ROTATE_VELOCITY_RATIO_THRESHOLD} - */ - @Deprecated - public static final float MINIMUM_ANGULAR_VELOCITY = 1.5f; - - /** - * Last scale span delta to XY velocity ratio required to execute scale velocity animation. - */ - public static final double SCALE_VELOCITY_RATIO_THRESHOLD = 4 * 1e-3; - - /** - * Last rotation delta to XY velocity ratio required to execute rotation velocity animation. - */ - public static final double ROTATE_VELOCITY_RATIO_THRESHOLD = 2.2 * 1e-4; - - /** - * Time within which user needs to lift fingers for velocity animation to start. - */ - public static final long SCHEDULED_ANIMATION_TIMEOUT = 150L; - - /** - * Maximum angular velocity for rotation animation - */ - public static final float MAXIMUM_ANGULAR_VELOCITY = 30f; - - /** - * 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; - - /** - * The currently supported maximum zoom level. - */ - public static final float MAXIMUM_ZOOM = 25.5f; - - /** - * The currently supported maximum tilt value. - */ - public static final double MAXIMUM_TILT = 60; - - /** - * The currently supported minimum tilt value. - */ - public static final double MINIMUM_TILT = 0; - - /** - * The currently supported maximum direction - */ - public static final double MAXIMUM_DIRECTION = 360; - - /** - * The currently supported minimum direction - */ - public static final double MINIMUM_DIRECTION = 0; - - /** - * The currently used minimum scale factor to clamp to when a quick zoom gesture occurs - * - * @deprecated unused - */ - @Deprecated - 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 - * - * @deprecated unused - */ - @Deprecated - public static final float MAXIMUM_SCALE_FACTOR_CLAMP = 0.15f; - - /** - * Zoom value multiplier for scale gestures. - */ - public static final float ZOOM_RATE = 0.65f; - - /** - * Fragment Argument Key for MapboxMapOptions - */ - public static final String FRAG_ARG_MAPBOXMAPOPTIONS = "MapboxMapOptions"; - - /** - * Layer Id of annotations layer - */ - public static final String LAYER_ID_ANNOTATIONS = "com.mapbox.annotations.points"; - - // Save instance state keys - 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_SCROLL_ENABLED = "mapbox_scrollEnabled"; - public static final String STATE_ROTATE_ENABLED = "mapbox_rotateEnabled"; - public static final String STATE_TILT_ENABLED = "mapbox_tiltEnabled"; - public static final String STATE_DOUBLE_TAP_ENABLED = "mapbox_doubleTapEnabled"; - public static final String STATE_QUICK_ZOOM_ENABLED = "mapbox_quickZoom"; - public static final String STATE_ZOOM_RATE = "mapbox_zoomRate"; - public static final String STATE_DEBUG_ACTIVE = "mapbox_debugActive"; - 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"; - public static final String STATE_COMPASS_MARGIN_TOP = "mapbox_compassMarginTop"; - public static final String STATE_COMPASS_MARGIN_RIGHT = "mapbox_compassMarginRight"; - public static final String STATE_COMPASS_MARGIN_BOTTOM = "mapbox_compassMarginBottom"; - public static final String STATE_COMPASS_FADE_WHEN_FACING_NORTH = "mapbox_compassFade"; - public static final String STATE_COMPASS_IMAGE_BITMAP = "mapbox_compassImage"; - public static final String STATE_LOGO_GRAVITY = "mapbox_logoGravity"; - public static final String STATE_LOGO_MARGIN_LEFT = "mapbox_logoMarginLeft"; - public static final String STATE_LOGO_MARGIN_TOP = "mapbox_logoMarginTop"; - public static final String STATE_LOGO_MARGIN_RIGHT = "mapbox_logoMarginRight"; - public static final String STATE_LOGO_MARGIN_BOTTOM = "mapbox_logoMarginBottom"; - public static final String STATE_LOGO_ENABLED = "mapbox_logoEnabled"; - public static final String STATE_ATTRIBUTION_GRAVITY = "mapbox_attrGravity"; - public static final String STATE_ATTRIBUTION_MARGIN_LEFT = "mapbox_attrMarginLeft"; - public static final String STATE_ATTRIBUTION_MARGIN_TOP = "mapbox_attrMarginTop"; - 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_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_DISABLE_ROTATE_WHEN_SCALING = "mapbox_disableRotateWhenScaling"; - public static final String STATE_INCREASE_SCALE_THRESHOLD = "mapbox_increaseScaleThreshold"; -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/TelemetryConstants.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/TelemetryConstants.java deleted file mode 100644 index 3dbae9de4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/TelemetryConstants.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -@Deprecated -public class TelemetryConstants { - - public static final String TWO_FINGER_TAP = "TwoFingerTap"; - public static final String DOUBLE_TAP = "DoubleTap"; - public static final String SINGLE_TAP = "SingleTap"; - public static final String PAN = "Pan"; - public static final String PINCH = "Pinch"; - public static final String ROTATION = "Rotation"; - public static final String PITCH = "Pitch"; - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/package-info.java deleted file mode 100644 index 165394c03..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/constants/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Constant API classes. - */ -package com.mapbox.mapboxsdk.constants; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/CalledFromWorkerThreadException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/CalledFromWorkerThreadException.java deleted file mode 100644 index 32e852d31..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/CalledFromWorkerThreadException.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -public class CalledFromWorkerThreadException extends RuntimeException { - - public CalledFromWorkerThreadException(String message) { - super(message); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/ConversionException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/ConversionException.java deleted file mode 100644 index 0d16c53b8..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/ConversionException.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -/** - * A ConversionException is thrown when a conversion failed to execute. - */ -public class ConversionException extends RuntimeException { - - public ConversionException(String detailMessage) { - super(detailMessage); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/IconBitmapChangedException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/IconBitmapChangedException.java deleted file mode 100644 index 1f6b0efc4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/IconBitmapChangedException.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -import com.mapbox.mapboxsdk.annotations.Icon; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.maps.MapView; - -/** - *

- * An IconBitmapChangedException is thrown by MapView when a Marker is added - * that has an Icon with a Bitmap that has been modified since the creation of the Icon. - *

- * You cannot modify a {@code Icon} after it has been added to the map in a {@code Marker} - * - * @see MapView - * @see Icon - * @see Marker - */ -public class IconBitmapChangedException extends RuntimeException { - - public IconBitmapChangedException() { - super("The added Marker has an Icon with a bitmap that has been modified. An Icon cannot be modified" - + "after it has been added to the map in a Marker."); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidLatLngBoundsException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidLatLngBoundsException.java deleted file mode 100644 index c1d038581..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidLatLngBoundsException.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -/** - * An InvalidLatLngBoundsException is thrown by LatLngBounds - * when there aren't enough LatLng to create a bounds. - */ -public class InvalidLatLngBoundsException extends RuntimeException { - - public InvalidLatLngBoundsException(int latLngsListSize) { - super("Cannot create a LatLngBounds from " + latLngsListSize + " items"); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidMarkerPositionException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidMarkerPositionException.java deleted file mode 100644 index 44ee83265..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/InvalidMarkerPositionException.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -/** - * A InvalidMarkerPositionException is thrown when a Marker object is created with an invalid LatLng position. - */ -public class InvalidMarkerPositionException extends RuntimeException { - - /** - * Creates a invalid marker position exception thrown when a Marker object is created with an invalid LatLng position. - */ - public InvalidMarkerPositionException() { - super("Adding an invalid Marker to a Map. " - + "Missing the required position field. " - + "Provide a non null LatLng as position to the Marker."); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/MapboxConfigurationException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/MapboxConfigurationException.java deleted file mode 100644 index 431de85f0..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/MapboxConfigurationException.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -import android.content.Context; -import android.support.annotation.NonNull; - -/** - * A MapboxConfigurationException is thrown by MapboxMap when the SDK hasn't been properly initialised. - *

- * This occurs either when {@link com.mapbox.mapboxsdk.Mapbox} is not correctly initialised or the provided access token - * through {@link com.mapbox.mapboxsdk.Mapbox#getInstance(Context, String)} isn't valid. - *

- * - * @see com.mapbox.mapboxsdk.Mapbox#getInstance(Context, String) - */ -public class MapboxConfigurationException extends RuntimeException { - - /** - * Creates a Mapbox configuration exception thrown by MapboxMap when the SDK hasn't been properly initialised. - */ - public MapboxConfigurationException() { - super("\nUsing MapView requires calling Mapbox.getInstance(Context context, String accessToken) before " - + "inflating or creating the view. The access token parameter is required when using a Mapbox service." - + "\nPlease see https://www.mapbox.com/help/create-api-access-token/ to learn how to create one." - + "\nMore information in this guide https://www.mapbox.com/help/first-steps-android-sdk/#access-tokens."); - } - - /** - * Creates a Mapbox configuration exception thrown by MapboxMap when the SDK hasn't been properly initialised. - */ - public MapboxConfigurationException(@NonNull String message) { - super(message); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/TooManyIconsException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/TooManyIconsException.java deleted file mode 100644 index bffc10dc0..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/TooManyIconsException.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.mapbox.mapboxsdk.exceptions; - -import com.mapbox.mapboxsdk.annotations.IconFactory; - -/** - *

- * A TooManyIconsException is thrown by IconFactory when it - * cannot create a Icon because there are already too many icons created. - *

- * You should try to reuse Icon objects whenever possible. - * - * @see IconFactory - */ -public class TooManyIconsException extends RuntimeException { - - public TooManyIconsException() { - super("Cannot create an Icon because there are already too many. Try reusing Icon objects whenever possible."); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/package-info.java deleted file mode 100644 index 09ecd55c1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/exceptions/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Exception API classes. - */ -package com.mapbox.mapboxsdk.exceptions; 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 deleted file mode 100644 index ce12489b4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLng.java +++ /dev/null @@ -1,334 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.location.Location; -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.FloatRange; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.geojson.Point; -import com.mapbox.mapboxsdk.constants.GeometryConstants; -import com.mapbox.turf.TurfMeasurement; - -import static com.mapbox.turf.TurfConstants.UNIT_METRES; - - -/** - * A geographical location which contains a single latitude, longitude pair, with - * optional altitude. - *

- * Latitude and longitude are expressed as decimal degrees - * in the WGS84 datum. By default, altitude is 0.0, or sea level. - *

- *

- * Mapbox GL displays maps in the Mercator Projection and projects geographical - * data automatically, so all data enters in the WGS84 datum. - *

- */ -public class LatLng implements Parcelable { - - /** - * Inner class responsible for recreating Parcels into objects. - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public LatLng createFromParcel(@NonNull Parcel in) { - return new LatLng(in); - } - - public LatLng[] newArray(int size) { - return new LatLng[size]; - } - }; - - @Keep - private double latitude; - @Keep - private double longitude; - private double altitude = 0.0; - - /** - * Construct a new latitude, longitude point at (0, 0) - */ - public LatLng() { - this.latitude = 0.0; - this.longitude = 0.0; - } - - /** - * Construct a new latitude, longitude point given double arguments - * - * @param latitude Latitude in degrees - * @param longitude Longitude in degrees - */ - @Keep - public LatLng(double latitude, double longitude) { - setLatitude(latitude); - setLongitude(longitude); - } - - /** - * Construct a new latitude, longitude, altitude point given double arguments - * - * @param latitude Latitude in degrees - * @param longitude Longitude in degress - * @param altitude Altitude in meters - */ - public LatLng(double latitude, double longitude, double altitude) { - setLatitude(latitude); - setLongitude(longitude); - setAltitude(altitude); - } - - /** - * Construct a new latitude, longitude, altitude point given location argument - * - * @param location Android Location - */ - public LatLng(Location location) { - this(location.getLatitude(), location.getLongitude(), location.getAltitude()); - } - - /** - * Construct a new latitude, longitude, altitude point given another latitude, longitude, altitude point. - * - * @param latLng LatLng to be cloned. - */ - public LatLng(LatLng latLng) { - this.latitude = latLng.latitude; - this.longitude = latLng.longitude; - this.altitude = latLng.altitude; - } - - /** - * Constructs a new latitude, longitude, altitude tuple given a parcel. - * - * @param in the parcel containing the latitude, longitude, altitude values - */ - protected LatLng(Parcel in) { - setLatitude(in.readDouble()); - setLongitude(in.readDouble()); - setAltitude(in.readDouble()); - } - - /** - * Set the latitude, in degrees. - *

- * This value is in the range of [-90, 90], see {@link GeometryConstants#MIN_LATITUDE} and - * {@link GeometryConstants#MAX_LATITUDE} - *

- * - * @param latitude the latitude value in degrees - * @see GeometryConstants#MIN_LATITUDE - * @see GeometryConstants#MAX_LATITUDE - */ - public void setLatitude( - @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) > GeometryConstants.MAX_LATITUDE) { - throw new IllegalArgumentException("latitude must be between -90 and 90"); - } - this.latitude = latitude; - } - - /** - * Get the latitude, in degrees. - *

- * This value is in the range of [-90, 90], see {@link GeometryConstants#MIN_LATITUDE} and - * {@link GeometryConstants#MAX_LATITUDE} - *

- * - * @return the latitude value in degrees - * @see GeometryConstants#MIN_LATITUDE - * @see GeometryConstants#MAX_LATITUDE - */ - public double getLatitude() { - return latitude; - } - - /** - * Set the longitude, in degrees. - *

- * This value is in the range of [-180, 180], see {@link GeometryConstants#MIN_LONGITUDE} and - * {@link GeometryConstants#MAX_LONGITUDE} - *

- * - * @param longitude the longitude value in degrees - * @see GeometryConstants#MIN_LONGITUDE - * @see GeometryConstants#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"); - } - if (Double.isInfinite(longitude)) { - throw new IllegalArgumentException("longitude must not be infinite"); - } - this.longitude = longitude; - } - - /** - * Get the longitude, in degrees. - *

- * This value is in the range of [-180, 180], see {@link GeometryConstants#MIN_LONGITUDE} and - * {@link GeometryConstants#MAX_LONGITUDE} - *

- * - * @return the longitude value in degrees - * @see GeometryConstants#MIN_LONGITUDE - * @see GeometryConstants#MAX_LONGITUDE - */ - public double getLongitude() { - return longitude; - } - - /** - * Set the altitude, in meters. - * - * @param altitude the altitude in meters - */ - public void setAltitude(double altitude) { - this.altitude = altitude; - } - - /** - * Get the altitude, in meters. - * - * @return the altitude value in meters - */ - public double getAltitude() { - return altitude; - } - - /** - * Return a new LatLng object with a wrapped Longitude. This allows original data object - * to remain unchanged. - * - * @return new LatLng object with wrapped Longitude - */ - @NonNull - public LatLng wrap() { - return new LatLng(latitude, wrap(longitude, - GeometryConstants.MIN_WRAP_LONGITUDE, GeometryConstants.MAX_WRAP_LONGITUDE) - ); - } - - - /** - * Constrains value to the given range (including min & max) via modular arithmetic. - *

- * 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; - } - - /** - * Indicates whether some other object is "equal to" this one. - * - * @param object The object to compare - * @return True if equal, false if not - */ - @Override - public boolean equals(@Nullable Object object) { - if (this == object) { - return true; - } - if (object == null || getClass() != object.getClass()) { - return false; - } - - LatLng latLng = (LatLng) object; - - return Double.compare(latLng.altitude, altitude) == 0 && Double.compare(latLng.latitude, latitude) == 0 - && Double.compare(latLng.longitude, longitude) == 0; - } - - /** - * Returns a hash code value for the object. - * - * @return the hash code value - */ - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(latitude); - result = (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(longitude); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(altitude); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - /** - * Returns a string representation of the object. - * - * @return the string representation - */ - @NonNull - @Override - public String toString() { - return "LatLng [latitude=" + latitude + ", longitude=" + longitude + ", altitude=" + altitude + "]"; - } - - /** - * Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. - * - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written - */ - @Override - public void writeToParcel(@NonNull Parcel out, int flags) { - out.writeDouble(latitude); - out.writeDouble(longitude); - out.writeDouble(altitude); - } - - /** - * Calculate distance between two points - * - * @param other Other LatLng to compare to - * @return distance in meters - */ - public double distanceTo(@NonNull LatLng other) { - return TurfMeasurement.distance( - Point.fromLngLat(longitude, latitude), - Point.fromLngLat(other.getLongitude(), other.getLatitude()), - UNIT_METRES - ); - } -} 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 deleted file mode 100644 index 263780f47..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngBounds.java +++ /dev/null @@ -1,608 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.FloatRange; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.constants.GeometryConstants; -import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException; - -import java.util.ArrayList; -import java.util.List; - -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MAX_LATITUDE; -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MAX_LONGITUDE; -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MAX_WRAP_LONGITUDE; -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MIN_LATITUDE; -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MIN_LONGITUDE; -import static com.mapbox.mapboxsdk.constants.GeometryConstants.MIN_WRAP_LONGITUDE; - -/** - * A geographical area representing a latitude/longitude aligned rectangle. - *

- * This class does not wrap values to the world bounds. - *

- */ -public class LatLngBounds implements Parcelable { - - @Keep - private final double latitudeNorth; - @Keep - private final double latitudeSouth; - @Keep - private final double longitudeEast; - @Keep - private final double longitudeWest; - - /** - * Construct a new LatLngBounds based on its corners, given in NESW - * order. - *

- * @since 7.0.0 LatLngBounds cannot be wrapped any more, i.e longitudeWest has to be - * less or equal to longitudeEast. - * - * For example, to represent bounds spanning 20 degrees crossing antimeridian with - * the NE point as (10, -170) and the SW point as (-10, 170), - * use (10, -190) and (-10, -170), or (10, -170) and (-10, -150). - * - * @param northLatitude Northern Latitude - * @param eastLongitude Eastern Longitude - * @param southLatitude Southern Latitude - * @param westLongitude Western Longitude - */ - @Keep - LatLngBounds(final double northLatitude, final double eastLongitude, - final double southLatitude, final double westLongitude) { - this.latitudeNorth = northLatitude; - this.longitudeEast = eastLongitude; - this.latitudeSouth = southLatitude; - this.longitudeWest = westLongitude; - } - - /** - * Returns the world bounds. - * - * @return the bounds representing the world - */ - public static LatLngBounds world() { - return LatLngBounds.from( - MAX_LATITUDE, MAX_WRAP_LONGITUDE, - MIN_LATITUDE, MIN_WRAP_LONGITUDE); - } - - /** - * Calculates the centerpoint of this LatLngBounds by simple interpolation and returns - * it as a point. This is a non-geodesic calculation which is not the geographic center. - * - * @return LatLng center of this LatLngBounds - */ - @NonNull - public LatLng getCenter() { - double latCenter = (this.latitudeNorth + this.latitudeSouth) / 2.0; - double longCenter = (this.longitudeEast + this.longitudeWest) / 2.0; - - return new LatLng(latCenter, longCenter); - } - - /** - * Get the north latitude value of this bounds. - * - * @return double latitude value for north - */ - public double getLatNorth() { - return this.latitudeNorth; - } - - /** - * Get the south latitude value of this bounds. - * - * @return double latitude value for south - */ - public double getLatSouth() { - return this.latitudeSouth; - } - - /** - * Get the east longitude value of this bounds. - * - * @return double longitude value for east - */ - public double getLonEast() { - return this.longitudeEast; - } - - /** - * Get the west longitude value of this bounds. - * - * @return double longitude value for west - */ - public double getLonWest() { - return this.longitudeWest; - } - - /** - * Get the latitude-longitude pair of the south west corner of this bounds. - * - * @return LatLng of the south west corner - */ - @NonNull - public LatLng getSouthWest() { - return new LatLng(latitudeSouth, longitudeWest); - } - - /** - * Get the latitude-longitude paur if the north east corner of this bounds. - * - * @return LatLng of the north east corner - */ - @NonNull - public LatLng getNorthEast() { - return new LatLng(latitudeNorth, longitudeEast); - } - - /** - * Get the latitude-longitude pair of the south east corner of this bounds. - * - * @return LatLng of the south east corner - */ - @NonNull - public LatLng getSouthEast() { - return new LatLng(latitudeSouth, longitudeEast); - } - - /** - * Get the latitude-longitude pair of the north west corner of this bounds. - * - * @return LatLng of the north west corner - */ - @NonNull - public LatLng getNorthWest() { - return new LatLng(latitudeNorth, longitudeWest); - } - - /** - * Get the area spanned by this LatLngBounds - * - * @return LatLngSpan area - */ - @NonNull - public LatLngSpan getSpan() { - return new LatLngSpan(getLatitudeSpan(), getLongitudeSpan()); - } - - /** - * Get the absolute distance, in degrees, between the north and - * south boundaries of this LatLngBounds - * - * @return Span distance - */ - public double getLatitudeSpan() { - return Math.abs(this.latitudeNorth - this.latitudeSouth); - } - - /** - * Get the absolute distance, in degrees, between the west and - * east boundaries of this LatLngBounds - * - * @return Span distance - */ - public double getLongitudeSpan() { - return Math.abs(this.longitudeEast - this.longitudeWest); - } - - /** - * Validate if LatLngBounds is empty, determined if absolute distance is - * - * @return boolean indicating if span is empty - */ - public boolean isEmptySpan() { - return getLongitudeSpan() == 0.0 || getLatitudeSpan() == 0.0; - } - - /** - * Returns a string representaton of the object. - * - * @return the string representation - */ - @NonNull - @Override - public String toString() { - return "N:" + this.latitudeNorth + "; E:" + this.longitudeEast + "; S:" + this.latitudeSouth - + "; W:" + this.longitudeWest; - } - - /** - * Constructs a LatLngBounds that contains all of a list of LatLng - * objects. Empty lists will yield invalid LatLngBounds. - * - * @param latLngs List of LatLng objects - * @return LatLngBounds - */ - static LatLngBounds fromLatLngs(final List latLngs) { - double minLat = MAX_LATITUDE; - double minLon = MAX_LONGITUDE; - double maxLat = MIN_LATITUDE; - double maxLon = MIN_LONGITUDE; - - for (final LatLng 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); - } - - return new LatLngBounds(maxLat, maxLon, minLat, minLon); - } - - /** - * Return an array of LatLng objects resembling this bounds. - * - * @return an array of 2 LatLng objects. - */ - @NonNull - public LatLng[] toLatLngs() { - return new LatLng[] {getNorthEast(), getSouthWest()}; - } - - /** - * Constructs a LatLngBounds from doubles representing a LatLng pair. - *

- * 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. - *

- * This method doesn't recalculate most east or most west boundaries. - * Note @since 7.0.0 lonEast and lonWest will NOT be wrapped to be in the range of [-180, 180], - * see {@link GeometryConstants#MIN_LONGITUDE} and {@link GeometryConstants#MAX_LONGITUDE} - * lonEast should be greater or equal lonWest, otherwise IllegalArgumentException will be thrown. - *

- */ - public static LatLngBounds from( - @FloatRange(from = MIN_LATITUDE, to = MAX_LATITUDE) double latNorth, - double lonEast, - @FloatRange(from = MIN_LATITUDE, to = MAX_LATITUDE) double latSouth, - double lonWest) { - - checkParams(latNorth, lonEast, latSouth, lonWest); - - return new LatLngBounds(latNorth, lonEast, latSouth, lonWest); - } - - private static void checkParams( - @FloatRange(from = MIN_LATITUDE, to = MAX_LATITUDE) double latNorth, - double lonEast, - @FloatRange(from = MIN_LATITUDE, to = 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 > MAX_LATITUDE || latNorth < MIN_LATITUDE - || latSouth > MAX_LATITUDE || latSouth < MIN_LATITUDE) { - throw new IllegalArgumentException("latitude must be between -90 and 90"); - } - - if (latNorth < latSouth) { - throw new IllegalArgumentException("latNorth cannot be less than latSouth"); - } - - if (lonEast < lonWest) { - throw new IllegalArgumentException("lonEast cannot be less than 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_WRAP_LONGITUDE; - } - - /** - * Constructs a LatLngBounds from a Tile identifier. - *

- * 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. - * - * @param latLng the latitude lognitude pair to include in the bounds. - * @return the newly constructed bounds - */ - @NonNull - public LatLngBounds include(@NonNull LatLng latLng) { - return new LatLngBounds.Builder() - .include(getNorthEast()) - .include(getSouthWest()) - .include(latLng) - .build(); - } - - /** - * Determines whether this LatLngBounds matches another one via LatLng. - * - * @param o another object - * @return a boolean indicating whether the LatLngBounds are equal - */ - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o instanceof LatLngBounds) { - LatLngBounds other = (LatLngBounds) o; - return latitudeNorth == other.getLatNorth() - && latitudeSouth == other.getLatSouth() - && longitudeEast == other.getLonEast() - && longitudeWest == other.getLonWest(); - } - return false; - } - - - private boolean containsLatitude(final double latitude) { - return (latitude <= this.latitudeNorth) - && (latitude >= this.latitudeSouth); - } - - private boolean containsLongitude(final double longitude) { - return (longitude <= this.longitudeEast) - && (longitude >= this.longitudeWest); - } - - /** - * Determines whether this LatLngBounds contains a point. - * - * @param latLng the point which may be contained - * @return true, if the point is contained within the bounds - */ - public boolean contains(@NonNull final LatLng latLng) { - return containsLatitude(latLng.getLatitude()) - && containsLongitude(latLng.getLongitude()); - } - - /** - * Determines whether this LatLngBounds contains another bounds. - * - * @param other the bounds which may be contained - * @return true, if the bounds is contained within the bounds - */ - public boolean contains(@NonNull final LatLngBounds other) { - return contains(other.getNorthEast()) - && contains(other.getSouthWest()); - } - - /** - * Returns a new LatLngBounds that stretches to contain both this and another LatLngBounds. - * - * @param bounds LatLngBounds to add - * @return LatLngBounds - */ - @NonNull - public LatLngBounds union(@NonNull LatLngBounds bounds) { - return unionNoParamCheck(bounds.getLatNorth(), bounds.getLonEast(), - bounds.getLatSouth(), bounds.getLonWest()); - } - - /** - * Returns a new LatLngBounds that stretches to contain both this and another LatLngBounds. - * - *

- * This values of northLat and southLat should be in the range of [-90, 90], - * see {@link GeometryConstants#MIN_LATITUDE} and {@link GeometryConstants#MAX_LATITUDE}, - * otherwise IllegalArgumentException will be thrown. - * northLat should be greater or equal southLat, otherwise IllegalArgumentException will be thrown. - * - *

- * eastLon should be greater or equal westLon, otherwise IllegalArgumentException will be thrown. - * - * @param northLat Northern Latitude corner point - * @param eastLon Eastern Longitude corner point - * @param southLat Southern Latitude corner point - * @param westLon Western Longitude corner point - * @return LatLngBounds - */ - @NonNull - public LatLngBounds union(final double northLat, final double eastLon, - final double southLat, final double westLon) { - checkParams(northLat, eastLon, southLat, westLon); - return unionNoParamCheck(northLat, eastLon, southLat, westLon); - } - - private LatLngBounds unionNoParamCheck(final double northLat, final double eastLon, - final double southLat, final double westLon) { - - return new LatLngBounds((this.latitudeNorth < northLat) ? northLat : this.latitudeNorth, - (this.longitudeEast < eastLon) ? eastLon : this.longitudeEast, - (this.latitudeSouth > southLat) ? southLat : this.latitudeSouth, - (this.longitudeWest > westLon) ? westLon : this.longitudeWest); - } - - /** - * Returns a new LatLngBounds that is the intersection of this with another LatLngBounds, - * - * @param box LatLngBounds to intersect with - * @return LatLngBounds - */ - @Nullable - public LatLngBounds intersect(@NonNull LatLngBounds box) { - return intersectNoParamCheck(box.getLatNorth(), box.getLonEast(), box.getLatSouth(), box.getLonWest()); - } - - - /** - * Returns a new LatLngBounds that is the intersection of this with another box. - * - *

- * This values of northLat and southLat should be in the range of [-90, 90], - * see {@link GeometryConstants#MIN_LATITUDE} and {@link GeometryConstants#MAX_LATITUDE}, - * otherwise IllegalArgumentException will be thrown. - * northLat should be greater or equal southLat, otherwise IllegalArgumentException will be thrown. - * - *

- * eastLon should be greater or equal westLon, otherwise IllegalArgumentException will be thrown. - * - * @param northLat Northern Latitude corner point - * @param eastLon Eastern Longitude corner point - * @param southLat Southern Latitude corner point - * @param westLon Western Longitude corner point - * @return LatLngBounds - */ - @NonNull - public LatLngBounds intersect(final double northLat, final double eastLon, - final double southLat, final double westLon) { - checkParams(northLat, eastLon, southLat, westLon); - return intersectNoParamCheck(northLat, eastLon, southLat, westLon); - } - - private LatLngBounds intersectNoParamCheck(final double northLat, final double eastLon, - final double southLat, final double westLon) { - - double minLonWest = Math.max(this.longitudeWest, westLon); - double maxLonEast = Math.min(this.longitudeEast, eastLon); - if (maxLonEast >= minLonWest) { - double minLatSouth = Math.max(this.latitudeSouth, southLat); - double maxLatNorth = Math.min(this.latitudeNorth, northLat); - if (maxLatNorth >= minLatSouth) { - return new LatLngBounds(maxLatNorth, maxLonEast, minLatSouth, minLonWest); - } - } - return null; - } - - - - /** - * Inner class responsible for recreating Parcels into objects. - */ - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - @Override - public LatLngBounds createFromParcel(@NonNull final Parcel in) { - return readFromParcel(in); - } - - @Override - public LatLngBounds[] newArray(final int size) { - return new LatLngBounds[size]; - } - }; - - /** - * Returns a hash code value for the object. - * - * @return the hash code - */ - @Override - public int hashCode() { - return (int) ((latitudeNorth + 90) - + ((latitudeSouth + 90) * 1000) - + ((longitudeEast + 180) * 1000000) - + ((longitudeWest + 180) * 1000000000)); - } - - /** - * Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. - * - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written - */ - @Override - public void writeToParcel(@NonNull final Parcel out, final int flags) { - out.writeDouble(this.latitudeNorth); - out.writeDouble(this.longitudeEast); - out.writeDouble(this.latitudeSouth); - out.writeDouble(this.longitudeWest); - } - - private static LatLngBounds readFromParcel(final Parcel in) { - final double northLat = in.readDouble(); - final double eastLon = in.readDouble(); - final double southLat = in.readDouble(); - final double westLon = in.readDouble(); - return new LatLngBounds(northLat, eastLon, southLat, westLon); - } - - /** - * Builder for composing LatLngBounds objects. - */ - public static final class Builder { - - private final List latLngList = new ArrayList<>(); - - /** - * Builds a new LatLngBounds. - *

- * Throws an {@link InvalidLatLngBoundsException} when no LatLngBounds can be created. - *

- * - * @return the build LatLngBounds - */ - public LatLngBounds build() { - if (latLngList.size() < 2) { - throw new InvalidLatLngBoundsException(latLngList.size()); - } - return LatLngBounds.fromLatLngs(latLngList); - } - - /** - * Adds a LatLng object to the LatLngBounds.Builder. - * - * @param latLngs the List of LatLng objects to be added - * @return this - */ - @NonNull - public Builder includes(@NonNull List latLngs) { - latLngList.addAll(latLngs); - return this; - } - - /** - * Adds a LatLng object to the LatLngBounds.Builder. - * - * @param latLng the LatLng to be added - * @return this - */ - @NonNull - public Builder include(@NonNull LatLng latLng) { - latLngList.add(latLng); - return this; - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngQuad.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngQuad.java deleted file mode 100644 index d17d0d6fe..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngQuad.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; - -/** - * A geographical area representing a non-aligned quadrilateral - *

- * This class does not wrap values to the world bounds - *

- */ -public class LatLngQuad implements Parcelable { - - @Keep - private final LatLng topLeft; - @Keep - private final LatLng topRight; - @Keep - private final LatLng bottomRight; - @Keep - private final LatLng bottomLeft; - - /** - * Construct a new LatLngQuad based on its corners, - * in order top left, top right, bottom left, bottom right - */ - @Keep - public LatLngQuad(final LatLng topLeft, final LatLng topRight, final LatLng bottomRight, final LatLng bottomLeft) { - this.topLeft = topLeft; - this.topRight = topRight; - this.bottomRight = bottomRight; - this.bottomLeft = bottomLeft; - } - - public LatLng getTopLeft() { - return this.topLeft; - } - - public LatLng getTopRight() { - return this.topRight; - } - - public LatLng getBottomRight() { - return this.bottomRight; - } - - public LatLng getBottomLeft() { - return this.bottomLeft; - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public LatLngQuad createFromParcel(@NonNull final Parcel in) { - return readFromParcel(in); - } - - @Override - public LatLngQuad[] newArray(final int size) { - return new LatLngQuad[size]; - } - }; - - @Override - public int hashCode() { - int code = topLeft.hashCode(); - code = (code ^ code >>> 31) + topRight.hashCode(); - code = (code ^ code >>> 31) + bottomRight.hashCode(); - code = (code ^ code >>> 31) + bottomLeft.hashCode(); - return code; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(@NonNull final Parcel out, final int arg1) { - topLeft.writeToParcel(out, arg1); - topRight.writeToParcel(out, arg1); - bottomRight.writeToParcel(out, arg1); - bottomLeft.writeToParcel(out, arg1); - } - - private static LatLngQuad readFromParcel(@NonNull final Parcel in) { - final LatLng topLeft = new LatLng(in); - final LatLng topRight = new LatLng(in); - final LatLng bottomRight = new LatLng(in); - final LatLng bottomLeft = new LatLng(in); - return new LatLngQuad(topLeft, topRight, bottomRight, bottomLeft); - } -} 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 deleted file mode 100644 index 941e6652f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/LatLngSpan.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.NonNull; - -/** - * A geographical span defined by its latitude and longitude span. - */ -public class LatLngSpan implements Parcelable { - - private double mLatitudeSpan; - private double mLongitudeSpan; - - private LatLngSpan(@NonNull Parcel in) { - mLatitudeSpan = in.readDouble(); - mLongitudeSpan = in.readDouble(); - } - - /** - * Creates a LatLgnSpan. - * - * @param latitudeSpan The span used for latitude. - * @param longitudeSpan The span used for longitude. - */ - public LatLngSpan(double latitudeSpan, double longitudeSpan) { - mLatitudeSpan = latitudeSpan; - mLongitudeSpan = longitudeSpan; - } - - /** - * Returns the latitude span. - * - * @return The latitude span. - */ - public double getLatitudeSpan() { - return mLatitudeSpan; - } - - /** - * Sets the latitude span. - * - * @param latitudeSpan The latitude span to set. - */ - public void setLatitudeSpan(double latitudeSpan) { - mLatitudeSpan = latitudeSpan; - } - - /** - * Returns to longitude span. - * - * @return The longitude span. - */ - public double getLongitudeSpan() { - return mLongitudeSpan; - } - - /** - * Sets the longitude span. - * - * @param longitudeSpan The longitude span to set. - */ - public void setLongitudeSpan(double longitudeSpan) { - mLongitudeSpan = longitudeSpan; - } - - /** - * Indicates whether some other object is "equal to" this one. - * - * @param object The object to compare - * @return True if equal, false if not - */ - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (object instanceof LatLngSpan) { - LatLngSpan other = (LatLngSpan) object; - return mLongitudeSpan == other.getLongitudeSpan() - && mLatitudeSpan == other.getLatitudeSpan(); - } - return false; - } - - /** - * Inner class responsible for recreating Parcels into objects. - */ - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - @Override - public LatLngSpan createFromParcel(@NonNull Parcel in) { - return new LatLngSpan(in); - } - - @Override - public LatLngSpan[] newArray(int size) { - return new LatLngSpan[size]; - } - }; - - /** - * Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. - * - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out Parcel in which the object should be written - * @param flags Additional flags about how the object should be written - */ - @Override - public void writeToParcel(@NonNull Parcel out, int flags) { - out.writeDouble(mLatitudeSpan); - out.writeDouble(mLongitudeSpan); - } - - /** - * Returns a hash code value for the object. - * - * @return hash code value of this - */ - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(mLatitudeSpan); - result = (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(mLongitudeSpan); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/ProjectedMeters.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/ProjectedMeters.java deleted file mode 100644 index 745a7c6be..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/ProjectedMeters.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -/** - * ProjectedMeters is a projection of longitude, latitude points in Mercator meters. - *

- * these have been projected into Mapbox GL's Mercator projection. Instead of decimal - * degrees, it uses Mercator meters (which are notably not equivalent to SI meters) - * except at the equator. - *

- */ -public class ProjectedMeters implements Parcelable { - - /** - * Inner class responsible for recreating Parcels into objects. - */ - public static final Creator CREATOR = new Creator() { - public ProjectedMeters createFromParcel(@NonNull Parcel in) { - return new ProjectedMeters(in); - } - - public ProjectedMeters[] newArray(int size) { - return new ProjectedMeters[size]; - } - }; - - private double northing; - private double easting; - - /** - * Creates a ProjectedMeters based on projected meters in north and east direction. - * - * @param northing the northing in meters - * @param easting the easting in meters - */ - @Keep - public ProjectedMeters(double northing, double easting) { - this.northing = northing; - this.easting = easting; - } - - /** - * Creates a ProjecteMeters based on another set of projected meters. - * - * @param projectedMeters The projected meters to be based on. - */ - public ProjectedMeters(ProjectedMeters projectedMeters) { - this.northing = projectedMeters.northing; - this.easting = projectedMeters.easting; - } - - /** - * Creates a ProjectedMeters from a Parcel. - * - * @param in The parcel to create from - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - private ProjectedMeters(Parcel in) { - northing = in.readDouble(); - easting = in.readDouble(); - } - - /** - * Get projected meters in north direction. - * - * @return Projected meters in north. - */ - public double getNorthing() { - return northing; - } - - /** - * Get projected meters in east direction. - * - * @return Projected meters in east. - */ - public double getEasting() { - return easting; - } - - /** - * Indicates whether some other object is "equal to" this one. - * - * @param other The object to compare this to - * @return true if equal, false if not - */ - @Override - public boolean equals(@Nullable Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - - ProjectedMeters projectedMeters = (ProjectedMeters) other; - - return Double.compare(projectedMeters.easting, easting) == 0 - && Double.compare(projectedMeters.northing, northing) == 0; - } - - /** - * Returns a hash code value for the object. - * - * @return the hash code of this - */ - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(easting); - result = (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(northing); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - return result; - } - - /** - * Returns a string representation of the object. - * - * @return the string representation of this - */ - @NonNull - @Override - public String toString() { - return "ProjectedMeters [northing=" + northing + ", easting=" + easting + "]"; - } - - /** - * Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. - * - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written - */ - @Override - public void writeToParcel(@NonNull Parcel out, int flags) { - out.writeDouble(northing); - out.writeDouble(easting); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/VisibleRegion.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/VisibleRegion.java deleted file mode 100644 index a8b4421ee..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/VisibleRegion.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.NonNull; - -/** - * Contains the four points defining the four-sided polygon that is visible in a map's camera. - * This polygon can be a trapezoid instead of a rectangle, because a camera can have tilt. - * If the camera is directly over the center of the camera, the shape is rectangular, - * but if the camera is tilted, the shape will appear to be a trapezoid whose - * smallest side is closest to the point of view. - */ -public class VisibleRegion implements Parcelable { - - /** - * LatLng object that defines the far left corner of the camera. - */ - public final LatLng farLeft; - - /** - * LatLng object that defines the far right corner of the camera. - */ - public final LatLng farRight; - - /** - * LatLng object that defines the bottom left corner of the camera. - */ - public final LatLng nearLeft; - - /** - * LatLng object that defines the bottom right corner of the camera. - */ - public final LatLng nearRight; - - /** - * The smallest bounding box that includes the visible region defined in this class. - */ - public final LatLngBounds latLngBounds; - - /** - * Creates a VisibleRegion from a Parcel. - * - * @param in The Parcel to create this from - */ - private VisibleRegion(Parcel in) { - this.farLeft = in.readParcelable(LatLng.class.getClassLoader()); - this.farRight = in.readParcelable(LatLng.class.getClassLoader()); - this.nearLeft = in.readParcelable(LatLng.class.getClassLoader()); - this.nearRight = in.readParcelable(LatLng.class.getClassLoader()); - this.latLngBounds = in.readParcelable(LatLngBounds.class.getClassLoader()); - } - - /** - * Creates a VisibleRegion given the four corners of the camera. - * - * @param farLeft A LatLng object containing the latitude and longitude of the near left corner of the region. - * @param farRight A LatLng object containing the latitude and longitude of the near left corner of the region. - * @param nearLeft A LatLng object containing the latitude and longitude of the near left corner of the region. - * @param nearRight A LatLng object containing the latitude and longitude of the near left corner of the region. - * @param latLngBounds The smallest bounding box that includes the visible region defined in this class. - */ - public VisibleRegion(LatLng farLeft, LatLng farRight, LatLng nearLeft, LatLng nearRight, LatLngBounds latLngBounds) { - this.farLeft = farLeft; - this.farRight = farRight; - this.nearLeft = nearLeft; - this.nearRight = nearRight; - this.latLngBounds = latLngBounds; - } - - /** - * Compares this VisibleRegion to another object. - * If the other object is actually a pointer to this object, - * or if all four corners and the bounds of the two objects are the same, - * this method returns true. Otherwise, this method returns false. - * - * @param o The Object to compare with. - * @return true if both objects are the same object. - */ - @Override - public boolean equals(Object o) { - if (!(o instanceof VisibleRegion)) { - return false; - } - if (o == this) { - return true; - } - - VisibleRegion visibleRegion = (VisibleRegion) o; - return farLeft.equals(visibleRegion.farLeft) - && farRight.equals(visibleRegion.farRight) - && nearLeft.equals(visibleRegion.nearLeft) - && nearRight.equals(visibleRegion.nearRight) - && latLngBounds.equals(visibleRegion.latLngBounds); - } - - /** - * The string representation of the object. - * - * @return the string representation of this - */ - @NonNull - @Override - public String toString() { - return "[farLeft [" + farLeft + "], farRight [" + farRight + "], nearLeft [" + nearLeft + "], nearRight [" - + nearRight + "], latLngBounds [" + latLngBounds + "]]"; - } - - /** - * Returns a hash code value for the object. - * - * @return the hash code - */ - @Override - public int hashCode() { - return ((farLeft.hashCode() + 90) - + ((farRight.hashCode() + 90) * 1000) - + ((nearLeft.hashCode() + 180) * 1000000) - + ((nearRight.hashCode() + 180) * 1000000000)); - } - - /** - * Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. - * - * @return a bitmask indicating the set of special object types marshaled by this Parcelable object instance. - */ - @Override - public int describeContents() { - return 0; - } - - /** - * Flatten this object in to a Parcel. - * - * @param out The Parcel in which the object should be written. - * @param flags Additional flags about how the object should be written - */ - @Override - public void writeToParcel(@NonNull Parcel out, int flags) { - out.writeParcelable(farLeft, flags); - out.writeParcelable(farRight, flags); - out.writeParcelable(nearLeft, flags); - out.writeParcelable(nearRight, flags); - out.writeParcelable(latLngBounds, flags); - } - - /** - * Inner class responsible for recreating Parcels into objects. - */ - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public VisibleRegion createFromParcel(@NonNull Parcel in) { - return new VisibleRegion(in); - } - - public VisibleRegion[] newArray(int size) { - return new VisibleRegion[size]; - } - }; - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/package-info.java deleted file mode 100644 index 754af7659..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/geometry/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Geometry API classes. - */ -package com.mapbox.mapboxsdk.geometry; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpIdentifier.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpIdentifier.java deleted file mode 100644 index 5f4f85ea7..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpIdentifier.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -import android.content.Context; -import android.content.pm.PackageInfo; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.Mapbox; - -public class HttpIdentifier { - - private HttpIdentifier() { - } - - /** - * Returns the application identifier, consisting out the package name, version name and version code. - * - * @return the application identifier - */ - public static String getIdentifier() { - return getIdentifier(Mapbox.getApplicationContext()); - } - - /** - * Returns the application identifier, consisting out the package name, version name and version code. - * - * @param context the context used to retrieve the package manager from - * @return the application identifier - */ - private static String getIdentifier(@NonNull Context context) { - try { - PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - return String.format("%s/%s (%s)", context.getPackageName(), packageInfo.versionName, packageInfo.versionCode); - } catch (Exception exception) { - MapStrictMode.strictModeViolation(exception); - return ""; - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpLogger.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpLogger.java deleted file mode 100644 index 2f44694f0..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpLogger.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -import android.util.Log; -import com.mapbox.mapboxsdk.log.Logger; - -import static com.mapbox.mapboxsdk.http.HttpRequest.CONNECTION_ERROR; -import static com.mapbox.mapboxsdk.http.HttpRequest.TEMPORARY_ERROR; - -public class HttpLogger { - - private static final String TAG = "Mbgl-HttpRequest"; - - public static boolean logRequestUrl; - public static boolean logEnabled = true; - - private HttpLogger(){ - } - - public static void logFailure(int type, String errorMessage, String requestUrl) { - log(type == TEMPORARY_ERROR ? Log.DEBUG : type == CONNECTION_ERROR ? Log.INFO : Log.WARN, - String.format( - "Request failed due to a %s error: %s %s", - type == TEMPORARY_ERROR ? "temporary" : type == CONNECTION_ERROR ? "connection" : "permanent", - errorMessage, - logRequestUrl ? requestUrl : "" - ) - ); - } - - public static void log(int type, String errorMessage) { - if (logEnabled) { - Logger.log(type, TAG, errorMessage); - } - } -} 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 deleted file mode 100644 index 1fd4f43cd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -/** - * Interface definition for performing http requests. - *

- * This allows to provide alternative implementations for the http interaction of this library. - *

- */ -public interface HttpRequest { - - int CONNECTION_ERROR = 0; - int TEMPORARY_ERROR = 1; - int PERMANENT_ERROR = 2; - - /** - * Executes the request. - * - * @param httpRequest callback to be invoked when we receive a response - * @param nativePtr the pointer associated to the request - * @param resourceUrl the resource url to download - * @param etag http header, identifier for a specific version of a resource - * @param modified http header, used to determine if a resource hasn't been modified since - * @param offlineUsage flag to indicate a resource will be used for offline, appends offline=true as a query parameter - */ - void executeRequest(HttpResponder httpRequest, long nativePtr, String resourceUrl, - String etag, String modified, boolean offlineUsage); - - /** - * Cancels the request. - */ - void cancelRequest(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpRequestUrl.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpRequestUrl.java deleted file mode 100644 index 1faf8f5e5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpRequestUrl.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.Mapbox; - -public class HttpRequestUrl { - - private HttpRequestUrl() { - } - - /** - * Adapts a resource request url based on the host, query size, and offline requirement. - * Mapbox resources downloaded for offline use are subject to separate Vector Tile and - * Raster Tile API pricing and are not included in the Maps SDK’s “unlimited” requests. - * See our pricing page for more information. - * - * @param host the host used as endpoint - * @param resourceUrl the resource to download - * @param querySize the query size of the resource request - * @param offline the type of resource, either offline or online - * @return the adapted resource url - */ - public static String buildResourceUrl(@NonNull String host, String resourceUrl, int querySize, boolean offline) { - if (isValidMapboxEndpoint(host)) { - if (querySize == 0) { - resourceUrl = resourceUrl + "?"; - } else { - resourceUrl = resourceUrl + "&"; - } - // Only add SKU token to requests not tagged as "offline" usage. - if (offline) { - resourceUrl = resourceUrl + "offline=true"; - } else { - resourceUrl = resourceUrl + "sku=" + Mapbox.getSkuToken(); - } - } - return resourceUrl; - } - - /** - * Validates if the host used as endpoint is a valid Mapbox endpoint. - * - * @param host the host used as endpoint - * @return true if a valid Mapbox endpoint - */ - private static boolean isValidMapboxEndpoint(String host) { - return host.equals("mapbox.com") - || host.endsWith(".mapbox.com") - || host.equals("mapbox.cn") - || host.endsWith(".mapbox.cn"); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpResponder.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpResponder.java deleted file mode 100644 index a050e07c5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/HttpResponder.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -/** - * Interface definition for a callback to be invoked when either a response was returned for a requested resource or - * when an error occurred when requesting the resource. - */ -public interface HttpResponder { - - /** - * Invoked when a resource has finished. - * - * @param responseCode http response code - * @param eTag http header, identifier for a specific version of a resource - * @param lastModified http header, used to determine if a resource hasn't been modified since - * @param cacheControl http header, used to determine cache strategy of a resource - * @param expires http header, used to determine when a resource is stale - * @param retryAfter http header, used to indicate when the service is expected to be unavailable to the client - * @param xRateLimitReset http header, used to determine the remaining window before the rate limit resets - * @param body http response body, in an array of bytes representation - */ - void onResponse(int responseCode, String eTag, String lastModified, String cacheControl, String expires, - String retryAfter, String xRateLimitReset, byte[] body); - - /** - * Invoked when a resource failed to be retrieved. - * - * @param type the error type, either one of {@link HttpRequest#CONNECTION_ERROR}, - * {@link HttpRequest#TEMPORARY_ERROR} or {@link HttpRequest#PERMANENT_ERROR} - * @param errorMessage the error message associated with the failure - */ - void handleFailure(int type, String errorMessage); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/LocalRequestTask.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/LocalRequestTask.java deleted file mode 100644 index 2d9fe43ad..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/LocalRequestTask.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -import android.content.res.AssetManager; -import android.os.AsyncTask; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.log.Logger; - -import java.io.IOException; -import java.io.InputStream; - -class LocalRequestTask extends AsyncTask { - - private static final String TAG = "Mbgl-LocalRequestTask"; - - private OnLocalRequestResponse requestResponse; - - LocalRequestTask(OnLocalRequestResponse requestResponse) { - this.requestResponse = requestResponse; - } - - @Nullable - @Override - protected byte[] doInBackground(String... strings) { - return loadFile(Mapbox.getApplicationContext().getAssets(), - "integration/" + strings[0] - .substring(8) - .replaceAll("%20", " ") - .replaceAll("%2c", ",")); - } - - @Override - protected void onPostExecute(@Nullable byte[] bytes) { - super.onPostExecute(bytes); - if (bytes != null && requestResponse != null) { - requestResponse.onResponse(bytes); - } - } - - @Nullable - private static byte[] loadFile(AssetManager assets, @NonNull String path) { - byte[] buffer = null; - InputStream input = null; - try { - input = assets.open(path); - int size = input.available(); - buffer = new byte[size]; - input.read(buffer); - } catch (IOException exception) { - logFileError(exception); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException exception) { - logFileError(exception); - } - } - } - return buffer; - } - - private static void logFileError(Exception exception) { - String message = "Load file failed"; - Logger.e(TAG, message, exception); - MapStrictMode.strictModeViolation(message, exception); - } - - public interface OnLocalRequestResponse { - void onResponse(byte[] bytes); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/NativeHttpRequest.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/NativeHttpRequest.java deleted file mode 100644 index e59b07dc1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/NativeHttpRequest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.mapbox.mapboxsdk.http; - -import android.support.annotation.Keep; -import android.support.annotation.Nullable; -import com.mapbox.mapboxsdk.Mapbox; - -import java.util.concurrent.locks.ReentrantLock; - -@Keep -public class NativeHttpRequest implements HttpResponder { - - private final HttpRequest httpRequest = Mapbox.getModuleProvider().createHttpRequest(); - - // Reentrancy is not needed, but "Lock" is an abstract class. - private final ReentrantLock lock = new ReentrantLock(); - - @Keep - private long nativePtr; - - @Keep - private NativeHttpRequest(long nativePtr, String resourceUrl, String etag, String modified, boolean offlineUsage) { - this.nativePtr = nativePtr; - - if (resourceUrl.startsWith("local://")) { - // used by render test to serve files from assets - executeLocalRequest(resourceUrl); - return; - } - httpRequest.executeRequest(this, nativePtr, resourceUrl, etag, modified, offlineUsage); - } - - public void cancel() { - httpRequest.cancelRequest(); - - // TODO: We need a lock here because we can try - // to cancel at the same time the request is getting - // answered on the OkHTTP thread. We could get rid of - // this lock by using Runnable when we move Android - // implementation of mbgl::RunLoop to Looper. - lock.lock(); - nativePtr = 0; - lock.unlock(); - } - - public void onResponse(int responseCode, String etag, String lastModified, String cacheControl, String expires, - String retryAfter, String xRateLimitReset, byte[] body) { - lock.lock(); - if (nativePtr != 0) { - nativeOnResponse(responseCode, - etag, - lastModified, - cacheControl, - expires, - retryAfter, - xRateLimitReset, - body); - } - lock.unlock(); - } - - private void executeLocalRequest(String resourceUrl) { - new LocalRequestTask(new LocalRequestTask.OnLocalRequestResponse() { - @Override - public void onResponse(@Nullable byte[] bytes) { - if (bytes != null) { - lock.lock(); - if (nativePtr != 0) { - NativeHttpRequest.this.nativeOnResponse(200, null, null, null, null, null, null, bytes); - } - lock.unlock(); - } - } - }).execute(resourceUrl); - } - - public void handleFailure(int type, String errorMessage) { - lock.lock(); - if (nativePtr != 0) { - nativeOnFailure(type, errorMessage); - } - lock.unlock(); - } - - @Keep - private native void nativeOnFailure(int type, String message); - - @Keep - private native void nativeOnResponse(int code, String etag, String modified, String cacheControl, String expires, - String retryAfter, String xRateLimitReset, byte[] body); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/package-info.java deleted file mode 100644 index 09eeda2b7..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/http/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Do not use this package. Internal use only. - */ -package com.mapbox.mapboxsdk.http; diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/AnimatorListenerHolder.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/AnimatorListenerHolder.java deleted file mode 100644 index 5dcf30919..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/AnimatorListenerHolder.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -class AnimatorListenerHolder { - @MapboxAnimator.Type - private final int animatorType; - private final MapboxAnimator.AnimationsValueChangeListener listener; - - AnimatorListenerHolder(@MapboxAnimator.Type int animatorType, MapboxAnimator.AnimationsValueChangeListener listener) { - this.animatorType = animatorType; - this.listener = listener; - } - - @MapboxAnimator.Type - public int getAnimatorType() { - return animatorType; - } - - public MapboxAnimator.AnimationsValueChangeListener getListener() { - return listener; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - AnimatorListenerHolder that = (AnimatorListenerHolder) o; - - if (animatorType != that.animatorType) { - return false; - } - return listener != null ? listener.equals(that.listener) : that.listener == null; - } - - @Override - public int hashCode() { - int result = animatorType; - result = 31 * result + (listener != null ? listener.hashCode() : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassEngine.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassEngine.java deleted file mode 100644 index bb7fd4972..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassEngine.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.location.modes.CameraMode; -import com.mapbox.mapboxsdk.location.modes.RenderMode; - -/** - * Interface defining the source of compass heading data that is - * consumed by the {@link LocationComponent} when in compass related - * {@link RenderMode} or - * {@link CameraMode}s. - */ -public interface CompassEngine { - - /** - * Adds a {@link CompassListener} that can be used to - * receive heading and state changes. - * - * @param compassListener to be added - */ - void addCompassListener(@NonNull CompassListener compassListener); - - /** - * Removes a {@link CompassListener} that can be used to - * receive heading and state changes. - * - * @param compassListener to be removed - */ - void removeCompassListener(@NonNull CompassListener compassListener); - - /** - * Returns the last heading value produced and pushed via - * a compass listener. - * - * @return last heading value - */ - float getLastHeading(); - - /** - * Provides the last know accuracy status from the sensor manager. - *

- * An integer value which is identical to the {@code SensorManager} class constants: - *

    - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_NO_CONTACT}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_UNRELIABLE}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_LOW}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_MEDIUM}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_HIGH}
  • - *
- * - * @return last accuracy status - */ - int getLastAccuracySensorStatus(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassListener.java deleted file mode 100644 index c44218a1d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/CompassListener.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -/** - * Callbacks related to the compass - */ -public interface CompassListener { - - /** - * Callback's invoked when a new compass update occurs. You can listen into the compass updates - * using {@link CompassEngine#addCompassListener(CompassListener)} and implementing these - * callbacks. Note that this interface is also used internally to to update the UI chevron/arrow. - * - * @param userHeading the new compass heading - */ - void onCompassChanged(float userHeading); - - /** - * This gets invoked when the compass accuracy status changes from one value to another. It - * provides an integer value which is identical to the {@code SensorManager} class constants: - *
    - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_NO_CONTACT}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_UNRELIABLE}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_LOW}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_MEDIUM}
  • - *
  • {@link android.hardware.SensorManager#SENSOR_STATUS_ACCURACY_HIGH}
  • - *
- * - * @param compassStatus the new accuracy of this sensor, one of - * {@code SensorManager.SENSOR_STATUS_*} - */ - void onCompassAccuracyChange(int compassStatus); -} - diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LatLngEvaluator.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LatLngEvaluator.java deleted file mode 100644 index c631b1b75..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LatLngEvaluator.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.TypeEvaluator; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.geometry.LatLng; - -class LatLngEvaluator implements TypeEvaluator { - - private final LatLng latLng = new LatLng(); - - @NonNull - @Override - public LatLng evaluate(float fraction, @NonNull LatLng startValue, @NonNull LatLng endValue) { - latLng.setLatitude(startValue.getLatitude() - + ((endValue.getLatitude() - startValue.getLatitude()) * fraction)); - latLng.setLongitude(startValue.getLongitude() - + ((endValue.getLongitude() - startValue.getLongitude()) * fraction)); - return latLng; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerBitmapProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerBitmapProvider.java deleted file mode 100644 index 14a1b49dc..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerBitmapProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.support.annotation.ColorInt; -import android.support.annotation.DrawableRes; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.utils.BitmapUtils; - -import static com.mapbox.mapboxsdk.location.Utils.generateShadow; - -class LayerBitmapProvider { - - private final Context context; - - LayerBitmapProvider(Context context) { - this.context = context; - } - - Bitmap generateBitmap(@DrawableRes int drawableRes, @ColorInt Integer tintColor) { - Drawable drawable = BitmapUtils.getDrawableFromRes(context, drawableRes, tintColor); - return BitmapUtils.getBitmapFromDrawable(drawable); - } - - Bitmap generateShadowBitmap(@NonNull LocationComponentOptions options) { - Drawable shadowDrawable = BitmapUtils.getDrawableFromRes(context, R.drawable.mapbox_user_icon_shadow); - return generateShadow(shadowDrawable, options.elevation()); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerFeatureProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerFeatureProvider.java deleted file mode 100644 index faa83ea0e..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerFeatureProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.geojson.Feature; -import com.mapbox.geojson.Point; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_LOCATION_STALE; - -class LayerFeatureProvider { - - @NonNull - Feature generateLocationFeature(@Nullable Feature locationFeature, @NonNull LocationComponentOptions options) { - if (locationFeature != null) { - return locationFeature; - } - locationFeature = Feature.fromGeometry(Point.fromLngLat(0.0, 0.0)); - locationFeature.addNumberProperty(PROPERTY_GPS_BEARING, 0f); - locationFeature.addNumberProperty(PROPERTY_COMPASS_BEARING, 0f); - locationFeature.addBooleanProperty(PROPERTY_LOCATION_STALE, options.enableStaleState()); - return locationFeature; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerSourceProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerSourceProvider.java deleted file mode 100644 index cac513c2f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LayerSourceProvider.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.support.annotation.NonNull; -import com.mapbox.geojson.Feature; -import com.mapbox.mapboxsdk.style.layers.CircleLayer; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.layers.Property; -import com.mapbox.mapboxsdk.style.layers.SymbolLayer; -import com.mapbox.mapboxsdk.style.sources.GeoJsonOptions; -import com.mapbox.mapboxsdk.style.sources.GeoJsonSource; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.ACCURACY_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.LOCATION_SOURCE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_ALPHA; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_COLOR; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_RADIUS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BACKGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BACKGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BEARING_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_LOCATION_STALE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_SHADOW_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_LAYER; -import static com.mapbox.mapboxsdk.style.expressions.Expression.get; -import static com.mapbox.mapboxsdk.style.expressions.Expression.literal; -import static com.mapbox.mapboxsdk.style.expressions.Expression.match; -import static com.mapbox.mapboxsdk.style.expressions.Expression.stop; -import static com.mapbox.mapboxsdk.style.expressions.Expression.switchCase; -import static com.mapbox.mapboxsdk.style.layers.Property.ICON_ROTATION_ALIGNMENT_MAP; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleOpacity; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circlePitchAlignment; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleStrokeColor; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconOffset; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconRotate; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconRotationAlignment; - -class LayerSourceProvider { - - private static final String EMPTY_STRING = ""; - - @NonNull - GeoJsonSource generateSource(Feature locationFeature) { - return new GeoJsonSource( - LOCATION_SOURCE, - locationFeature, - new GeoJsonOptions().withMaxZoom(16) - ); - } - - @NonNull - Layer generateLayer(@NonNull String layerId) { - SymbolLayer layer = new SymbolLayer(layerId, LOCATION_SOURCE); - layer.setProperties( - iconAllowOverlap(true), - iconIgnorePlacement(true), - iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP), - iconRotate( - match(literal(layerId), literal(0f), - stop(FOREGROUND_LAYER, get(PROPERTY_GPS_BEARING)), - stop(BACKGROUND_LAYER, get(PROPERTY_GPS_BEARING)), - stop(SHADOW_LAYER, get(PROPERTY_GPS_BEARING)), - stop(BEARING_LAYER, get(PROPERTY_COMPASS_BEARING)) - ) - ), - iconImage( - match(literal(layerId), literal(EMPTY_STRING), - stop(FOREGROUND_LAYER, switchCase( - get(PROPERTY_LOCATION_STALE), get(PROPERTY_FOREGROUND_STALE_ICON), - get(PROPERTY_FOREGROUND_ICON))), - stop(BACKGROUND_LAYER, switchCase( - get(PROPERTY_LOCATION_STALE), get(PROPERTY_BACKGROUND_STALE_ICON), - get(PROPERTY_BACKGROUND_ICON))), - stop(SHADOW_LAYER, literal(SHADOW_ICON)), - stop(BEARING_LAYER, get(PROPERTY_BEARING_ICON)) - ) - ), - iconOffset( - match(literal(layerId), literal(new Float[] {0f, 0f}), - stop(literal(FOREGROUND_LAYER), get(PROPERTY_FOREGROUND_ICON_OFFSET)), - stop(literal(SHADOW_LAYER), get(PROPERTY_SHADOW_ICON_OFFSET)) - ) - ) - ); - return layer; - } - - @NonNull - Layer generateAccuracyLayer() { - return new CircleLayer(ACCURACY_LAYER, LOCATION_SOURCE) - .withProperties( - circleRadius(get(PROPERTY_ACCURACY_RADIUS)), - circleColor(get(PROPERTY_ACCURACY_COLOR)), - circleOpacity(get(PROPERTY_ACCURACY_ALPHA)), - circleStrokeColor(get(PROPERTY_ACCURACY_COLOR)), - circlePitchAlignment(Property.CIRCLE_PITCH_ALIGNMENT_MAP) - ); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinator.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinator.java deleted file mode 100644 index 5aad038a2..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinator.java +++ /dev/null @@ -1,422 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.Animator; -import android.location.Location; -import android.os.SystemClock; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.VisibleForTesting; -import android.util.SparseArray; -import android.view.animation.LinearInterpolator; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.ACCURACY_RADIUS_ANIMATION_DURATION; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.COMPASS_UPDATE_RATE_MS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.MAX_ANIMATION_DURATION_MS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_LATLNG; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_ACCURACY; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_LATLNG; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_TILT; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_ZOOM; -import static com.mapbox.mapboxsdk.location.Utils.immediateAnimation; - -final class LocationAnimatorCoordinator { - - private static final String TAG = "Mbgl-LocationAnimatorCoordinator"; - - @VisibleForTesting - final SparseArray animatorArray = new SparseArray<>(); - - private final Projection projection; - private Location previousLocation; - private float previousAccuracyRadius = -1; - private float previousCompassBearing = -1; - private long locationUpdateTimestamp = -1; - private float durationMultiplier; - private final MapboxAnimatorProvider animatorProvider; - private final MapboxAnimatorSetProvider animatorSetProvider; - private boolean compassAnimationEnabled; - private boolean accuracyAnimationEnabled; - - @VisibleForTesting - int maxAnimationFps = Integer.MAX_VALUE; - - @VisibleForTesting - final SparseArray listeners = new SparseArray<>(); - - LocationAnimatorCoordinator(@NonNull Projection projection, @NonNull MapboxAnimatorSetProvider animatorSetProvider, - @NonNull MapboxAnimatorProvider animatorProvider) { - this.projection = projection; - this.animatorProvider = animatorProvider; - this.animatorSetProvider = animatorSetProvider; - } - - void updateAnimatorListenerHolders(@NonNull Set listenerHolders) { - listeners.clear(); - for (AnimatorListenerHolder holder : listenerHolders) { - listeners.append(holder.getAnimatorType(), holder.getListener()); - } - } - - void feedNewLocation(@NonNull Location newLocation, @NonNull CameraPosition currentCameraPosition, - boolean isGpsNorth) { - if (previousLocation == null) { - previousLocation = newLocation; - locationUpdateTimestamp = SystemClock.elapsedRealtime() - TRANSITION_ANIMATION_DURATION_MS; - } - - LatLng previousLayerLatLng = getPreviousLayerLatLng(); - float previousLayerBearing = getPreviousLayerGpsBearing(); - LatLng previousCameraLatLng = currentCameraPosition.target; - float previousCameraBearing = (float) currentCameraPosition.bearing; - - LatLng targetLatLng = new LatLng(newLocation); - float targetLayerBearing = newLocation.getBearing(); - float targetCameraBearing = newLocation.getBearing(); - targetCameraBearing = checkGpsNorth(isGpsNorth, targetCameraBearing); - - updateLayerAnimators(previousLayerLatLng, targetLatLng, previousLayerBearing, targetLayerBearing); - updateCameraAnimators(previousCameraLatLng, previousCameraBearing, targetLatLng, targetCameraBearing); - - boolean snap = immediateAnimation(projection, previousCameraLatLng, targetLatLng) - || immediateAnimation(projection, previousLayerLatLng, targetLatLng); - - long animationDuration = 0; - if (!snap) { - long previousUpdateTimeStamp = locationUpdateTimestamp; - locationUpdateTimestamp = SystemClock.elapsedRealtime(); - - if (previousUpdateTimeStamp == 0) { - animationDuration = 0; - } else { - animationDuration = (long) ((locationUpdateTimestamp - previousUpdateTimeStamp) * durationMultiplier) - /* make animation slightly longer with durationMultiplier, defaults to 1.1f */; - } - - animationDuration = Math.min(animationDuration, MAX_ANIMATION_DURATION_MS); - } - - playAnimators(animationDuration, - ANIMATOR_LAYER_LATLNG, - ANIMATOR_LAYER_GPS_BEARING, - ANIMATOR_CAMERA_LATLNG, - ANIMATOR_CAMERA_GPS_BEARING); - - previousLocation = newLocation; - } - - void feedNewCompassBearing(float targetCompassBearing, @NonNull CameraPosition currentCameraPosition) { - if (previousCompassBearing < 0) { - previousCompassBearing = targetCompassBearing; - } - - float previousLayerBearing = getPreviousLayerCompassBearing(); - float previousCameraBearing = (float) currentCameraPosition.bearing; - - updateCompassAnimators(targetCompassBearing, previousLayerBearing, previousCameraBearing); - playAnimators( - compassAnimationEnabled ? COMPASS_UPDATE_RATE_MS : 0, - ANIMATOR_LAYER_COMPASS_BEARING, - ANIMATOR_CAMERA_COMPASS_BEARING); - - previousCompassBearing = targetCompassBearing; - } - - void feedNewAccuracyRadius(float targetAccuracyRadius, boolean noAnimation) { - if (previousAccuracyRadius < 0) { - previousAccuracyRadius = targetAccuracyRadius; - } - - float previousAccuracyRadius = getPreviousAccuracyRadius(); - updateAccuracyAnimators(targetAccuracyRadius, previousAccuracyRadius); - playAnimators( - noAnimation || !accuracyAnimationEnabled ? 0 : ACCURACY_RADIUS_ANIMATION_DURATION, - ANIMATOR_LAYER_ACCURACY); - - this.previousAccuracyRadius = targetAccuracyRadius; - } - - void feedNewZoomLevel(double targetZoomLevel, @NonNull CameraPosition currentCameraPosition, long animationDuration, - @Nullable MapboxMap.CancelableCallback callback) { - updateZoomAnimator((float) targetZoomLevel, (float) currentCameraPosition.zoom, callback); - playAnimators(animationDuration, ANIMATOR_ZOOM); - } - - void feedNewTilt(double targetTilt, @NonNull CameraPosition currentCameraPosition, long animationDuration, - @Nullable MapboxMap.CancelableCallback callback) { - updateTiltAnimator((float) targetTilt, (float) currentCameraPosition.tilt, callback); - playAnimators(animationDuration, ANIMATOR_TILT); - } - - private LatLng getPreviousLayerLatLng() { - LatLng previousLatLng; - MapboxAnimator latLngAnimator = animatorArray.get(ANIMATOR_LAYER_LATLNG); - if (latLngAnimator != null) { - previousLatLng = (LatLng) latLngAnimator.getAnimatedValue(); - } else { - previousLatLng = new LatLng(previousLocation); - } - return previousLatLng; - } - - private float getPreviousLayerGpsBearing() { - MapboxFloatAnimator animator = (MapboxFloatAnimator) animatorArray.get(ANIMATOR_LAYER_GPS_BEARING); - float previousBearing; - if (animator != null) { - previousBearing = (float) animator.getAnimatedValue(); - } else { - previousBearing = previousLocation.getBearing(); - } - return previousBearing; - } - - private float getPreviousLayerCompassBearing() { - MapboxFloatAnimator animator = (MapboxFloatAnimator) animatorArray.get(ANIMATOR_LAYER_COMPASS_BEARING); - - float previousBearing; - if (animator != null) { - previousBearing = (float) animator.getAnimatedValue(); - } else { - previousBearing = previousCompassBearing; - } - return previousBearing; - } - - private float getPreviousAccuracyRadius() { - MapboxAnimator animator = animatorArray.get(ANIMATOR_LAYER_ACCURACY); - float previousRadius; - if (animator != null) { - previousRadius = (float) animator.getAnimatedValue(); - } else { - previousRadius = previousAccuracyRadius; - } - return previousRadius; - } - - private void updateLayerAnimators(LatLng previousLatLng, LatLng targetLatLng, - float previousBearing, float targetBearing) { - createNewLatLngAnimator(ANIMATOR_LAYER_LATLNG, previousLatLng, targetLatLng); - - // Because Location bearing values are normalized to [0, 360] - // we need to do the same for the previous bearing value to determine the shortest path - previousBearing = Utils.normalize(previousBearing); - float normalizedLayerBearing = Utils.shortestRotation(targetBearing, previousBearing); - createNewFloatAnimator(ANIMATOR_LAYER_GPS_BEARING, previousBearing, normalizedLayerBearing); - } - - private void updateCameraAnimators(LatLng previousCameraLatLng, float previousCameraBearing, - LatLng targetLatLng, float targetBearing) { - createNewLatLngAnimator(ANIMATOR_CAMERA_LATLNG, previousCameraLatLng, targetLatLng); - - float normalizedCameraBearing = Utils.shortestRotation(targetBearing, previousCameraBearing); - createNewFloatAnimator(ANIMATOR_CAMERA_GPS_BEARING, previousCameraBearing, normalizedCameraBearing); - } - - private void updateCompassAnimators(float targetCompassBearing, float previousLayerBearing, - float previousCameraBearing) { - float normalizedLayerBearing = Utils.shortestRotation(targetCompassBearing, previousLayerBearing); - createNewFloatAnimator(ANIMATOR_LAYER_COMPASS_BEARING, previousLayerBearing, normalizedLayerBearing); - - float normalizedCameraBearing = Utils.shortestRotation(targetCompassBearing, previousCameraBearing); - createNewFloatAnimator(ANIMATOR_CAMERA_COMPASS_BEARING, previousCameraBearing, normalizedCameraBearing); - } - - private void updateAccuracyAnimators(float targetAccuracyRadius, float previousAccuracyRadius) { - createNewFloatAnimator(ANIMATOR_LAYER_ACCURACY, previousAccuracyRadius, targetAccuracyRadius); - } - - private void updateZoomAnimator(float targetZoomLevel, float previousZoomLevel, - @Nullable MapboxMap.CancelableCallback cancelableCallback) { - createNewCameraAdapterAnimator(ANIMATOR_ZOOM, previousZoomLevel, targetZoomLevel, cancelableCallback); - } - - private void updateTiltAnimator(float targetTilt, float previousTiltLevel, - @Nullable MapboxMap.CancelableCallback cancelableCallback) { - createNewCameraAdapterAnimator(ANIMATOR_TILT, previousTiltLevel, targetTilt, cancelableCallback); - } - - private void createNewLatLngAnimator(@MapboxAnimator.Type int animatorType, LatLng previous, LatLng target) { - cancelAnimator(animatorType); - MapboxAnimator.AnimationsValueChangeListener listener = listeners.get(animatorType); - if (listener != null) { - animatorArray.put(animatorType, animatorProvider.latLngAnimator(previous, target, listener, maxAnimationFps)); - } - } - - private void createNewFloatAnimator(@MapboxAnimator.Type int animatorType, float previous, float target) { - cancelAnimator(animatorType); - MapboxAnimator.AnimationsValueChangeListener listener = listeners.get(animatorType); - if (listener != null) { - animatorArray.put(animatorType, animatorProvider.floatAnimator(previous, target, listener, maxAnimationFps)); - } - } - - private void createNewCameraAdapterAnimator(@MapboxAnimator.Type int animatorType, float previous, float target, - @Nullable MapboxMap.CancelableCallback cancelableCallback) { - cancelAnimator(animatorType); - MapboxAnimator.AnimationsValueChangeListener listener = listeners.get(animatorType); - if (listener != null) { - animatorArray.put(animatorType, animatorProvider.cameraAnimator(previous, target, listener, cancelableCallback)); - } - } - - private float checkGpsNorth(boolean isGpsNorth, float targetCameraBearing) { - if (isGpsNorth) { - targetCameraBearing = 0; - } - return targetCameraBearing; - } - - private void playAnimators(long duration, @MapboxAnimator.Type int... animatorTypes) { - List animators = new ArrayList<>(); - for (@MapboxAnimator.Type int animatorType : animatorTypes) { - Animator animator = animatorArray.get(animatorType); - if (animator != null) { - animators.add(animator); - } - } - animatorSetProvider.startAnimation(animators, new LinearInterpolator(), duration); - } - - void resetAllCameraAnimations(@NonNull CameraPosition currentCameraPosition, boolean isGpsNorth) { - resetCameraCompassAnimation(currentCameraPosition); - boolean snap = resetCameraLocationAnimations(currentCameraPosition, isGpsNorth); - playAnimators( - snap ? 0 : TRANSITION_ANIMATION_DURATION_MS, - ANIMATOR_CAMERA_LATLNG, - ANIMATOR_CAMERA_GPS_BEARING); - } - - private boolean resetCameraLocationAnimations(@NonNull CameraPosition currentCameraPosition, boolean isGpsNorth) { - resetCameraGpsBearingAnimation(currentCameraPosition, isGpsNorth); - return resetCameraLatLngAnimation(currentCameraPosition); - } - - private boolean resetCameraLatLngAnimation(@NonNull CameraPosition currentCameraPosition) { - MapboxLatLngAnimator animator = (MapboxLatLngAnimator) animatorArray.get(ANIMATOR_CAMERA_LATLNG); - if (animator == null) { - return false; - } - - LatLng currentTarget = animator.getTarget(); - LatLng previousCameraTarget = currentCameraPosition.target; - createNewLatLngAnimator(ANIMATOR_CAMERA_LATLNG, previousCameraTarget, currentTarget); - - return immediateAnimation(projection, previousCameraTarget, currentTarget); - } - - private void resetCameraGpsBearingAnimation(@NonNull CameraPosition currentCameraPosition, boolean isGpsNorth) { - MapboxFloatAnimator animator = (MapboxFloatAnimator) animatorArray.get(ANIMATOR_CAMERA_GPS_BEARING); - if (animator == null) { - return; - } - - float currentTargetBearing = animator.getTarget(); - currentTargetBearing = checkGpsNorth(isGpsNorth, currentTargetBearing); - float previousCameraBearing = (float) currentCameraPosition.bearing; - float normalizedCameraBearing = Utils.shortestRotation(currentTargetBearing, previousCameraBearing); - createNewFloatAnimator(ANIMATOR_CAMERA_GPS_BEARING, previousCameraBearing, normalizedCameraBearing); - } - - private void resetCameraCompassAnimation(@NonNull CameraPosition currentCameraPosition) { - MapboxFloatAnimator animator = - (MapboxFloatAnimator) animatorArray.get(ANIMATOR_CAMERA_COMPASS_BEARING); - if (animator == null) { - return; - } - - float currentTargetBearing = animator.getTarget(); - float previousCameraBearing = (float) currentCameraPosition.bearing; - float normalizedCameraBearing = Utils.shortestRotation(currentTargetBearing, previousCameraBearing); - createNewFloatAnimator(ANIMATOR_CAMERA_COMPASS_BEARING, previousCameraBearing, normalizedCameraBearing); - } - - void resetAllLayerAnimations() { - MapboxLatLngAnimator latLngAnimator = (MapboxLatLngAnimator) animatorArray.get(ANIMATOR_LAYER_LATLNG); - MapboxFloatAnimator gpsBearingAnimator = (MapboxFloatAnimator) animatorArray.get(ANIMATOR_LAYER_GPS_BEARING); - MapboxFloatAnimator compassBearingAnimator = - (MapboxFloatAnimator) animatorArray.get(ANIMATOR_LAYER_COMPASS_BEARING); - - if (latLngAnimator != null && gpsBearingAnimator != null) { - LatLng currentLatLng = (LatLng) latLngAnimator.getAnimatedValue(); - LatLng currentLatLngTarget = latLngAnimator.getTarget(); - createNewLatLngAnimator(ANIMATOR_LAYER_LATLNG, currentLatLng, currentLatLngTarget); - - float currentGpsBearing = (float) gpsBearingAnimator.getAnimatedValue(); - float currentGpsBearingTarget = gpsBearingAnimator.getTarget(); - createNewFloatAnimator(ANIMATOR_LAYER_GPS_BEARING, currentGpsBearing, currentGpsBearingTarget); - - long duration = latLngAnimator.getDuration() - latLngAnimator.getCurrentPlayTime(); - - playAnimators(duration, ANIMATOR_LAYER_LATLNG, ANIMATOR_LAYER_GPS_BEARING); - } - - if (compassBearingAnimator != null) { - float currentLayerBearing = getPreviousLayerCompassBearing(); - float currentLayerBearingTarget = compassBearingAnimator.getTarget(); - createNewFloatAnimator(ANIMATOR_LAYER_COMPASS_BEARING, currentLayerBearing, currentLayerBearingTarget); - playAnimators( - compassAnimationEnabled ? COMPASS_UPDATE_RATE_MS : 0, - ANIMATOR_LAYER_COMPASS_BEARING); - } - } - - void cancelZoomAnimation() { - cancelAnimator(ANIMATOR_ZOOM); - } - - void cancelTiltAnimation() { - cancelAnimator(ANIMATOR_TILT); - } - - void cancelAllAnimations() { - for (int i = 0; i < animatorArray.size(); i++) { - @MapboxAnimator.Type int animatorType = animatorArray.keyAt(i); - cancelAnimator(animatorType); - } - } - - private void cancelAnimator(@MapboxAnimator.Type int animatorType) { - MapboxAnimator animator = animatorArray.get(animatorType); - if (animator != null) { - animator.cancel(); - animator.removeAllUpdateListeners(); - animator.removeAllListeners(); - animatorArray.put(animatorType, null); - } - } - - void setTrackingAnimationDurationMultiplier(float trackingAnimationDurationMultiplier) { - this.durationMultiplier = trackingAnimationDurationMultiplier; - } - - void setCompassAnimationEnabled(boolean compassAnimationEnabled) { - this.compassAnimationEnabled = compassAnimationEnabled; - } - - void setAccuracyAnimationEnabled(boolean accuracyAnimationEnabled) { - this.accuracyAnimationEnabled = accuracyAnimationEnabled; - } - - void setMaxAnimationFps(int maxAnimationFps) { - if (maxAnimationFps <= 0) { - Logger.e(TAG, "Max animation FPS cannot be less or equal to 0."); - return; - } - this.maxAnimationFps = maxAnimationFps; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationCameraController.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationCameraController.java deleted file mode 100644 index 79d2e02bf..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationCameraController.java +++ /dev/null @@ -1,437 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.graphics.PointF; -import android.location.Location; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.VisibleForTesting; -import android.view.MotionEvent; - -import com.mapbox.android.gestures.AndroidGesturesManager; -import com.mapbox.android.gestures.MoveGestureDetector; -import com.mapbox.android.gestures.RotateGestureDetector; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.camera.CameraUpdate; -import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.location.modes.CameraMode; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Transform; - -import java.util.HashSet; -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS; - -final class LocationCameraController { - - @CameraMode.Mode - private int cameraMode; - - private final MapboxMap mapboxMap; - private final Transform transform; - private final OnCameraTrackingChangedListener internalCameraTrackingChangedListener; - private LocationComponentOptions options; - private boolean adjustFocalPoint; - - private final MoveGestureDetector moveGestureDetector; - private final OnCameraMoveInvalidateListener onCameraMoveInvalidateListener; - - private final AndroidGesturesManager initialGesturesManager; - private final AndroidGesturesManager internalGesturesManager; - - private boolean isTransitioning; - - LocationCameraController( - Context context, - MapboxMap mapboxMap, - Transform transform, - OnCameraTrackingChangedListener internalCameraTrackingChangedListener, - @NonNull LocationComponentOptions options, - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener) { - this.mapboxMap = mapboxMap; - this.transform = transform; - - initialGesturesManager = mapboxMap.getGesturesManager(); - internalGesturesManager = new LocationGesturesManager(context); - moveGestureDetector = internalGesturesManager.getMoveGestureDetector(); - mapboxMap.addOnRotateListener(onRotateListener); - mapboxMap.addOnFlingListener(onFlingListener); - mapboxMap.addOnMoveListener(onMoveListener); - - this.internalCameraTrackingChangedListener = internalCameraTrackingChangedListener; - this.onCameraMoveInvalidateListener = onCameraMoveInvalidateListener; - initializeOptions(options); - } - - // Package private for testing purposes - LocationCameraController(MapboxMap mapboxMap, - Transform transform, - MoveGestureDetector moveGestureDetector, - OnCameraTrackingChangedListener internalCameraTrackingChangedListener, - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener, - AndroidGesturesManager initialGesturesManager, - AndroidGesturesManager internalGesturesManager) { - this.mapboxMap = mapboxMap; - this.transform = transform; - this.moveGestureDetector = moveGestureDetector; - this.internalCameraTrackingChangedListener = internalCameraTrackingChangedListener; - this.onCameraMoveInvalidateListener = onCameraMoveInvalidateListener; - this.internalGesturesManager = internalGesturesManager; - this.initialGesturesManager = initialGesturesManager; - } - - void initializeOptions(LocationComponentOptions options) { - this.options = options; - if (options.trackingGesturesManagement()) { - if (mapboxMap.getGesturesManager() != internalGesturesManager) { - mapboxMap.setGesturesManager(internalGesturesManager, true, true); - } - adjustGesturesThresholds(); - } else if (mapboxMap.getGesturesManager() != initialGesturesManager) { - mapboxMap.setGesturesManager(initialGesturesManager, true, true); - } - } - - void setCameraMode(@CameraMode.Mode int cameraMode) { - setCameraMode(cameraMode, null, TRANSITION_ANIMATION_DURATION_MS, null, null, null, null); - } - - void setCameraMode(@CameraMode.Mode final int cameraMode, @Nullable Location lastLocation, - long transitionDuration, - @Nullable Double zoom, @Nullable Double bearing, @Nullable Double tilt, - @Nullable OnLocationCameraTransitionListener internalTransitionListener) { - if (this.cameraMode == cameraMode) { - return; - } - - final boolean wasTracking = isLocationTracking(); - this.cameraMode = cameraMode; - - if (cameraMode != CameraMode.NONE) { - mapboxMap.cancelTransitions(); - } - - adjustGesturesThresholds(); - notifyCameraTrackingChangeListener(wasTracking); - transitionToCurrentLocation( - wasTracking, lastLocation, transitionDuration, zoom, bearing, tilt, internalTransitionListener); - } - - /** - * Initiates a camera animation to the current location if location tracking was engaged. - * Notifies an internal listener when the transition's finished to invalidate animators and notify external listeners. - */ - private void transitionToCurrentLocation(boolean wasTracking, Location lastLocation, - long transitionDuration, - Double zoom, Double bearing, Double tilt, - final OnLocationCameraTransitionListener internalTransitionListener) { - if (!wasTracking && isLocationTracking() && lastLocation != null) { - isTransitioning = true; - LatLng target = new LatLng(lastLocation); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(target); - if (zoom != null) { - builder.zoom(zoom); - } - if (tilt != null) { - builder.tilt(tilt); - } - if (bearing != null) { - builder.bearing(bearing); - } else { - if (isLocationBearingTracking()) { - builder.bearing(cameraMode == CameraMode.TRACKING_GPS_NORTH ? 0 : lastLocation.getBearing()); - } - } - - CameraUpdate update = CameraUpdateFactory.newCameraPosition(builder.build()); - MapboxMap.CancelableCallback callback = new MapboxMap.CancelableCallback() { - @Override - public void onCancel() { - isTransitioning = false; - if (internalTransitionListener != null) { - internalTransitionListener.onLocationCameraTransitionCanceled(cameraMode); - } - } - - @Override - public void onFinish() { - isTransitioning = false; - if (internalTransitionListener != null) { - internalTransitionListener.onLocationCameraTransitionFinished(cameraMode); - } - } - }; - - CameraPosition currentPosition = mapboxMap.getCameraPosition(); - if (Utils.immediateAnimation(mapboxMap.getProjection(), currentPosition.target, target)) { - transform.moveCamera( - mapboxMap, - update, - callback); - } else { - transform.animateCamera( - mapboxMap, - update, - (int) transitionDuration, - callback); - } - } else { - if (internalTransitionListener != null) { - internalTransitionListener.onLocationCameraTransitionFinished(cameraMode); - } - } - } - - int getCameraMode() { - return cameraMode; - } - - private void setBearing(float bearing) { - if (isTransitioning) { - return; - } - - transform.moveCamera(mapboxMap, CameraUpdateFactory.bearingTo(bearing), null); - onCameraMoveInvalidateListener.onInvalidateCameraMove(); - } - - private void setLatLng(@NonNull LatLng latLng) { - if (isTransitioning) { - return; - } - - transform.moveCamera(mapboxMap, CameraUpdateFactory.newLatLng(latLng), null); - onCameraMoveInvalidateListener.onInvalidateCameraMove(); - - if (adjustFocalPoint) { - PointF focalPoint = mapboxMap.getProjection().toScreenLocation(latLng); - mapboxMap.getUiSettings().setFocalPoint(focalPoint); - adjustFocalPoint = false; - } - } - - private void setZoom(float zoom) { - if (isTransitioning) { - return; - } - - transform.moveCamera(mapboxMap, CameraUpdateFactory.zoomTo(zoom), null); - onCameraMoveInvalidateListener.onInvalidateCameraMove(); - } - - private void setTilt(float tilt) { - if (isTransitioning) { - return; - } - - transform.moveCamera(mapboxMap, CameraUpdateFactory.tiltTo(tilt), null); - onCameraMoveInvalidateListener.onInvalidateCameraMove(); - } - - private final MapboxAnimator.AnimationsValueChangeListener latLngValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(LatLng value) { - setLatLng(value); - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener gpsBearingValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - boolean trackingNorth = cameraMode == CameraMode.TRACKING_GPS_NORTH - && mapboxMap.getCameraPosition().bearing == 0; - - if (!trackingNorth) { - setBearing(value); - } - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener compassBearingValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - if (cameraMode == CameraMode.TRACKING_COMPASS - || cameraMode == CameraMode.NONE_COMPASS) { - setBearing(value); - } - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener zoomValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - setZoom(value); - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener tiltValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - setTilt(value); - } - }; - - Set getAnimationListeners() { - Set holders = new HashSet<>(); - if (isLocationTracking()) { - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_CAMERA_LATLNG, latLngValueListener)); - } - - if (isLocationBearingTracking()) { - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING, gpsBearingValueListener)); - } - - if (isConsumingCompass()) { - holders.add(new AnimatorListenerHolder( - MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING, - compassBearingValueListener)); - } - - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_ZOOM, zoomValueListener)); - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_TILT, tiltValueListener)); - return holders; - } - - boolean isTransitioning() { - return isTransitioning; - } - - private void adjustGesturesThresholds() { - if (options.trackingGesturesManagement()) { - if (isLocationTracking()) { - adjustFocalPoint = true; - moveGestureDetector.setMoveThreshold(options.trackingInitialMoveThreshold()); - } else { - moveGestureDetector.setMoveThreshold(0f); - } - } - } - - boolean isConsumingCompass() { - return cameraMode == CameraMode.TRACKING_COMPASS - || cameraMode == CameraMode.NONE_COMPASS; - } - - private boolean isLocationTracking() { - return cameraMode == CameraMode.TRACKING - || cameraMode == CameraMode.TRACKING_COMPASS - || cameraMode == CameraMode.TRACKING_GPS - || cameraMode == CameraMode.TRACKING_GPS_NORTH; - } - - private boolean isBearingTracking() { - return cameraMode == CameraMode.NONE_COMPASS - || cameraMode == CameraMode.TRACKING_COMPASS - || cameraMode == CameraMode.NONE_GPS - || cameraMode == CameraMode.TRACKING_GPS - || cameraMode == CameraMode.TRACKING_GPS_NORTH; - } - - private boolean isLocationBearingTracking() { - return cameraMode == CameraMode.TRACKING_GPS - || cameraMode == CameraMode.TRACKING_GPS_NORTH - || cameraMode == CameraMode.NONE_GPS; - } - - private void notifyCameraTrackingChangeListener(boolean wasTracking) { - internalCameraTrackingChangedListener.onCameraTrackingChanged(cameraMode); - if (wasTracking && !isLocationTracking()) { - mapboxMap.getUiSettings().setFocalPoint(null); - internalCameraTrackingChangedListener.onCameraTrackingDismissed(); - } - } - - @NonNull - @VisibleForTesting - MapboxMap.OnMoveListener onMoveListener = new MapboxMap.OnMoveListener() { - private boolean interrupt; - - @Override - public void onMoveBegin(@NonNull MoveGestureDetector detector) { - if (options.trackingGesturesManagement() - && detector.getPointersCount() > 1 - && detector.getMoveThreshold() != options.trackingMultiFingerMoveThreshold() - && isLocationTracking()) { - detector.setMoveThreshold(options.trackingMultiFingerMoveThreshold()); - interrupt = true; - } else { - setCameraMode(CameraMode.NONE); - } - } - - @Override - public void onMove(@NonNull MoveGestureDetector detector) { - if (interrupt) { - detector.interrupt(); - return; - } - - if (isLocationTracking() || isBearingTracking()) { - setCameraMode(CameraMode.NONE); - detector.interrupt(); - } - } - - @Override - public void onMoveEnd(@NonNull MoveGestureDetector detector) { - if (options.trackingGesturesManagement() && !interrupt && isLocationTracking()) { - detector.setMoveThreshold(options.trackingInitialMoveThreshold()); - } - interrupt = false; - } - }; - - @NonNull - private MapboxMap.OnRotateListener onRotateListener = new MapboxMap.OnRotateListener() { - @Override - public void onRotateBegin(@NonNull RotateGestureDetector detector) { - if (isBearingTracking()) { - setCameraMode(CameraMode.NONE); - } - } - - @Override - public void onRotate(@NonNull RotateGestureDetector detector) { - // no implementation - } - - @Override - public void onRotateEnd(@NonNull RotateGestureDetector detector) { - // no implementation - } - }; - - @NonNull - private MapboxMap.OnFlingListener onFlingListener = new MapboxMap.OnFlingListener() { - @Override - public void onFling() { - setCameraMode(CameraMode.NONE); - } - }; - - private class LocationGesturesManager extends AndroidGesturesManager { - - LocationGesturesManager(Context context) { - super(context); - } - - @Override - public boolean onTouchEvent(@Nullable MotionEvent motionEvent) { - if (motionEvent != null) { - int action = motionEvent.getActionMasked(); - if (action == MotionEvent.ACTION_UP) { - adjustGesturesThresholds(); - } - } - return super.onTouchEvent(motionEvent); - } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponent.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponent.java deleted file mode 100644 index 8b014b0e9..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponent.java +++ /dev/null @@ -1,1618 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.hardware.SensorManager; -import android.location.Location; -import android.os.Looper; -import android.os.SystemClock; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.RequiresPermission; -import android.support.annotation.StyleRes; -import android.support.annotation.VisibleForTesting; -import android.view.WindowManager; - -import com.mapbox.android.core.location.LocationEngine; -import com.mapbox.android.core.location.LocationEngineCallback; -import com.mapbox.android.core.location.LocationEngineProvider; -import com.mapbox.android.core.location.LocationEngineRequest; -import com.mapbox.android.core.location.LocationEngineResult; -import com.mapbox.android.core.permissions.PermissionsManager; -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.camera.CameraUpdate; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.location.modes.CameraMode; -import com.mapbox.mapboxsdk.location.modes.RenderMode; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraIdleListener; -import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveListener; -import com.mapbox.mapboxsdk.maps.MapboxMap.OnMapClickListener; -import com.mapbox.mapboxsdk.maps.Style; -import com.mapbox.mapboxsdk.maps.Transform; - -import java.lang.ref.WeakReference; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import static android.Manifest.permission.ACCESS_COARSE_LOCATION; -import static android.Manifest.permission.ACCESS_FINE_LOCATION; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_FASTEST_INTERVAL_MILLIS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_INTERVAL_MILLIS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_TRACKING_TILT_ANIM_DURATION; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_TRACKING_ZOOM_ANIM_DURATION; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS; - -/** - * The Location Component provides location awareness to your mobile application. Enabling this - * component provides a contextual experience to your users by showing an icon representing the users - * current location. A few different modes are offered to provide the right context to your users at - * the correct time. {@link RenderMode#NORMAL} simply shows the users location on the map - * represented as a dot. {@link RenderMode#COMPASS} mode allows you to display an arrow icon - * (by default) that points in the direction the device is pointing in. - * {@link RenderMode#GPS} can be used in conjunction with our Navigation SDK to - * display a larger icon (customized with {@link LocationComponentOptions#gpsDrawable()}) we call the user puck. - *

- * This component also offers the ability to set a map camera behavior for tracking the user - * location. These different {@link CameraMode}s will track, stop tracking the location based on the - * mode set with {@link LocationComponent#setCameraMode(int)}. - *

- * - * To get the component object use {@link MapboxMap#getLocationComponent()} and activate it with - * {@link #activateLocationComponent(Context, Style)} or one of the overloads. - * Then, manage its visibility with {@link #setLocationComponentEnabled(boolean)}. - * The component will not process location updates right after activation, but only after being enabled. - * - *

- * Using this component requires you to request permission beforehand manually or using - * {@link PermissionsManager}. Either - * {@code ACCESS_COARSE_LOCATION} or {@code ACCESS_FINE_LOCATION} permissions can be requested for - * this component to work as expected. - *

- * This component offers a default, built-in {@link LocationEngine} with some of the activation methods. - * This engine will be obtained by {@link LocationEngineProvider#getBestLocationEngine(Context, boolean)} which defaults - * to the {@link com.mapbox.android.core.location.MapboxFusedLocationEngineImpl}. If you'd like to utilize Google - * Play Services - * for more precise location updates, simply add the Google Play Location Services dependency in your build script. - * This will make the default engine the {@link com.mapbox.android.core.location.GoogleLocationEngineImpl} instead. - * After a custom engine is passed to the component, or the built-in is initialized, - * the location updates are going to be requested with the {@link LocationEngineRequest}, either a default one, - * or the one passed during the activation. - * When using any engine, requesting/removing the location updates is going to be managed internally. - *

- * You can also push location updates to the component without any internal engine management. - * To achieve that, use {@link #activateLocationComponent(Context, Style, boolean)} with false. - * No engine is going to be initialized and you can push location updates with {@link #forceLocationUpdate(Location)}. - *

- * For location puck animation purposes, like navigation, - * we recommend limiting the maximum zoom level of the map for the best user experience. - *

- * Location Component doesn't support state saving out-of-the-box. - */ -public final class LocationComponent { - private static final String TAG = "Mbgl-LocationComponent"; - - @NonNull - private final MapboxMap mapboxMap; - @NonNull - private final Transform transform; - private Style style; - private LocationComponentOptions options; - @NonNull - private InternalLocationEngineProvider internalLocationEngineProvider = new InternalLocationEngineProvider(); - @Nullable - private LocationEngine locationEngine; - @NonNull - private LocationEngineRequest locationEngineRequest = - new LocationEngineRequest.Builder(DEFAULT_INTERVAL_MILLIS) - .setFastestInterval(DEFAULT_FASTEST_INTERVAL_MILLIS) - .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY) - .build(); - private LocationEngineCallback currentLocationEngineListener - = new CurrentLocationEngineCallback(this); - private LocationEngineCallback lastLocationEngineListener - = new LastLocationEngineCallback(this); - - @Nullable - private CompassEngine compassEngine; - - private LocationLayerController locationLayerController; - private LocationCameraController locationCameraController; - - private LocationAnimatorCoordinator locationAnimatorCoordinator; - - /** - * Holds last location which is being returned in the {@link #getLastKnownLocation()} - * when there is no {@link #locationEngine} set or when the last location returned by the engine is null. - */ - @Nullable - private Location lastLocation; - private CameraPosition lastCameraPosition; - - /** - * Indicates whether the component has been initialized. - */ - private boolean isComponentInitialized; - - /** - * Indicates that the component is enabled and should be displaying location if Mapbox components are available and - * the lifecycle is in a started state. - */ - private boolean isEnabled; - - /** - * Indicated that component's lifecycle {@link #onStart()} method has been called. - * This allows Mapbox components enter started state and display data, and adds state safety for methods like - * {@link #setLocationComponentEnabled(boolean)} - */ - private boolean isComponentStarted; - - /** - * Indicates if Mapbox components are ready to be interacted with. This can differ from {@link #isComponentStarted} - * if the Mapbox style is being reloaded. - */ - private boolean isLayerReady; - - /** - * Indicates whether we are listening for compass updates. - */ - private boolean isListeningToCompass; - - private StaleStateManager staleStateManager; - private final CopyOnWriteArrayList onLocationStaleListeners - = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onLocationClickListeners - = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onLocationLongClickListeners - = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onCameraTrackingChangedListeners - = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onRenderModeChangedListeners - = new CopyOnWriteArrayList<>(); - - // Workaround for too frequent updates, see https://github.com/mapbox/mapbox-gl-native/issues/13587 - private long fastestInterval; - private long lastUpdateTime; - - /** - * Internal use. - *

- * To get the component object use {@link MapboxMap#getLocationComponent()}. - */ - public LocationComponent(@NonNull MapboxMap mapboxMap, - @NonNull Transform transform, - @NonNull List developerAnimationListeners) { - this.mapboxMap = mapboxMap; - this.transform = transform; - developerAnimationListeners.add(developerAnimationListener); - } - - // used for creating a spy - LocationComponent() { - //noinspection ConstantConditions - mapboxMap = null; - transform = null; - } - - @VisibleForTesting - LocationComponent(@NonNull MapboxMap mapboxMap, - @NonNull Transform transform, - @NonNull List developerAnimationListeners, - @NonNull LocationEngineCallback currentListener, - @NonNull LocationEngineCallback lastListener, - @NonNull LocationLayerController locationLayerController, - @NonNull LocationCameraController locationCameraController, - @NonNull LocationAnimatorCoordinator locationAnimatorCoordinator, - @NonNull StaleStateManager staleStateManager, - @NonNull CompassEngine compassEngine, - @NonNull InternalLocationEngineProvider internalLocationEngineProvider) { - this.mapboxMap = mapboxMap; - this.transform = transform; - developerAnimationListeners.add(developerAnimationListener); - this.currentLocationEngineListener = currentListener; - this.lastLocationEngineListener = lastListener; - this.locationLayerController = locationLayerController; - this.locationCameraController = locationCameraController; - this.locationAnimatorCoordinator = locationAnimatorCoordinator; - this.staleStateManager = staleStateManager; - this.compassEngine = compassEngine; - this.internalLocationEngineProvider = internalLocationEngineProvider; - isComponentInitialized = true; - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - *

- * Note: This method will initialize and use an internal {@link LocationEngine} when enabled. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style) { - activateLocationComponent(context, style, - LocationComponentOptions.createFromAttributes(context, R.style.mapbox_LocationComponent)); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param useDefaultLocationEngine true if you want to initialize and use the built-in location engine or false if - * there should be no location engine initialized - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - boolean useDefaultLocationEngine) { - if (useDefaultLocationEngine) { - activateLocationComponent(context, style, R.style.mapbox_LocationComponent); - } else { - activateLocationComponent(context, style, null, R.style.mapbox_LocationComponent); - } - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param useDefaultLocationEngine true if you want to initialize and use the built-in location engine or false if - * there should be no location engine initialized - * @param locationEngineRequest the location request - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - boolean useDefaultLocationEngine, - @NonNull LocationEngineRequest locationEngineRequest) { - setLocationEngineRequest(locationEngineRequest); - if (useDefaultLocationEngine) { - activateLocationComponent(context, style, R.style.mapbox_LocationComponent); - } else { - activateLocationComponent(context, style, null, R.style.mapbox_LocationComponent); - } - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param useDefaultLocationEngine true if you want to initialize and use the built-in location engine or false if - * there should be no location engine initialized - * @param locationEngineRequest the location request - * @param options the options - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - boolean useDefaultLocationEngine, - @NonNull LocationEngineRequest locationEngineRequest, - @NonNull LocationComponentOptions options) { - setLocationEngineRequest(locationEngineRequest); - if (useDefaultLocationEngine) { - activateLocationComponent(context, style, options); - } else { - activateLocationComponent(context, style, null, options); - } - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - *

- * Note: This method will initialize and use an internal {@link LocationEngine} when enabled. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param styleRes the LocationComponent style res - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, @StyleRes int styleRes) { - activateLocationComponent(context, style, LocationComponentOptions.createFromAttributes(context, styleRes)); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - *

- * Note: This method will initialize and use an internal {@link LocationEngine} when enabled. - *

- * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param options the options - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @NonNull LocationComponentOptions options) { - initialize(context, style, options); - initializeLocationEngine(context); - applyStyle(options); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param locationEngine the engine, or null if you'd like to only force location updates - * @param styleRes the LocationComponent style res - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, @StyleRes int styleRes) { - activateLocationComponent(context, style, locationEngine, - LocationComponentOptions.createFromAttributes(context, styleRes)); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param locationEngine the engine, or null if you'd like to only force location updates - * @param locationEngineRequest the location request - * @param styleRes the LocationComponent style res - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, - @NonNull LocationEngineRequest locationEngineRequest, @StyleRes int styleRes) { - activateLocationComponent(context, style, locationEngine, locationEngineRequest, - LocationComponentOptions.createFromAttributes(context, styleRes)); - } - - /** - * This method will show the location icon and enable the camera tracking the location. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param locationEngine the engine - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine) { - activateLocationComponent(context, style, locationEngine, R.style.mapbox_LocationComponent); - } - - /** - * This method will show the location icon and enable the camera tracking the location. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param locationEngine the engine - * @param locationEngineRequest the location request - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, - @NonNull LocationEngineRequest locationEngineRequest) { - activateLocationComponent(context, style, locationEngine, locationEngineRequest, R.style.mapbox_LocationComponent); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param locationEngine the engine, or null if you'd like to only force location updates - * @param style the proxy object for current map style. More info at {@link Style} - * @param options the options - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, - @NonNull LocationComponentOptions options) { - initialize(context, style, options); - setLocationEngine(locationEngine); - applyStyle(options); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param context the context - * @param style the proxy object for current map style. More info at {@link Style} - * @param locationEngine the engine, or null if you'd like to only force location updates - * @param locationEngineRequest the location request - * @param options the options - * @deprecated use {@link LocationComponentActivationOptions.Builder} instead - */ - @Deprecated - public void activateLocationComponent(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, - @NonNull LocationEngineRequest locationEngineRequest, - @NonNull LocationComponentOptions options) { - initialize(context, style, options); - setLocationEngineRequest(locationEngineRequest); - setLocationEngine(locationEngine); - applyStyle(options); - } - - /** - * This method initializes the component and needs to be called before any other operations are performed. - * Afterwards, you can manage component's visibility by {@link #setLocationComponentEnabled(boolean)}. - * - * @param activationOptions a fully built {@link LocationComponentActivationOptions} object - */ - public void activateLocationComponent(@NonNull LocationComponentActivationOptions activationOptions) { - LocationComponentOptions options = activationOptions.locationComponentOptions(); - if (options == null) { - int styleRes = activationOptions.styleRes(); - if (styleRes == 0) { - styleRes = R.style.mapbox_LocationComponent; - } - options = LocationComponentOptions.createFromAttributes(activationOptions.context(), styleRes); - } - - // Initialize the LocationComponent with Context, the map's `Style`, and either custom LocationComponentOptions - // or backup options created from default/custom attributes - initialize(activationOptions.context(), activationOptions.style(), options); - - // Apply the LocationComponent styling - // TODO avoid doubling style initialization - applyStyle(options); - - // Set the LocationEngine request if one was given to LocationComponentActivationOptions - LocationEngineRequest locationEngineRequest = activationOptions.locationEngineRequest(); - if (locationEngineRequest != null) { - setLocationEngineRequest(locationEngineRequest); - } - - // Set the LocationEngine if one was given to LocationComponentActivationOptions - LocationEngine locationEngine = activationOptions.locationEngine(); - if (locationEngine != null) { - setLocationEngine(locationEngine); - } else { - if (activationOptions.useDefaultLocationEngine()) { - initializeLocationEngine(activationOptions.context()); - } else { - setLocationEngine(null); - } - } - } - - /** - * Manage component's visibility after activation. - * - * @param isEnabled true if the plugin should be visible and listen for location updates, false otherwise. - */ - @RequiresPermission(anyOf = {ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}) - public void setLocationComponentEnabled(boolean isEnabled) { - checkActivationState(); - if (isEnabled) { - enableLocationComponent(); - } else { - disableLocationComponent(); - } - } - - /** - * Returns whether the plugin is enabled, meaning that location can be displayed and camera modes can be used. - * - * @return true if the plugin is enabled, false otherwise - */ - public boolean isLocationComponentEnabled() { - checkActivationState(); - return isEnabled; - } - - /** - * Sets the camera mode, which determines how the map camera will track the rendered location. - *

- * When camera is transitioning to a new mode, it will reject inputs like {@link #zoomWhileTracking(double)} or - * {@link #tiltWhileTracking(double)}. - * Use {@link OnLocationCameraTransitionListener} to listen for the transition state. - *

- *

    - *
  • {@link CameraMode#NONE}: No camera tracking
  • - *
  • {@link CameraMode#NONE_COMPASS}: Camera does not track location, but does track compass bearing
  • - *
  • {@link CameraMode#NONE_GPS}: Camera does not track location, but does track GPS bearing
  • - *
  • {@link CameraMode#TRACKING}: Camera tracks the user location
  • - *
  • {@link CameraMode#TRACKING_COMPASS}: Camera tracks the user location, with bearing provided by a compass
  • - *
  • {@link CameraMode#TRACKING_GPS}: Camera tracks the user location, with normalized bearing
  • - *
  • {@link CameraMode#TRACKING_GPS_NORTH}: Camera tracks the user location, with bearing always set to north
  • - *
- * - * @param cameraMode one of the modes found in {@link CameraMode} - */ - public void setCameraMode(@CameraMode.Mode int cameraMode) { - setCameraMode(cameraMode, null); - } - - /** - * Sets the camera mode, which determines how the map camera will track the rendered location. - *

- * When camera is transitioning to a new mode, it will reject inputs like {@link #zoomWhileTracking(double)} or - * {@link #tiltWhileTracking(double)}. - * Use {@link OnLocationCameraTransitionListener} to listen for the transition state. - *

- *

    - *
  • {@link CameraMode#NONE}: No camera tracking
  • - *
  • {@link CameraMode#NONE_COMPASS}: Camera does not track location, but does track compass bearing
  • - *
  • {@link CameraMode#NONE_GPS}: Camera does not track location, but does track GPS bearing
  • - *
  • {@link CameraMode#TRACKING}: Camera tracks the user location
  • - *
  • {@link CameraMode#TRACKING_COMPASS}: Camera tracks the user location, with bearing provided by a compass
  • - *
  • {@link CameraMode#TRACKING_GPS}: Camera tracks the user location, with normalized bearing
  • - *
  • {@link CameraMode#TRACKING_GPS_NORTH}: Camera tracks the user location, with bearing always set to north
  • - *
- * - * @param cameraMode one of the modes found in {@link CameraMode} - * @param transitionListener callback that's going to be invoked when the transition animation finishes - */ - public void setCameraMode(@CameraMode.Mode int cameraMode, - @Nullable OnLocationCameraTransitionListener transitionListener) { - setCameraMode(cameraMode, TRANSITION_ANIMATION_DURATION_MS, null, null, null, transitionListener); - } - - /** - * Sets the camera mode, which determines how the map camera will track the rendered location. - *

- * When camera is transitioning to a new mode, it will reject inputs like {@link #zoomWhileTracking(double)} or - * {@link #tiltWhileTracking(double)}. - * Use {@link OnLocationCameraTransitionListener} to listen for the transition state. - *

- * Set values of zoom, bearing and tilt that the camera will transition to. If null is passed to any of those, - * current value will be used for that parameter instead. - * If the camera is already tracking, provided values are ignored. - *

- *

    - *
  • {@link CameraMode#NONE}: No camera tracking
  • - *
  • {@link CameraMode#NONE_COMPASS}: Camera does not track location, but does track compass bearing
  • - *
  • {@link CameraMode#NONE_GPS}: Camera does not track location, but does track GPS bearing
  • - *
  • {@link CameraMode#TRACKING}: Camera tracks the user location
  • - *
  • {@link CameraMode#TRACKING_COMPASS}: Camera tracks the user location, with bearing provided by a compass
  • - *
  • {@link CameraMode#TRACKING_GPS}: Camera tracks the user location, with normalized bearing
  • - *
  • {@link CameraMode#TRACKING_GPS_NORTH}: Camera tracks the user location, with bearing always set to north
  • - *
- * - * @param cameraMode one of the modes found in {@link CameraMode} - * @param transitionDuration duration of the transition in milliseconds - * @param zoom target zoom, set to null to use current camera position - * @param bearing target bearing, set to null to use current camera position - * @param tilt target tilt, set to null to use current camera position - * @param transitionListener callback that's going to be invoked when the transition animation finishes - */ - public void setCameraMode(@CameraMode.Mode int cameraMode, - long transitionDuration, - @Nullable Double zoom, @Nullable Double bearing, @Nullable Double tilt, - @Nullable OnLocationCameraTransitionListener transitionListener) { - checkActivationState(); - locationCameraController.setCameraMode( - cameraMode, lastLocation, transitionDuration, zoom, bearing, tilt, - new CameraTransitionListener(transitionListener)); - updateCompassListenerState(true); - } - - /** - * Used to reset camera animators and notify listeners when the transition finishes. - */ - private class CameraTransitionListener implements OnLocationCameraTransitionListener { - - private final OnLocationCameraTransitionListener externalListener; - - private CameraTransitionListener(OnLocationCameraTransitionListener externalListener) { - this.externalListener = externalListener; - } - - @Override - public void onLocationCameraTransitionFinished(int cameraMode) { - if (externalListener != null) { - externalListener.onLocationCameraTransitionFinished(cameraMode); - } - reset(cameraMode); - } - - @Override - public void onLocationCameraTransitionCanceled(int cameraMode) { - if (externalListener != null) { - externalListener.onLocationCameraTransitionCanceled(cameraMode); - } - reset(cameraMode); - } - - private void reset(@CameraMode.Mode int cameraMode) { - locationAnimatorCoordinator.resetAllCameraAnimations(mapboxMap.getCameraPosition(), - cameraMode == CameraMode.TRACKING_GPS_NORTH); - } - } - - /** - * Provides the current camera mode being used to track the location or compass updates. - * - * @return the current camera mode - */ - @CameraMode.Mode - public int getCameraMode() { - checkActivationState(); - return locationCameraController.getCameraMode(); - } - - /** - * Sets the render mode, which determines how the location updates will be rendered on the map. - *

- *

    - *
  • {@link RenderMode#NORMAL}: Shows user location, bearing ignored
  • - *
  • {@link RenderMode#COMPASS}: Shows user location with bearing considered from compass
  • - *
  • {@link RenderMode#GPS}: Shows user location with bearing considered from location
  • - *
- * - * @param renderMode one of the modes found in {@link RenderMode} - */ - public void setRenderMode(@RenderMode.Mode int renderMode) { - checkActivationState(); - locationLayerController.setRenderMode(renderMode); - updateLayerOffsets(true); - updateCompassListenerState(true); - } - - /** - * Provides the current render mode being used to show - * the location and/or compass updates on the map. - * - * @return the current render mode - */ - @RenderMode.Mode - public int getRenderMode() { - checkActivationState(); - return locationLayerController.getRenderMode(); - } - - /** - * Returns the current location options being used. - * - * @return the current {@link LocationComponentOptions} - */ - public LocationComponentOptions getLocationComponentOptions() { - checkActivationState(); - return options; - } - - /** - * Apply a new component style with a style resource. - * - * @param styleRes a XML style overriding some or all the options - */ - public void applyStyle(@NonNull Context context, @StyleRes int styleRes) { - checkActivationState(); - applyStyle(LocationComponentOptions.createFromAttributes(context, styleRes)); - } - - /** - * Apply a new component style with location component options. - * - * @param options to update the current style - */ - public void applyStyle(@NonNull final LocationComponentOptions options) { - checkActivationState(); - LocationComponent.this.options = options; - if (mapboxMap.getStyle() != null) { - locationLayerController.applyStyle(options); - locationCameraController.initializeOptions(options); - staleStateManager.setEnabled(options.enableStaleState()); - staleStateManager.setDelayTime(options.staleStateTimeout()); - locationAnimatorCoordinator.setTrackingAnimationDurationMultiplier(options.trackingAnimationDurationMultiplier()); - locationAnimatorCoordinator.setCompassAnimationEnabled(options.compassAnimationEnabled()); - locationAnimatorCoordinator.setAccuracyAnimationEnabled(options.accuracyAnimationEnabled()); - updateMapWithOptions(options); - } - } - - /** - * Zooms to the desired zoom level. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the zoom change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the zoom as a camera change argument. - *

- * - * @param zoomLevel The desired zoom level. - * @param animationDuration The zoom animation duration. - * @param callback The callback with finish/cancel information - */ - public void zoomWhileTracking(double zoomLevel, long animationDuration, - @Nullable MapboxMap.CancelableCallback callback) { - checkActivationState(); - if (!isLayerReady) { - return; - } else if (getCameraMode() == CameraMode.NONE) { - Logger.e(TAG, String.format("%s%s", - "LocationComponent#zoomWhileTracking method can only be used", - " when a camera mode other than CameraMode#NONE is engaged.")); - return; - } else if (locationCameraController.isTransitioning()) { - Logger.e(TAG, - "LocationComponent#zoomWhileTracking method call is ignored because the camera mode is transitioning"); - return; - } - locationAnimatorCoordinator.feedNewZoomLevel(zoomLevel, mapboxMap.getCameraPosition(), animationDuration, callback); - } - - /** - * Zooms to the desired zoom level. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the zoom change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the zoom as a camera change argument. - *

- * - * @param zoomLevel The desired zoom level. - * @param animationDuration The zoom animation duration. - */ - public void zoomWhileTracking(double zoomLevel, long animationDuration) { - checkActivationState(); - zoomWhileTracking(zoomLevel, animationDuration, null); - } - - /** - * Zooms to the desired zoom level. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the zoom change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the zoom as a camera change argument. - *

- * - * @param zoomLevel The desired zoom level. - */ - public void zoomWhileTracking(double zoomLevel) { - checkActivationState(); - zoomWhileTracking(zoomLevel, DEFAULT_TRACKING_ZOOM_ANIM_DURATION, null); - } - - /** - * Cancels animation started by {@link #zoomWhileTracking(double, long, MapboxMap.CancelableCallback)}. - */ - public void cancelZoomWhileTrackingAnimation() { - checkActivationState(); - locationAnimatorCoordinator.cancelZoomAnimation(); - } - - /** - * Tilts the camera. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the tilt change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the tilt as a camera change argument. - *

- * - * @param tilt The desired camera tilt. - * @param animationDuration The tilt animation duration. - * @param callback The callback with finish/cancel information - */ - public void tiltWhileTracking(double tilt, long animationDuration, - @Nullable MapboxMap.CancelableCallback callback) { - checkActivationState(); - if (!isLayerReady) { - return; - } else if (getCameraMode() == CameraMode.NONE) { - Logger.e(TAG, String.format("%s%s", - "LocationComponent#tiltWhileTracking method can only be used", - " when a camera mode other than CameraMode#NONE is engaged.")); - return; - } else if (locationCameraController.isTransitioning()) { - Logger.e(TAG, - "LocationComponent#tiltWhileTracking method call is ignored because the camera mode is transitioning"); - return; - } - locationAnimatorCoordinator.feedNewTilt(tilt, mapboxMap.getCameraPosition(), animationDuration, callback); - } - - /** - * Tilts the camera. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the tilt change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the tilt as a camera change argument. - *

- * - * @param tilt The desired camera tilt. - * @param animationDuration The tilt animation duration. - */ - public void tiltWhileTracking(double tilt, long animationDuration) { - checkActivationState(); - tiltWhileTracking(tilt, animationDuration, null); - } - - /** - * Tilts the camera. - * This API can only be used in pair with camera modes other than {@link CameraMode#NONE}. - * If you are not using any of {@link CameraMode} modes, - * use one of {@link MapboxMap#moveCamera(CameraUpdate)}, - * {@link MapboxMap#easeCamera(CameraUpdate)} or {@link MapboxMap#animateCamera(CameraUpdate)} instead. - *

- * If the camera is transitioning when the tilt change is requested, the call is going to be ignored. - * Use {@link CameraTransitionListener} to chain the animations, or provide the tilt as a camera change argument. - *

- * - * @param tilt The desired camera tilt. - */ - public void tiltWhileTracking(double tilt) { - checkActivationState(); - tiltWhileTracking(tilt, DEFAULT_TRACKING_TILT_ANIM_DURATION, null); - } - - /** - * Cancels animation started by {@link #tiltWhileTracking(double, long, MapboxMap.CancelableCallback)}. - */ - public void cancelTiltWhileTrackingAnimation() { - checkActivationState(); - locationAnimatorCoordinator.cancelTiltAnimation(); - } - - /** - * Use to either force a location update or to manually control when the user location gets - * updated. - * - * @param location where the location icon is placed on the map - */ - public void forceLocationUpdate(@Nullable Location location) { - checkActivationState(); - updateLocation(location, false); - } - - /** - * Set max FPS at which location animators can output updates. The throttling will only impact the location puck - * and camera tracking smooth animations. - *

- * Setting this will not impact any other animations schedule with {@link MapboxMap}, gesture animations or - * {@link #zoomWhileTracking(double)}/{@link #tiltWhileTracking(double)}. - *

- * Use this setting to limit animation rate of the location puck on higher zoom levels to decrease the stress on - * the device's CPU which can directly improve battery life, without sacrificing UX. - *

- * Example usage: - *

-   * {@code
-   * mapboxMap.addOnCameraIdleListener(new MapboxMap.OnCameraIdleListener() {
-   *   {@literal @}Override
-   *   public void onCameraIdle() {
-   *     double zoom = mapboxMap.getCameraPosition().zoom;
-   *     int maxAnimationFps;
-   *     if (zoom < 5) {
-   *       maxAnimationFps = 3;
-   *     } else if (zoom < 10) {
-   *       maxAnimationFps = 5;
-   *     } else if (zoom < 15) {
-   *       maxAnimationFps = 7;
-   *     } else if (zoom < 18) {
-   *       maxAnimationFps = 15;
-   *     } else {
-   *       maxAnimationFps = Integer.MAX_VALUE;
-   *     }
-   *     locationComponent.setMaxAnimationFps(maxAnimationFps);
-   *   }
-   * });
-   * }
-   * 
- *

- * If you're looking for a way to throttle the FPS of the whole map, including other animations and gestures, see - * {@link MapView#setMaximumFps(int)}. - * - * @param maxAnimationFps max location animation FPS - */ - public void setMaxAnimationFps(int maxAnimationFps) { - checkActivationState(); - locationAnimatorCoordinator.setMaxAnimationFps(maxAnimationFps); - } - - /** - * Set the location engine to update the current user location. - *

- * If {@code null} is passed in, all updates will have to occur through the - * {@link LocationComponent#forceLocationUpdate(Location)} method. - * - * @param locationEngine a {@link LocationEngine} this component should use to handle updates - */ - @SuppressLint("MissingPermission") - public void setLocationEngine(@Nullable LocationEngine locationEngine) { - checkActivationState(); - if (this.locationEngine != null) { - // If internal location engines being used, extra steps need to be taken to deconstruct the instance. - this.locationEngine.removeLocationUpdates(currentLocationEngineListener); - this.locationEngine = null; - } - - if (locationEngine != null) { - fastestInterval = locationEngineRequest.getFastestInterval(); - this.locationEngine = locationEngine; - if (isLayerReady && isEnabled) { - setLastLocation(); - locationEngine.requestLocationUpdates( - locationEngineRequest, currentLocationEngineListener, Looper.getMainLooper()); - } - } else { - fastestInterval = 0; - } - } - - /** - * Set the location request that's going to be used when requesting location updates. - * - * @param locationEngineRequest the location request - */ - public void setLocationEngineRequest(@NonNull LocationEngineRequest locationEngineRequest) { - checkActivationState(); - this.locationEngineRequest = locationEngineRequest; - - // reset internal LocationEngine ref to re-request location updates if needed - setLocationEngine(locationEngine); - } - - /** - * Get the location request that's going to be used when requesting location updates. - */ - @NonNull - public LocationEngineRequest getLocationEngineRequest() { - checkActivationState(); - return locationEngineRequest; - } - - /** - * Returns the current {@link LocationEngine} being used for updating the user location. - * - * @return the {@link LocationEngine} being used to update the user location - */ - @Nullable - public LocationEngine getLocationEngine() { - checkActivationState(); - return locationEngine; - } - - /** - * Sets the compass engine used to provide compass heading values. - * - * @param compassEngine to be used - */ - public void setCompassEngine(@Nullable CompassEngine compassEngine) { - checkActivationState(); - if (this.compassEngine != null) { - updateCompassListenerState(false); - } - this.compassEngine = compassEngine; - updateCompassListenerState(true); - } - - /** - * Returns the compass engine used to provide compass heading values. - * - * @return compass engine currently being used - */ - @Nullable - public CompassEngine getCompassEngine() { - checkActivationState(); - return compassEngine; - } - - /** - * Get the last know location of the location component. - * - * @return the last known location - */ - @Nullable - public Location getLastKnownLocation() { - checkActivationState(); - return lastLocation; - } - - /** - * Adds a listener that gets invoked when the user clicks the displayed location. - *

- * If there are registered location click listeners and the location is clicked, - * only {@link OnLocationClickListener#onLocationComponentClick()} is going to be delivered, - * {@link com.mapbox.mapboxsdk.maps.MapboxMap.OnMapClickListener#onMapClick(LatLng)} is going to be consumed - * and not pushed to the listeners registered after the component's activation. - * - * @param listener The location click listener that is invoked when the - * location is clicked - */ - public void addOnLocationClickListener(@NonNull OnLocationClickListener listener) { - onLocationClickListeners.add(listener); - } - - /** - * Removes the passed listener from the current list of location click listeners. - * - * @param listener to be removed - */ - public void removeOnLocationClickListener(@NonNull OnLocationClickListener listener) { - onLocationClickListeners.remove(listener); - } - - /** - * Adds a listener that gets invoked when the user long clicks the displayed location. - *

- * If there are registered location long click listeners and the location is long clicked, - * only {@link OnLocationLongClickListener#onLocationComponentLongClick()} is going to be delivered, - * {@link com.mapbox.mapboxsdk.maps.MapboxMap.OnMapLongClickListener#onMapLongClick(LatLng)} is going to be consumed - * and not pushed to the listeners registered after the component's activation. - * - * @param listener The location click listener that is invoked when the - * location is clicked - */ - public void addOnLocationLongClickListener(@NonNull OnLocationLongClickListener listener) { - onLocationLongClickListeners.add(listener); - } - - /** - * Removes the passed listener from the current list of location long click listeners. - * - * @param listener to be removed - */ - public void removeOnLocationLongClickListener(@NonNull OnLocationLongClickListener listener) { - onLocationLongClickListeners.remove(listener); - } - - /** - * Adds a listener that gets invoked when camera tracking state changes. - * - * @param listener Listener that gets invoked when camera tracking state changes. - */ - public void addOnCameraTrackingChangedListener(@NonNull OnCameraTrackingChangedListener listener) { - onCameraTrackingChangedListeners.add(listener); - } - - /** - * Removes a listener that gets invoked when camera tracking state changes. - * - * @param listener Listener that gets invoked when camera tracking state changes. - */ - public void removeOnCameraTrackingChangedListener(@NonNull OnCameraTrackingChangedListener listener) { - onCameraTrackingChangedListeners.remove(listener); - } - - /** - * Adds a listener that gets invoked when render mode changes. - * - * @param listener Listener that gets invoked when render mode changes. - */ - public void addOnRenderModeChangedListener(@NonNull OnRenderModeChangedListener listener) { - onRenderModeChangedListeners.add(listener); - } - - /** - * Removes a listener that gets invoked when render mode changes. - * - * @param listener Listener that gets invoked when render mode changes. - */ - public void removeRenderModeChangedListener(@NonNull OnRenderModeChangedListener listener) { - onRenderModeChangedListeners.remove(listener); - } - - /** - * Adds the passed listener that gets invoked when user updates have stopped long enough for the last update - * to be considered stale. - *

- * This timeout is set by {@link LocationComponentOptions#staleStateTimeout()}. - * - * @param listener invoked when last update is considered stale - */ - public void addOnLocationStaleListener(@NonNull OnLocationStaleListener listener) { - onLocationStaleListeners.add(listener); - } - - /** - * Removes the passed listener from the current list of stale listeners. - * - * @param listener to be removed from the list - */ - public void removeOnLocationStaleListener(@NonNull OnLocationStaleListener listener) { - onLocationStaleListeners.remove(listener); - } - - /** - * Internal use. - */ - public void onStart() { - isComponentStarted = true; - onLocationLayerStart(); - } - - /** - * Internal use. - */ - public void onStop() { - onLocationLayerStop(); - isComponentStarted = false; - } - - /** - * Internal use. - */ - public void onDestroy() { - } - - /** - * Internal use. - */ - public void onStartLoadingMap() { - onLocationLayerStop(); - } - - /** - * Internal use. - */ - public void onFinishLoadingStyle() { - if (isComponentInitialized) { - style = mapboxMap.getStyle(); - locationLayerController.initializeComponents(style, options); - locationCameraController.initializeOptions(options); - onLocationLayerStart(); - } - } - - @SuppressLint("MissingPermission") - private void onLocationLayerStart() { - if (!isComponentInitialized || !isComponentStarted || mapboxMap.getStyle() == null) { - return; - } - - if (!isLayerReady) { - isLayerReady = true; - mapboxMap.addOnCameraMoveListener(onCameraMoveListener); - mapboxMap.addOnCameraIdleListener(onCameraIdleListener); - if (options.enableStaleState()) { - staleStateManager.onStart(); - } - } - - if (isEnabled) { - if (locationEngine != null) { - try { - locationEngine.requestLocationUpdates( - locationEngineRequest, currentLocationEngineListener, Looper.getMainLooper()); - } catch (SecurityException se) { - Logger.e(TAG, "Unable to request location updates", se); - } - } - setCameraMode(locationCameraController.getCameraMode()); - setLastLocation(); - updateCompassListenerState(true); - setLastCompassHeading(); - } - } - - private void onLocationLayerStop() { - if (!isComponentInitialized || !isLayerReady || !isComponentStarted) { - return; - } - - isLayerReady = false; - staleStateManager.onStop(); - if (compassEngine != null) { - updateCompassListenerState(false); - } - locationAnimatorCoordinator.cancelAllAnimations(); - if (locationEngine != null) { - locationEngine.removeLocationUpdates(currentLocationEngineListener); - } - mapboxMap.removeOnCameraMoveListener(onCameraMoveListener); - mapboxMap.removeOnCameraIdleListener(onCameraIdleListener); - } - - private void initialize(@NonNull final Context context, @NonNull Style style, - @NonNull final LocationComponentOptions options) { - if (isComponentInitialized) { - return; - } - isComponentInitialized = true; - - if (!style.isFullyLoaded()) { - throw new IllegalStateException("Style is invalid, provide the most recently loaded one."); - } - - this.style = style; - this.options = options; - - mapboxMap.addOnMapClickListener(onMapClickListener); - mapboxMap.addOnMapLongClickListener(onMapLongClickListener); - - LayerSourceProvider sourceProvider = new LayerSourceProvider(); - LayerFeatureProvider featureProvider = new LayerFeatureProvider(); - LayerBitmapProvider bitmapProvider = new LayerBitmapProvider(context); - locationLayerController = new LocationLayerController(mapboxMap, style, sourceProvider, featureProvider, - bitmapProvider, options, renderModeChangedListener); - locationCameraController = new LocationCameraController( - context, mapboxMap, transform, cameraTrackingChangedListener, options, onCameraMoveInvalidateListener); - - locationAnimatorCoordinator = new LocationAnimatorCoordinator( - mapboxMap.getProjection(), - MapboxAnimatorSetProvider.getInstance(), - MapboxAnimatorProvider.getInstance() - ); - locationAnimatorCoordinator.setTrackingAnimationDurationMultiplier(options - .trackingAnimationDurationMultiplier()); - - WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); - SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - if (windowManager != null && sensorManager != null) { - compassEngine = new LocationComponentCompassEngine(windowManager, sensorManager); - } - staleStateManager = new StaleStateManager(onLocationStaleListener, options); - - updateMapWithOptions(options); - - setRenderMode(RenderMode.NORMAL); - setCameraMode(CameraMode.NONE); - - onLocationLayerStart(); - } - - private void initializeLocationEngine(@NonNull Context context) { - if (this.locationEngine != null) { - this.locationEngine.removeLocationUpdates(currentLocationEngineListener); - } - setLocationEngine(internalLocationEngineProvider.getBestLocationEngine(context, false)); - } - - private void updateCompassListenerState(boolean canListen) { - if (compassEngine != null) { - if (!canListen) { - // We shouldn't listen, simply unregistering - removeCompassListener(compassEngine); - return; - } - - if (!isComponentInitialized || !isComponentStarted || !isEnabled) { - return; - } - - if (locationCameraController.isConsumingCompass() || locationLayerController.isConsumingCompass()) { - // If we have a consumer, and not yet listening, then start listening - if (!isListeningToCompass) { - isListeningToCompass = true; - compassEngine.addCompassListener(compassListener); - } - } else { - // If we have no consumers, stop listening - removeCompassListener(compassEngine); - } - } - } - - private void removeCompassListener(@NonNull CompassEngine engine) { - if (isListeningToCompass) { - isListeningToCompass = false; - engine.removeCompassListener(compassListener); - } - } - - private void enableLocationComponent() { - isEnabled = true; - onLocationLayerStart(); - } - - private void disableLocationComponent() { - isEnabled = false; - locationLayerController.hide(); - onLocationLayerStop(); - } - - private void updateMapWithOptions(@NonNull LocationComponentOptions options) { - int[] padding = options.padding(); - if (padding != null) { - mapboxMap.setPadding( - padding[0], padding[1], padding[2], padding[3] - ); - } - } - - /** - * Updates the user location icon. - * - * @param location the latest user location - */ - private void updateLocation(@Nullable final Location location, boolean fromLastLocation) { - if (location == null) { - return; - } else if (!isLayerReady) { - lastLocation = location; - return; - } else { - long currentTime = SystemClock.elapsedRealtime(); - if (currentTime - lastUpdateTime < fastestInterval) { - return; - } else { - lastUpdateTime = currentTime; - } - } - - showLocationLayerIfHidden(); - - if (!fromLastLocation) { - staleStateManager.updateLatestLocationTime(); - } - CameraPosition currentCameraPosition = mapboxMap.getCameraPosition(); - boolean isGpsNorth = getCameraMode() == CameraMode.TRACKING_GPS_NORTH; - locationAnimatorCoordinator.feedNewLocation(location, currentCameraPosition, isGpsNorth); - updateAccuracyRadius(location, false); - lastLocation = location; - } - - private void showLocationLayerIfHidden() { - boolean isLocationLayerHidden = locationLayerController.isHidden(); - if (isEnabled && isComponentStarted && isLocationLayerHidden) { - locationLayerController.show(); - } - } - - private void updateCompassHeading(float heading) { - locationAnimatorCoordinator.feedNewCompassBearing(heading, mapboxMap.getCameraPosition()); - } - - /** - * If the locationEngine contains a last location value, we use it for the initial location layer - * position. - */ - @SuppressLint("MissingPermission") - private void setLastLocation() { - if (locationEngine != null) { - locationEngine.getLastLocation(lastLocationEngineListener); - } else { - updateLocation(getLastKnownLocation(), true); - } - } - - private void setLastCompassHeading() { - updateCompassHeading(compassEngine != null ? compassEngine.getLastHeading() : 0); - } - - @SuppressLint("MissingPermission") - private void updateLayerOffsets(boolean forceUpdate) { - CameraPosition position = mapboxMap.getCameraPosition(); - if (lastCameraPosition == null || forceUpdate) { - lastCameraPosition = position; - locationLayerController.updateForegroundBearing((float) position.bearing); - locationLayerController.updateForegroundOffset(position.tilt); - updateAccuracyRadius(getLastKnownLocation(), true); - return; - } - - if (position.bearing != lastCameraPosition.bearing) { - locationLayerController.updateForegroundBearing((float) position.bearing); - } - if (position.tilt != lastCameraPosition.tilt) { - locationLayerController.updateForegroundOffset(position.tilt); - } - if (position.zoom != lastCameraPosition.zoom) { - updateAccuracyRadius(getLastKnownLocation(), true); - } - lastCameraPosition = position; - } - - private void updateAccuracyRadius(Location location, boolean noAnimation) { - locationAnimatorCoordinator.feedNewAccuracyRadius(Utils.calculateZoomLevelRadius(mapboxMap, location), noAnimation); - } - - private void updateAnimatorListenerHolders() { - Set animationsValueChangeListeners = new HashSet<>(); - animationsValueChangeListeners.addAll(locationLayerController.getAnimationListeners()); - animationsValueChangeListeners.addAll(locationCameraController.getAnimationListeners()); - locationAnimatorCoordinator.updateAnimatorListenerHolders(animationsValueChangeListeners); - locationAnimatorCoordinator.resetAllCameraAnimations(mapboxMap.getCameraPosition(), - locationCameraController.getCameraMode() == CameraMode.TRACKING_GPS_NORTH); - locationAnimatorCoordinator.resetAllLayerAnimations(); - } - - @NonNull - private OnCameraMoveListener onCameraMoveListener = new OnCameraMoveListener() { - @Override - public void onCameraMove() { - updateLayerOffsets(false); - } - }; - - @NonNull - private OnCameraIdleListener onCameraIdleListener = new OnCameraIdleListener() { - @Override - public void onCameraIdle() { - updateLayerOffsets(false); - } - }; - - @NonNull - private OnMapClickListener onMapClickListener = new OnMapClickListener() { - @Override - public boolean onMapClick(@NonNull LatLng point) { - if (!onLocationClickListeners.isEmpty() && locationLayerController.onMapClick(point)) { - for (OnLocationClickListener listener : onLocationClickListeners) { - listener.onLocationComponentClick(); - } - return true; - } - return false; - } - }; - - @NonNull - private MapboxMap.OnMapLongClickListener onMapLongClickListener = new MapboxMap.OnMapLongClickListener() { - @Override - public boolean onMapLongClick(@NonNull LatLng point) { - if (!onLocationLongClickListeners.isEmpty() && locationLayerController.onMapClick(point)) { - for (OnLocationLongClickListener listener : onLocationLongClickListeners) { - listener.onLocationComponentLongClick(); - } - return true; - } - return false; - } - }; - - @NonNull - private OnLocationStaleListener onLocationStaleListener = new OnLocationStaleListener() { - @Override - public void onStaleStateChange(boolean isStale) { - locationLayerController.setLocationsStale(isStale); - - for (OnLocationStaleListener listener : onLocationStaleListeners) { - listener.onStaleStateChange(isStale); - } - } - }; - - @NonNull - private OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = new OnCameraMoveInvalidateListener() { - @Override - public void onInvalidateCameraMove() { - onCameraMoveListener.onCameraMove(); - } - }; - - @NonNull - private CompassListener compassListener = new CompassListener() { - @Override - public void onCompassChanged(float userHeading) { - updateCompassHeading(userHeading); - } - - @Override - public void onCompassAccuracyChange(int compassStatus) { - // Currently don't handle this inside SDK - } - }; - - @VisibleForTesting - static final class CurrentLocationEngineCallback implements LocationEngineCallback { - private final WeakReference componentWeakReference; - - CurrentLocationEngineCallback(LocationComponent component) { - this.componentWeakReference = new WeakReference<>(component); - } - - @Override - public void onSuccess(LocationEngineResult result) { - LocationComponent component = componentWeakReference.get(); - if (component != null) { - component.updateLocation(result.getLastLocation(), false); - } - } - - @Override - public void onFailure(@NonNull Exception exception) { - Logger.e(TAG, "Failed to obtain location update", exception); - } - } - - @VisibleForTesting - static final class LastLocationEngineCallback implements LocationEngineCallback { - private final WeakReference componentWeakReference; - - LastLocationEngineCallback(LocationComponent component) { - this.componentWeakReference = new WeakReference<>(component); - } - - @Override - public void onSuccess(LocationEngineResult result) { - LocationComponent component = componentWeakReference.get(); - if (component != null) { - component.updateLocation(result.getLastLocation(), true); - } - } - - @Override - public void onFailure(@NonNull Exception exception) { - Logger.e(TAG, "Failed to obtain last location update", exception); - } - } - - @NonNull - @VisibleForTesting - OnCameraTrackingChangedListener cameraTrackingChangedListener = new OnCameraTrackingChangedListener() { - @Override - public void onCameraTrackingDismissed() { - for (OnCameraTrackingChangedListener listener : onCameraTrackingChangedListeners) { - listener.onCameraTrackingDismissed(); - } - } - - @Override - public void onCameraTrackingChanged(int currentMode) { - locationAnimatorCoordinator.cancelZoomAnimation(); - locationAnimatorCoordinator.cancelTiltAnimation(); - updateAnimatorListenerHolders(); - for (OnCameraTrackingChangedListener listener : onCameraTrackingChangedListeners) { - listener.onCameraTrackingChanged(currentMode); - } - } - }; - - @NonNull - @VisibleForTesting - OnRenderModeChangedListener renderModeChangedListener = new OnRenderModeChangedListener() { - @Override - public void onRenderModeChanged(int currentMode) { - updateAnimatorListenerHolders(); - for (OnRenderModeChangedListener listener : onRenderModeChangedListeners) { - listener.onRenderModeChanged(currentMode); - } - } - }; - - @NonNull - private final MapboxMap.OnDeveloperAnimationListener developerAnimationListener = - new MapboxMap.OnDeveloperAnimationListener() { - @Override - public void onDeveloperAnimationStarted() { - if (isComponentInitialized && isEnabled) { - setCameraMode(CameraMode.NONE); - } - } - }; - - static class InternalLocationEngineProvider { - LocationEngine getBestLocationEngine(@NonNull Context context, boolean background) { - return LocationEngineProvider.getBestLocationEngine(context, background); - } - } - - private void checkActivationState() { - if (!isComponentInitialized) { - throw new LocationComponentNotInitializedException(); - } - } - - /** - * Returns whether the location component is activated. - * - * @return true if the component is activated, false otherwise - */ - public boolean isLocationComponentActivated() { - return isComponentInitialized; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptions.java deleted file mode 100644 index 04987621e..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptions.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.android.core.location.LocationEngine; -import com.mapbox.android.core.location.LocationEngineRequest; -import com.mapbox.mapboxsdk.maps.Style; - -/** - * A class which holds the various options for activating the Maps SDK's {@link LocationComponent} to eventually - * show the device location on the map. - */ -public class LocationComponentActivationOptions { - - private final Context context; - private final Style style; - private final LocationEngine locationEngine; - private final LocationEngineRequest locationEngineRequest; - private final LocationComponentOptions locationComponentOptions; - private final int styleRes; - private final boolean useDefaultLocationEngine; - - private LocationComponentActivationOptions(@NonNull Context context, @NonNull Style style, - @Nullable LocationEngine locationEngine, - @Nullable LocationEngineRequest locationEngineRequest, - @Nullable LocationComponentOptions locationComponentOptions, - int styleRes, - boolean useDefaultLocationEngine) { - this.context = context; - this.style = style; - this.locationEngine = locationEngine; - this.locationEngineRequest = locationEngineRequest; - this.locationComponentOptions = locationComponentOptions; - this.styleRes = styleRes; - this.useDefaultLocationEngine = useDefaultLocationEngine; - } - - /** - * Convenience method to retrieve a {@link LocationComponentActivationOptions} object which is ready to build with - * - * @return a builder object - */ - @NonNull - public static Builder builder(@NonNull Context context, @NonNull Style fullyLoadedMapStyle) { - return new LocationComponentActivationOptions.Builder(context, fullyLoadedMapStyle); - } - - /** - * The application's current context - * - * @return the application's current context - */ - @NonNull - public Context context() { - return context; - } - - /** - * The proxy object for current map style. More info at {@link Style} - * - * @return the map's fully loaded Style object - */ - @NonNull - public Style style() { - return style; - } - - /** - * The {@link LocationEngine} which the {@link LocationComponent} should use - * - * @return the engine - */ - @Nullable - public LocationEngine locationEngine() { - return locationEngine; - } - - /** - * The location request which the {@link LocationComponent} should use - * - * @return the LocationEngineRequest object - */ - @Nullable - public LocationEngineRequest locationEngineRequest() { - return locationEngineRequest; - } - - /** - * A built {@link LocationComponentOptions} object, which holds the various {@link LocationComponent} styling options - * - * @return the options for styling the actual LocationComponent - */ - @Nullable - public LocationComponentOptions locationComponentOptions() { - return locationComponentOptions; - } - - /** - * The LocationComponent style resource (e.g. R.style.style_name) - * - * @return the style resource. - */ - public int styleRes() { - return styleRes; - } - - /** - * True if you want to initialize and use the built-in location engine or false if there should be no - * location engine initialized - * - * @return whether the default LocationEngine is used - */ - public boolean useDefaultLocationEngine() { - return useDefaultLocationEngine; - } - - /** - * Builder class for constructing a new instance of {@link LocationComponentActivationOptions}. - */ - public static class Builder { - private final Context context; - private final Style style; - private LocationEngine locationEngine; - private LocationEngineRequest locationEngineRequest; - private LocationComponentOptions locationComponentOptions; - private int styleRes; - - /** - * Set to true as the default in case a true/false value isn't declared via the builder's - * {@link LocationComponentActivationOptions#useDefaultLocationEngine()} method. - *

- * Please be aware that this activation boolean is ignored when a non-null - * {@link LocationEngine} is set via the builder's `locationEngine()` method. - */ - private boolean useDefaultLocationEngine = true; - - /** - * Constructor for the {@link LocationComponentActivationOptions} builder class. - * While other activation options are optional, the activation process always requires - * context and a fully-loaded map {@link Style} object, which is why the two are in this - * constructor. - */ - public Builder(@NonNull Context context, @NonNull Style style) { - this.context = context; - this.style = style; - } - - /** - * Deliver your own {@link LocationEngine} to the LocationComponent. - *

- * The true/false - * {@link LocationComponentActivationOptions.Builder#useDefaultLocationEngine()} - * activation option is ignored when a non-null {@link LocationEngine} is set via - * this `locationEngine()` method. - * - * @param locationEngine a {@link LocationEngine} object - * @return the {@link Builder} object being constructed - */ - @NonNull - public Builder locationEngine(@Nullable LocationEngine locationEngine) { - this.locationEngine = locationEngine; - return this; - } - - /** - * @param locationEngineRequest the location request which the - * {@link LocationComponent} should use - * @return the {@link Builder} object being constructed - */ - public Builder locationEngineRequest(LocationEngineRequest locationEngineRequest) { - this.locationEngineRequest = locationEngineRequest; - return this; - } - - /** - * @param locationComponentOptions a built {@link LocationComponentOptions} object, - * which holds the various {@link LocationComponent} - * styling options - * @return the {@link Builder} object being constructed - */ - public Builder locationComponentOptions(LocationComponentOptions locationComponentOptions) { - this.locationComponentOptions = locationComponentOptions; - return this; - } - - /** - * @param styleRes the LocationComponent style resource (e.g. R.style.style_name) - * @return the {@link Builder} object being constructed - */ - public Builder styleRes(int styleRes) { - this.styleRes = styleRes; - return this; - } - - /** - * @param useDefaultLocationEngine true if you want to initialize and use the - * built-in location engine or false if there - * should be no location engine initialized - * This is ignored when null is set as the parameter - * for {@link LocationComponentActivationOptions#builder - * (Context, Style)#locationEngine()}. - * @return the {@link Builder} object being constructed - */ - public Builder useDefaultLocationEngine(boolean useDefaultLocationEngine) { - this.useDefaultLocationEngine = useDefaultLocationEngine; - return this; - } - - /** - * Method which actually builds the {@link LocationComponentActivationOptions} object while - * taking the various options into account. - * - * @return a built {@link LocationComponentActivationOptions} object - */ - public LocationComponentActivationOptions build() { - if (styleRes != 0 && locationComponentOptions != null) { - throw new IllegalArgumentException( - "You've provided both a style resource and a LocationComponentOptions object to the " - + "LocationComponentActivationOptions builder. You can't use both and " - + "you must choose one of the two to style the LocationComponent."); - } - if (context == null) { - throw new NullPointerException( - "Context in LocationComponentActivationOptions is null."); - } - if (style == null) { - throw new NullPointerException( - "Style in LocationComponentActivationOptions is null. Make sure the " - + "Style object isn't null. Wait for the map to fully load before passing " - + "the Style object to LocationComponentActivationOptions."); - } - if (!style.isFullyLoaded()) { - throw new IllegalArgumentException( - "Style in LocationComponentActivationOptions isn't fully loaded. Wait for the " - + "map to fully load before passing the Style object to " - + "LocationComponentActivationOptions."); - } - return new LocationComponentActivationOptions(context, style, locationEngine, - locationEngineRequest, locationComponentOptions, styleRes, useDefaultLocationEngine); - } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentCompassEngine.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentCompassEngine.java deleted file mode 100644 index ce3823303..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentCompassEngine.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.os.SystemClock; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.Surface; -import android.view.WindowManager; - -import com.mapbox.mapboxsdk.log.Logger; - -import java.util.ArrayList; -import java.util.List; - -/** - * This manager class handles compass events such as starting the tracking of device bearing, or - * when a new compass update occurs. - */ -class LocationComponentCompassEngine implements CompassEngine, SensorEventListener { - - private static final String TAG = "Mbgl-LocationComponentCompassEngine"; - - // The rate sensor events will be delivered at. As the Android documentation states, this is only - // a hint to the system and the events might actually be received faster or slower then this - // specified rate. Since the minimum Android API levels about 9, we are able to set this value - // ourselves rather than using one of the provided constants which deliver updates too quickly for - // our use case. The default is set to 100ms - static final int SENSOR_DELAY_MICROS = 100 * 1000; - // Filtering coefficient 0 < ALPHA < 1 - private static final float ALPHA = 0.45f; - - @NonNull - private final WindowManager windowManager; - @NonNull - private final SensorManager sensorManager; - private final List compassListeners = new ArrayList<>(); - - // Not all devices have a compassSensor - @Nullable - private Sensor compassSensor; - @Nullable - private Sensor gravitySensor; - @Nullable - private Sensor magneticFieldSensor; - - @NonNull - private float[] truncatedRotationVectorValue = new float[4]; - @NonNull - private float[] rotationMatrix = new float[9]; - private float[] rotationVectorValue; - private float lastHeading; - private int lastAccuracySensorStatus; - - private long compassUpdateNextTimestamp; - @Nullable - private float[] gravityValues = new float[3]; - @Nullable - private float[] magneticValues = new float[3]; - - /** - * Construct a new instance of the this class. A internal compass listeners needed to separate it - * from the cleared list of public listeners. - */ - LocationComponentCompassEngine(@NonNull WindowManager windowManager, @NonNull SensorManager sensorManager) { - this.windowManager = windowManager; - this.sensorManager = sensorManager; - compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); - if (compassSensor == null) { - if (isGyroscopeAvailable()) { - Logger.d(TAG, "Rotation vector sensor not supported on device, " - + "falling back to orientation."); - compassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); - } else { - Logger.d(TAG, "Rotation vector sensor not supported on device, " - + "falling back to accelerometer and magnetic field."); - gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - magneticFieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - } - } - } - - @Override - public void addCompassListener(@NonNull CompassListener compassListener) { - if (compassListeners.isEmpty()) { - registerSensorListeners(); - } - compassListeners.add(compassListener); - } - - @Override - public void removeCompassListener(@NonNull CompassListener compassListener) { - compassListeners.remove(compassListener); - if (compassListeners.isEmpty()) { - unregisterSensorListeners(); - } - } - - @Override - public int getLastAccuracySensorStatus() { - return lastAccuracySensorStatus; - } - - @Override - public float getLastHeading() { - return lastHeading; - } - - @Override - public void onSensorChanged(@NonNull SensorEvent event) { - // check when the last time the compass was updated, return if too soon. - long currentTime = SystemClock.elapsedRealtime(); - if (currentTime < compassUpdateNextTimestamp) { - return; - } - if (lastAccuracySensorStatus == SensorManager.SENSOR_STATUS_UNRELIABLE) { - Logger.d(TAG, "Compass sensor is unreliable, device calibration is needed."); - return; - } - if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) { - rotationVectorValue = getRotationVectorFromSensorEvent(event); - updateOrientation(); - } else if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { - notifyCompassChangeListeners((event.values[0] + 360) % 360); - } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { - gravityValues = lowPassFilter(getRotationVectorFromSensorEvent(event), gravityValues); - updateOrientation(); - } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { - magneticValues = lowPassFilter(getRotationVectorFromSensorEvent(event), magneticValues); - updateOrientation(); - } - - // Update the compassUpdateNextTimestamp - compassUpdateNextTimestamp = currentTime + LocationComponentConstants.COMPASS_UPDATE_RATE_MS; - } - - @Override - public void onAccuracyChanged(Sensor sensor, int accuracy) { - if (lastAccuracySensorStatus != accuracy) { - for (CompassListener compassListener : compassListeners) { - compassListener.onCompassAccuracyChange(accuracy); - } - lastAccuracySensorStatus = accuracy; - } - } - - private boolean isGyroscopeAvailable() { - return sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null; - } - - @SuppressWarnings("SuspiciousNameCombination") - private void updateOrientation() { - if (rotationVectorValue != null) { - SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVectorValue); - } else { - // Get rotation matrix given the gravity and geomagnetic matrices - SensorManager.getRotationMatrix(rotationMatrix, null, gravityValues, magneticValues); - } - - final int worldAxisForDeviceAxisX; - final int worldAxisForDeviceAxisY; - - // Remap the axes as if the device screen was the instrument panel, - // and adjust the rotation matrix for the device orientation. - switch (windowManager.getDefaultDisplay().getRotation()) { - case Surface.ROTATION_90: - worldAxisForDeviceAxisX = SensorManager.AXIS_Z; - worldAxisForDeviceAxisY = SensorManager.AXIS_MINUS_X; - break; - case Surface.ROTATION_180: - worldAxisForDeviceAxisX = SensorManager.AXIS_MINUS_X; - worldAxisForDeviceAxisY = SensorManager.AXIS_MINUS_Z; - break; - case Surface.ROTATION_270: - worldAxisForDeviceAxisX = SensorManager.AXIS_MINUS_Z; - worldAxisForDeviceAxisY = SensorManager.AXIS_X; - break; - case Surface.ROTATION_0: - default: - worldAxisForDeviceAxisX = SensorManager.AXIS_X; - worldAxisForDeviceAxisY = SensorManager.AXIS_Z; - break; - } - - float[] adjustedRotationMatrix = new float[9]; - SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisForDeviceAxisX, - worldAxisForDeviceAxisY, adjustedRotationMatrix); - - // Transform rotation matrix into azimuth/pitch/roll - float[] orientation = new float[3]; - SensorManager.getOrientation(adjustedRotationMatrix, orientation); - - // The x-axis is all we care about here. - notifyCompassChangeListeners((float) Math.toDegrees(orientation[0])); - } - - private void notifyCompassChangeListeners(float heading) { - for (CompassListener compassListener : compassListeners) { - compassListener.onCompassChanged(heading); - } - lastHeading = heading; - } - - private void registerSensorListeners() { - if (isCompassSensorAvailable()) { - // Does nothing if the sensors already registered. - sensorManager.registerListener(this, compassSensor, SENSOR_DELAY_MICROS); - } else { - sensorManager.registerListener(this, gravitySensor, SENSOR_DELAY_MICROS); - sensorManager.registerListener(this, magneticFieldSensor, SENSOR_DELAY_MICROS); - } - } - - private void unregisterSensorListeners() { - if (isCompassSensorAvailable()) { - sensorManager.unregisterListener(this, compassSensor); - } else { - sensorManager.unregisterListener(this, gravitySensor); - sensorManager.unregisterListener(this, magneticFieldSensor); - } - } - - private boolean isCompassSensorAvailable() { - return compassSensor != null; - } - - /** - * Helper function, that filters newValues, considering previous values - * - * @param newValues array of float, that contains new data - * @param smoothedValues array of float, that contains previous state - * @return float filtered array of float - */ - @NonNull - private float[] lowPassFilter(@NonNull float[] newValues, @Nullable float[] smoothedValues) { - if (smoothedValues == null) { - return newValues; - } - for (int i = 0; i < newValues.length; i++) { - smoothedValues[i] = smoothedValues[i] + ALPHA * (newValues[i] - smoothedValues[i]); - } - return smoothedValues; - } - - /** - * 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 - private 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; - } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentConstants.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentConstants.java deleted file mode 100644 index f2158584c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentConstants.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -/** - * Contains all the constants being used for the {@link LocationComponent}. - */ -public final class LocationComponentConstants { - - // Controls the compass update rate in milliseconds - static final long COMPASS_UPDATE_RATE_MS = 500; - - // Sets the transition animation duration when switching camera modes. - static final long TRANSITION_ANIMATION_DURATION_MS = 750; - - // Sets the max allowed time for the location icon animation from one LatLng to another. - static final long MAX_ANIMATION_DURATION_MS = 2000; - - // Sets the duration of change of accuracy radius when a different value is provided. - static final long ACCURACY_RADIUS_ANIMATION_DURATION = 250; - - // Default animation duration for zooming while tracking. - static final long DEFAULT_TRACKING_ZOOM_ANIM_DURATION = 750; - - // Default animation duration for tilting while tracking. - static final long DEFAULT_TRACKING_TILT_ANIM_DURATION = 1250; - - // Threshold value to perform immediate camera/layer position update. - static final double INSTANT_LOCATION_TRANSITION_THRESHOLD = 50_000; - - // Default interval between location updates - static final long DEFAULT_INTERVAL_MILLIS = 1000; - - // Default fastest acceptable interval between location updates - static final long DEFAULT_FASTEST_INTERVAL_MILLIS = 1000; - - // Sources - - /** - * Source ID of the location's GeoJsonSource. - */ - public static final String LOCATION_SOURCE = "mapbox-location-source"; - - static final String PROPERTY_GPS_BEARING = "mapbox-property-gps-bearing"; - static final String PROPERTY_COMPASS_BEARING = "mapbox-property-compass-bearing"; - static final String PROPERTY_LOCATION_STALE = "mapbox-property-location-stale"; - static final String PROPERTY_ACCURACY_RADIUS = "mapbox-property-accuracy-radius"; - static final String PROPERTY_ACCURACY_COLOR = "mapbox-property-accuracy-color"; - static final String PROPERTY_ACCURACY_ALPHA = "mapbox-property-accuracy-alpha"; - static final String PROPERTY_FOREGROUND_ICON_OFFSET = "mapbox-property-foreground-icon-offset"; - static final String PROPERTY_SHADOW_ICON_OFFSET = "mapbox-property-shadow-icon-offset"; - static final String PROPERTY_FOREGROUND_ICON = "mapbox-property-foreground-icon"; - static final String PROPERTY_BACKGROUND_ICON = "mapbox-property-background-icon"; - static final String PROPERTY_FOREGROUND_STALE_ICON = "mapbox-property-foreground-stale-icon"; - static final String PROPERTY_BACKGROUND_STALE_ICON = "mapbox-property-background-stale-icon"; - static final String PROPERTY_BEARING_ICON = "mapbox-property-shadow-icon"; - - // Layers - - /** - * Layer ID of the location shadow. - */ - public static final String SHADOW_LAYER = "mapbox-location-shadow-layer"; - - /** - * Layer ID of the location foreground icon. - */ - public static final String FOREGROUND_LAYER = "mapbox-location-foreground-layer"; - - /** - * Layer ID of the location background icon. - */ - public static final String BACKGROUND_LAYER = "mapbox-location-background-layer"; - - /** - * Layer ID of the location accuracy. - */ - public static final String ACCURACY_LAYER = "mapbox-location-accuracy-layer"; - - /** - * Layer ID of the location bearing icon. - */ - public static final String BEARING_LAYER = "mapbox-location-bearing-layer"; - - // Icons - static final String FOREGROUND_ICON = "mapbox-location-icon"; - static final String BACKGROUND_ICON = "mapbox-location-stroke-icon"; - static final String FOREGROUND_STALE_ICON = "mapbox-location-stale-icon"; - static final String BACKGROUND_STALE_ICON = "mapbox-location-background-stale-icon"; - static final String SHADOW_ICON = "mapbox-location-shadow-icon"; - static final String BEARING_ICON = "mapbox-location-bearing-icon"; - - private LocationComponentConstants() { - // Class should not be initialized - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentNotInitializedException.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentNotInitializedException.java deleted file mode 100644 index 82a73b973..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentNotInitializedException.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -final class LocationComponentNotInitializedException extends RuntimeException { - LocationComponentNotInitializedException() { - super("The LocationComponent has to be activated with one of the LocationComponent#activateLocationComponent" - + " overloads before any other methods are invoked."); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentOptions.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentOptions.java deleted file mode 100644 index 48c89622c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentOptions.java +++ /dev/null @@ -1,1778 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.os.Parcel; -import android.os.Parcelable; -import android.support.annotation.ColorInt; -import android.support.annotation.Dimension; -import android.support.annotation.DrawableRes; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.StyleRes; - -import com.mapbox.android.gestures.AndroidGesturesManager; -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.style.layers.Layer; - -import java.util.Arrays; - -/** - * This class exposes options for the Location Component. The options can be set by defining a - * style in your apps style.xml file and passing in directly into the {@link LocationComponent} - * class. Alternatively, if properties need to be changed at runtime depending on a specific state, - * you can build an instance of this class, setting the values you desire, and then passing it into - * either the {@link LocationComponent} activation method (if it isn't initialized yet) or - * {@link LocationComponent#applyStyle(LocationComponentOptions)}. - *

- * When the {@link #createFromAttributes(Context, int)} methods called, any attributes not found - * inside the style will revert back to using their default set values. Likewise, when building a - * new {@link LocationComponentOptions} class using the builder, any options neglecting to be set will - * reset to their default values. - *

- * If you would like to keep your custom style changes while modifying a single attribute, you can - * get the currently used options object using {@link LocationComponent#getLocationComponentOptions()} - * and it's {@code toBuilder} method to modify a single entry while also maintaining the other - * settings. Once your modifications have been made, you'll need to pass it back into the location - * component using {@link LocationComponent#applyStyle(LocationComponentOptions)}. - */ -public class LocationComponentOptions implements Parcelable { - - /** - * Default accuracy alpha - */ - private static final float ACCURACY_ALPHA_DEFAULT = 0.15f; - - /** - * Default icon scale factor when the map is zoomed out - */ - private static final float MIN_ZOOM_ICON_SCALE_DEFAULT = 0.6f; - - /** - * Default icon scale factor when the map is zoomed in - */ - private static final float MAX_ZOOM_ICON_SCALE_DEFAULT = 1f; - - /** - * Default map padding - */ - private static final int[] PADDING_DEFAULT = {0, 0, 0, 0}; - - /** - * The default value which is used when the stale state is enabled - */ - private static final long STALE_STATE_DELAY_MS = 30_000L; - - /** - * Default animation duration multiplier - */ - private static final float TRACKING_ANIMATION_DURATION_MULTIPLIER_DEFAULT = 1.1f; - - private float accuracyAlpha; - private int accuracyColor; - private int backgroundDrawableStale; - @Nullable - private String backgroundStaleName; - private int foregroundDrawableStale; - @Nullable - private String foregroundStaleName; - private int gpsDrawable; - @Nullable - private String gpsName; - private int foregroundDrawable; - @Nullable - private String foregroundName; - private int backgroundDrawable; - @Nullable - private String backgroundName; - private int bearingDrawable; - @Nullable - private String bearingName; - @Nullable - private Integer bearingTintColor; - @Nullable - private Integer foregroundTintColor; - @Nullable - private Integer backgroundTintColor; - @Nullable - private Integer foregroundStaleTintColor; - @Nullable - private Integer backgroundStaleTintColor; - private float elevation; - private boolean enableStaleState; - private long staleStateTimeout; - @Nullable - private int[] padding; - private float maxZoomIconScale; - private float minZoomIconScale; - private boolean trackingGesturesManagement; - private float trackingInitialMoveThreshold; - private float trackingMultiFingerMoveThreshold; - private String layerAbove; - private String layerBelow; - private float trackingAnimationDurationMultiplier; - private boolean compassAnimationEnabled; - private boolean accuracyAnimationEnabled; - - public LocationComponentOptions( - float accuracyAlpha, - int accuracyColor, - int backgroundDrawableStale, - @Nullable String backgroundStaleName, - int foregroundDrawableStale, - @Nullable String foregroundStaleName, - int gpsDrawable, - @Nullable String gpsName, - int foregroundDrawable, - @Nullable String foregroundName, - int backgroundDrawable, - @Nullable String backgroundName, - int bearingDrawable, - @Nullable String bearingName, - @Nullable Integer bearingTintColor, - @Nullable Integer foregroundTintColor, - @Nullable Integer backgroundTintColor, - @Nullable Integer foregroundStaleTintColor, - @Nullable Integer backgroundStaleTintColor, - float elevation, - boolean enableStaleState, - long staleStateTimeout, - @Nullable int[] padding, - float maxZoomIconScale, - float minZoomIconScale, - boolean trackingGesturesManagement, - float trackingInitialMoveThreshold, - float trackingMultiFingerMoveThreshold, - String layerAbove, - String layerBelow, - float trackingAnimationDurationMultiplier, - boolean compassAnimationEnabled, - boolean accuracyAnimationEnabled) { - this.accuracyAlpha = accuracyAlpha; - this.accuracyColor = accuracyColor; - this.backgroundDrawableStale = backgroundDrawableStale; - this.backgroundStaleName = backgroundStaleName; - this.foregroundDrawableStale = foregroundDrawableStale; - this.foregroundStaleName = foregroundStaleName; - this.gpsDrawable = gpsDrawable; - this.gpsName = gpsName; - this.foregroundDrawable = foregroundDrawable; - this.foregroundName = foregroundName; - this.backgroundDrawable = backgroundDrawable; - this.backgroundName = backgroundName; - this.bearingDrawable = bearingDrawable; - this.bearingName = bearingName; - this.bearingTintColor = bearingTintColor; - this.foregroundTintColor = foregroundTintColor; - this.backgroundTintColor = backgroundTintColor; - this.foregroundStaleTintColor = foregroundStaleTintColor; - this.backgroundStaleTintColor = backgroundStaleTintColor; - this.elevation = elevation; - this.enableStaleState = enableStaleState; - this.staleStateTimeout = staleStateTimeout; - if (padding == null) { - throw new NullPointerException("Null padding"); - } - this.padding = padding; - this.maxZoomIconScale = maxZoomIconScale; - this.minZoomIconScale = minZoomIconScale; - this.trackingGesturesManagement = trackingGesturesManagement; - this.trackingInitialMoveThreshold = trackingInitialMoveThreshold; - this.trackingMultiFingerMoveThreshold = trackingMultiFingerMoveThreshold; - this.layerAbove = layerAbove; - this.layerBelow = layerBelow; - this.trackingAnimationDurationMultiplier = trackingAnimationDurationMultiplier; - this.compassAnimationEnabled = compassAnimationEnabled; - this.accuracyAnimationEnabled = accuracyAnimationEnabled; - } - - /** - * Construct a new Location Component Options class using the attributes found within a style - * resource. It's important to note that you only need to define the attributes you plan to - * change and can safely ignore the other attributes which will be set to their default value. - * - * @param context your activity's context used for acquiring resources - * @param styleRes the style id where your custom attributes are defined - * @return a new {@link LocationComponentOptions} object with the settings you defined in your style - * resource - */ - @NonNull - public static LocationComponentOptions createFromAttributes(@NonNull Context context, - @StyleRes int styleRes) { - - TypedArray typedArray = context.obtainStyledAttributes( - styleRes, R.styleable.mapbox_LocationComponent); - - LocationComponentOptions.Builder builder = new LocationComponentOptions.Builder() - .enableStaleState(true) - .staleStateTimeout(STALE_STATE_DELAY_MS) - .maxZoomIconScale(MAX_ZOOM_ICON_SCALE_DEFAULT) - .minZoomIconScale(MIN_ZOOM_ICON_SCALE_DEFAULT) - .padding(PADDING_DEFAULT); - - builder.foregroundDrawable(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_foregroundDrawable, -1)); - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_foregroundTintColor)) { - builder.foregroundTintColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_foregroundTintColor, -1)); - } - builder.backgroundDrawable(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_backgroundDrawable, -1)); - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_backgroundTintColor)) { - builder.backgroundTintColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_backgroundTintColor, -1)); - } - builder.foregroundDrawableStale(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_foregroundDrawableStale, -1)); - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_foregroundStaleTintColor)) { - builder.foregroundStaleTintColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_foregroundStaleTintColor, -1)); - } - builder.backgroundDrawableStale(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_backgroundDrawableStale, -1)); - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_backgroundStaleTintColor)) { - builder.backgroundStaleTintColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_backgroundStaleTintColor, -1)); - } - builder.bearingDrawable(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_bearingDrawable, -1)); - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_bearingTintColor)) { - builder.bearingTintColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_bearingTintColor, -1)); - } - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_enableStaleState)) { - builder.enableStaleState(typedArray.getBoolean( - R.styleable.mapbox_LocationComponent_mapbox_enableStaleState, true)); - } - if (typedArray.hasValue(R.styleable.mapbox_LocationComponent_mapbox_staleStateTimeout)) { - builder.staleStateTimeout(typedArray.getInteger( - R.styleable.mapbox_LocationComponent_mapbox_staleStateTimeout, (int) STALE_STATE_DELAY_MS)); - } - builder.gpsDrawable(typedArray.getResourceId( - R.styleable.mapbox_LocationComponent_mapbox_gpsDrawable, -1)); - float elevation = typedArray.getDimension( - R.styleable.mapbox_LocationComponent_mapbox_elevation, 0); - builder.accuracyColor(typedArray.getColor( - R.styleable.mapbox_LocationComponent_mapbox_accuracyColor, -1)); - builder.accuracyAlpha(typedArray.getFloat( - R.styleable.mapbox_LocationComponent_mapbox_accuracyAlpha, ACCURACY_ALPHA_DEFAULT)); - builder.elevation(elevation); - - builder.trackingGesturesManagement(typedArray.getBoolean( - R.styleable.mapbox_LocationComponent_mapbox_trackingGesturesManagement, false)); - builder.trackingInitialMoveThreshold(typedArray.getDimension( - R.styleable.mapbox_LocationComponent_mapbox_trackingInitialMoveThreshold, - context.getResources().getDimension(R.dimen.mapbox_locationComponentTrackingInitialMoveThreshold))); - builder.trackingMultiFingerMoveThreshold(typedArray.getDimension( - R.styleable.mapbox_LocationComponent_mapbox_trackingMultiFingerMoveThreshold, - context.getResources().getDimension(R.dimen.mapbox_locationComponentTrackingMultiFingerMoveThreshold))); - - builder.padding(new int[] { - typedArray.getInt(R.styleable.mapbox_LocationComponent_mapbox_iconPaddingLeft, 0), - typedArray.getInt(R.styleable.mapbox_LocationComponent_mapbox_iconPaddingTop, 0), - typedArray.getInt(R.styleable.mapbox_LocationComponent_mapbox_iconPaddingRight, 0), - typedArray.getInt(R.styleable.mapbox_LocationComponent_mapbox_iconPaddingBottom, 0), - }); - - builder.layerAbove( - typedArray.getString(R.styleable.mapbox_LocationComponent_mapbox_layer_above)); - - builder.layerBelow( - typedArray.getString(R.styleable.mapbox_LocationComponent_mapbox_layer_below)); - - float minScale = typedArray.getFloat( - R.styleable.mapbox_LocationComponent_mapbox_minZoomIconScale, MIN_ZOOM_ICON_SCALE_DEFAULT); - float maxScale = typedArray.getFloat( - R.styleable.mapbox_LocationComponent_mapbox_maxZoomIconScale, MAX_ZOOM_ICON_SCALE_DEFAULT); - builder.minZoomIconScale(minScale); - builder.maxZoomIconScale(maxScale); - - float trackingAnimationDurationMultiplier = typedArray.getFloat( - R.styleable.mapbox_LocationComponent_mapbox_trackingAnimationDurationMultiplier, - TRACKING_ANIMATION_DURATION_MULTIPLIER_DEFAULT - ); - builder.trackingAnimationDurationMultiplier(trackingAnimationDurationMultiplier); - - builder.compassAnimationEnabled = typedArray.getBoolean( - R.styleable.mapbox_LocationComponent_mapbox_compassAnimationEnabled, true - ); - - builder.accuracyAnimationEnabled = typedArray.getBoolean( - R.styleable.mapbox_LocationComponent_mapbox_accuracyAnimationEnabled, true - ); - - typedArray.recycle(); - - return builder.build(); - } - - /** - * Takes the currently constructed {@link LocationComponentOptions} object and provides it's builder - * with all the values set matching the values in this instance. This allows you to modify a - * single attribute and then rebuild the object. - * - * @return the builder which contains the values defined in this current instance as defaults. - */ - @NonNull - public Builder toBuilder() { - return new Builder(this); - } - - /** - * Build a new instance of the {@link LocationComponentOptions} class with all the attributes set - * automatically to their defined defaults in this library. This allows you to adjust a few - * attributes while leaving the rest alone and maintaining their default behavior. - * - * @param context your activities context used to acquire the style resource - * @return the builder which contains the default values defined by the style resource - */ - @NonNull - public static Builder builder(@NonNull Context context) { - return LocationComponentOptions.createFromAttributes(context, - R.style.mapbox_LocationComponent).toBuilder(); - } - - /** - * Set the opacity of the accuracy view to a value from 0 to 1, where 0 means the accuracy view is - * completely transparent and 1 means the view is completely opaque. - * References style attribute R.styleable#LocationComponent_accuracyAlpha - * - * @return the opacity of the accuracy view - */ - public float accuracyAlpha() { - return accuracyAlpha; - } - - /** - * Solid color to use as the accuracy view color property. - * References style attribute R.styleable#LocationComponent_accuracyColor - * - * @return the color of the accuracy view - */ - @ColorInt - public int accuracyColor() { - return accuracyColor; - } - - /** - * Defines the drawable used for the stale background icon. - * References style attribute R.styleable#LocationComponent_backgroundDrawableStale - * - * @return the drawable resource ID - */ - @DrawableRes - public int backgroundDrawableStale() { - return backgroundDrawableStale; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will use this image in place of the provided or default mapbox_foregroundDrawableStale. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String backgroundStaleName() { - return backgroundStaleName; - } - - /** - * Defines the drawable used for the stale foreground icon. - * References style attribute R.styleable#LocationComponent_foregroundDrawableStale - * - * @return the drawable resource ID - */ - @DrawableRes - public int foregroundDrawableStale() { - return foregroundDrawableStale; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_foregroundDrawableStale. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String foregroundStaleName() { - return foregroundStaleName; - } - - /** - * Defines the drawable used for the navigation state icon. - * References style attribute R.styleable#LocationComponent_gpsDrawable - * - * @return the drawable resource ID - */ - @DrawableRes - public int gpsDrawable() { - return gpsDrawable; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_gpsDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String gpsName() { - return gpsName; - } - - /** - * Supply a Drawable that is to be rendered on top of all of the content in the Location LayerComponent layer stack. - * References style attribute R.styleable#LocationComponent_foregroundDrawable - * - * @return the drawable resource used for the foreground layer - */ - @DrawableRes - public int foregroundDrawable() { - return foregroundDrawable; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_foregroundDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String foregroundName() { - return foregroundName; - } - - /** - * Defines the drawable used for the background state icon. - * References style attribute R.styleable#LocationComponent_backgroundDrawable - * - * @return the drawable resource ID - */ - @DrawableRes - public int backgroundDrawable() { - return backgroundDrawable; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_backgroundDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String backgroundName() { - return backgroundName; - } - - /** - * Defines the drawable used for the bearing icon. - * References style attribute R.styleable#LocationComponent_bearingDrawable - * - * @return the drawable resource ID - */ - @DrawableRes - public int bearingDrawable() { - return bearingDrawable; - } - - /** - * String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_bearingDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @return String icon or maki-icon name - */ - @Nullable - public String bearingName() { - return bearingName; - } - - /** - * Defines the bearing icon color as an integer. - * References style attribute R.styleable#LocationComponent_bearingTintColor - * - * @return the color integer resource - */ - @ColorInt - @Nullable - public Integer bearingTintColor() { - return bearingTintColor; - } - - /** - * Defines the foreground color as an integer. - * References style attribute R.styleable#LocationComponent_foregroundTintColor - * - * @return the color integer resource - */ - @ColorInt - @Nullable - public Integer foregroundTintColor() { - return foregroundTintColor; - } - - /** - * Defines the background color as an integer. - * References style attribute R.styleable#LocationComponent_backgroundTintColor - * - * @return the color integer resource - */ - @ColorInt - @Nullable - public Integer backgroundTintColor() { - return backgroundTintColor; - } - - /** - * Defines the foreground stale color as an integer. - * References style attribute R.styleable#LocationComponent_foregroundStaleTintColor - * - * @return the color integer resource - */ - @ColorInt - @Nullable - public Integer foregroundStaleTintColor() { - return foregroundStaleTintColor; - } - - /** - * Defines the background stale color as an integer. - * References style attribute R.styleable#LocationComponent_backgroundStaleTintColor - * - * @return the color integer resource - */ - @ColorInt - @Nullable - public Integer backgroundStaleTintColor() { - return backgroundStaleTintColor; - } - - /** - * Sets the base elevation of this view, in pixels. To turn off the shadow that appears under - * the location icon, set the elevation to 0. - * References style attribute R.styleable#LocationComponent_elevation - * - * @return the elevation currently set for the location component icon - */ - @Dimension - public float elevation() { - return elevation; - } - - /** - * Enable or disable to stale state mode. This mode indicates to the user that the location being - * displayed on the map hasn't been updated in a specific amount of time. - * References style attribute R.styleable#LocationComponent_enableStaleState - * - * @return whether the stale state mode is enabled or not - */ - public boolean enableStaleState() { - return enableStaleState; - } - - /** - * Set the delay before the location icon becomes stale. The timer begins approximately when a new - * location update comes in and using this defined time, if an update hasn't occured by the end, - * the location is considered stale. - * References style attribute R.styleable#LocationComponent_staleStateDelay - * - * @return the duration in milliseconds which it should take before the location is - * considered stale - */ - public long staleStateTimeout() { - return staleStateTimeout; - } - - /** - * Sets the distance from the edges of the map view’s frame to the edges of the map - * view’s logical viewport. - *

- *

- * 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 - * frame from the viewport. For instance, if the only the top edge is inset, the - * map center is effectively shifted downward. - *

- * - * @return integer array of padding values - */ - @Nullable - @SuppressWarnings("mutable") - public int[] padding() { - return padding; - } - - /** - * The scale factor of the location icon when the map is zoomed in. - * Scaling is linear. - * - * @return icon scale factor - */ - public float maxZoomIconScale() { - return maxZoomIconScale; - } - - /** - * The scale factor of the location icon when the map is zoomed out. - * Scaling is linear. - * - * @return icon scale factor - */ - public float minZoomIconScale() { - return minZoomIconScale; - } - - /** - * Returns whether gesture threshold should be adjusted when camera is in one of the tracking modes. - * This will adjust the focal point and increase thresholds to enable camera manipulation, - * like zooming in and out, without breaking tracking. - *

- * Note: If set to true, this can overwrite some of the gesture thresholds - * and the custom {@link com.mapbox.android.gestures.AndroidGesturesManager} that was set with - * {@link com.mapbox.mapboxsdk.maps.MapboxMap#setGesturesManager(AndroidGesturesManager, boolean, boolean)}. - * - * @return true if gestures are adjusted when in one of the camera tracking modes, false otherwise - * @see Builder#trackingInitialMoveThreshold(float) - * @see Builder#trackingMultiFingerMoveThreshold(float) - */ - public boolean trackingGesturesManagement() { - return trackingGesturesManagement; - } - - /** - * Minimum single pointer movement in pixels required to break camera tracking. - * - * @return the minimum movement - */ - public float trackingInitialMoveThreshold() { - return trackingInitialMoveThreshold; - } - - /** - * Minimum multi pointer movement in pixels required to break camera tracking (for example during scale gesture). - * - * @return the minimum movement - */ - public float trackingMultiFingerMoveThreshold() { - return trackingMultiFingerMoveThreshold; - } - - /** - * Gets the id of the layer that's referenced when placing the component on the map using - * {@link com.mapbox.mapboxsdk.maps.Style#addLayerAbove(Layer, String)}. - *

- * The component is going to placed directly above this layer. - * - * @return layerAbove the id of the layer the component is going to placed directly above. - */ - public String layerAbove() { - return layerAbove; - } - - /** - * Gets the id of the layer that's referenced when placing the component on the map using - * {@link com.mapbox.mapboxsdk.maps.Style#addLayerBelow(Layer, String)}. - *

- * The component is going to placed directly below this layer. - * - * @return layerBelow the id of the layer the component is going to placed directly below. - */ - public String layerBelow() { - return layerBelow; - } - - /** - * Get the tracking animation duration multiplier. - * - * @return tracking animation duration multiplier - */ - public float trackingAnimationDurationMultiplier() { - return trackingAnimationDurationMultiplier; - } - - /** - * Enable or disable smooth animation of compass values for {@link com.mapbox.mapboxsdk.location.modes.CameraMode} - * and {@link com.mapbox.mapboxsdk.location.modes.RenderMode}. - * - * @return whether smooth compass animation is enabled - */ - public boolean compassAnimationEnabled() { - return compassAnimationEnabled; - } - - /** - * Enable or disable smooth animation of the accuracy circle around the user's position. - * - * @return whether smooth animation of the accuracy circle is enabled - */ - public boolean accuracyAnimationEnabled() { - return accuracyAnimationEnabled; - } - - @NonNull - @Override - public String toString() { - return "LocationComponentOptions{" - + "accuracyAlpha=" + accuracyAlpha + ", " - + "accuracyColor=" + accuracyColor + ", " - + "backgroundDrawableStale=" + backgroundDrawableStale + ", " - + "backgroundStaleName=" + backgroundStaleName + ", " - + "foregroundDrawableStale=" + foregroundDrawableStale + ", " - + "foregroundStaleName=" + foregroundStaleName + ", " - + "gpsDrawable=" + gpsDrawable + ", " - + "gpsName=" + gpsName + ", " - + "foregroundDrawable=" + foregroundDrawable + ", " - + "foregroundName=" + foregroundName + ", " - + "backgroundDrawable=" + backgroundDrawable + ", " - + "backgroundName=" + backgroundName + ", " - + "bearingDrawable=" + bearingDrawable + ", " - + "bearingName=" + bearingName + ", " - + "bearingTintColor=" + bearingTintColor + ", " - + "foregroundTintColor=" + foregroundTintColor + ", " - + "backgroundTintColor=" + backgroundTintColor + ", " - + "foregroundStaleTintColor=" + foregroundStaleTintColor + ", " - + "backgroundStaleTintColor=" + backgroundStaleTintColor + ", " - + "elevation=" + elevation + ", " - + "enableStaleState=" + enableStaleState + ", " - + "staleStateTimeout=" + staleStateTimeout + ", " - + "padding=" + Arrays.toString(padding) + ", " - + "maxZoomIconScale=" + maxZoomIconScale + ", " - + "minZoomIconScale=" + minZoomIconScale + ", " - + "trackingGesturesManagement=" + trackingGesturesManagement + ", " - + "trackingInitialMoveThreshold=" + trackingInitialMoveThreshold + ", " - + "trackingMultiFingerMoveThreshold=" + trackingMultiFingerMoveThreshold + ", " - + "layerAbove=" + layerAbove - + "layerBelow=" + layerBelow - + "trackingAnimationDurationMultiplier=" + trackingAnimationDurationMultiplier - + "}"; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - LocationComponentOptions options = (LocationComponentOptions) o; - - if (Float.compare(options.accuracyAlpha, accuracyAlpha) != 0) { - return false; - } - if (accuracyColor != options.accuracyColor) { - return false; - } - if (backgroundDrawableStale != options.backgroundDrawableStale) { - return false; - } - if (foregroundDrawableStale != options.foregroundDrawableStale) { - return false; - } - if (gpsDrawable != options.gpsDrawable) { - return false; - } - if (foregroundDrawable != options.foregroundDrawable) { - return false; - } - if (backgroundDrawable != options.backgroundDrawable) { - return false; - } - if (bearingDrawable != options.bearingDrawable) { - return false; - } - if (Float.compare(options.elevation, elevation) != 0) { - return false; - } - if (enableStaleState != options.enableStaleState) { - return false; - } - if (staleStateTimeout != options.staleStateTimeout) { - return false; - } - if (Float.compare(options.maxZoomIconScale, maxZoomIconScale) != 0) { - return false; - } - if (Float.compare(options.minZoomIconScale, minZoomIconScale) != 0) { - return false; - } - if (trackingGesturesManagement != options.trackingGesturesManagement) { - return false; - } - if (Float.compare(options.trackingInitialMoveThreshold, trackingInitialMoveThreshold) != 0) { - return false; - } - if (Float.compare(options.trackingMultiFingerMoveThreshold, trackingMultiFingerMoveThreshold) != 0) { - return false; - } - if (Float.compare(options.trackingAnimationDurationMultiplier, trackingAnimationDurationMultiplier) != 0) { - return false; - } - if (compassAnimationEnabled != options.compassAnimationEnabled) { - return false; - } - if (accuracyAnimationEnabled != options.accuracyAnimationEnabled) { - return false; - } - if (backgroundStaleName != null ? !backgroundStaleName.equals(options.backgroundStaleName) : - options.backgroundStaleName != null) { - return false; - } - if (foregroundStaleName != null ? !foregroundStaleName.equals(options.foregroundStaleName) : - options.foregroundStaleName != null) { - return false; - } - if (gpsName != null ? !gpsName.equals(options.gpsName) : options.gpsName != null) { - return false; - } - if (foregroundName != null ? !foregroundName.equals(options.foregroundName) : options.foregroundName != null) { - return false; - } - if (backgroundName != null ? !backgroundName.equals(options.backgroundName) : options.backgroundName != null) { - return false; - } - if (bearingName != null ? !bearingName.equals(options.bearingName) : options.bearingName != null) { - return false; - } - if (bearingTintColor != null ? !bearingTintColor.equals(options.bearingTintColor) : - options.bearingTintColor != null) { - return false; - } - if (foregroundTintColor != null ? !foregroundTintColor.equals(options.foregroundTintColor) : - options.foregroundTintColor != null) { - return false; - } - if (backgroundTintColor != null ? !backgroundTintColor.equals(options.backgroundTintColor) : - options.backgroundTintColor != null) { - return false; - } - if (foregroundStaleTintColor != null ? !foregroundStaleTintColor.equals(options.foregroundStaleTintColor) : - options.foregroundStaleTintColor != null) { - return false; - } - if (backgroundStaleTintColor != null ? !backgroundStaleTintColor.equals(options.backgroundStaleTintColor) : - options.backgroundStaleTintColor != null) { - return false; - } - if (!Arrays.equals(padding, options.padding)) { - return false; - } - if (layerAbove != null ? !layerAbove.equals(options.layerAbove) : options.layerAbove != null) { - return false; - } - return layerBelow != null ? layerBelow.equals(options.layerBelow) : options.layerBelow == null; - } - - @Override - public int hashCode() { - int result = (accuracyAlpha != +0.0f ? Float.floatToIntBits(accuracyAlpha) : 0); - result = 31 * result + accuracyColor; - result = 31 * result + backgroundDrawableStale; - result = 31 * result + (backgroundStaleName != null ? backgroundStaleName.hashCode() : 0); - result = 31 * result + foregroundDrawableStale; - result = 31 * result + (foregroundStaleName != null ? foregroundStaleName.hashCode() : 0); - result = 31 * result + gpsDrawable; - result = 31 * result + (gpsName != null ? gpsName.hashCode() : 0); - result = 31 * result + foregroundDrawable; - result = 31 * result + (foregroundName != null ? foregroundName.hashCode() : 0); - result = 31 * result + backgroundDrawable; - result = 31 * result + (backgroundName != null ? backgroundName.hashCode() : 0); - result = 31 * result + bearingDrawable; - result = 31 * result + (bearingName != null ? bearingName.hashCode() : 0); - result = 31 * result + (bearingTintColor != null ? bearingTintColor.hashCode() : 0); - result = 31 * result + (foregroundTintColor != null ? foregroundTintColor.hashCode() : 0); - result = 31 * result + (backgroundTintColor != null ? backgroundTintColor.hashCode() : 0); - result = 31 * result + (foregroundStaleTintColor != null ? foregroundStaleTintColor.hashCode() : 0); - result = 31 * result + (backgroundStaleTintColor != null ? backgroundStaleTintColor.hashCode() : 0); - result = 31 * result + (elevation != +0.0f ? Float.floatToIntBits(elevation) : 0); - result = 31 * result + (enableStaleState ? 1 : 0); - result = 31 * result + (int) (staleStateTimeout ^ (staleStateTimeout >>> 32)); - result = 31 * result + Arrays.hashCode(padding); - result = 31 * result + (maxZoomIconScale != +0.0f ? Float.floatToIntBits(maxZoomIconScale) : 0); - result = 31 * result + (minZoomIconScale != +0.0f ? Float.floatToIntBits(minZoomIconScale) : 0); - result = 31 * result + (trackingGesturesManagement ? 1 : 0); - result = 31 * result + (trackingInitialMoveThreshold != +0.0f - ? Float.floatToIntBits(trackingInitialMoveThreshold) : 0); - result = 31 * result + (trackingMultiFingerMoveThreshold != +0.0f - ? Float.floatToIntBits(trackingMultiFingerMoveThreshold) : 0); - result = 31 * result + (layerAbove != null ? layerAbove.hashCode() : 0); - result = 31 * result + (layerBelow != null ? layerBelow.hashCode() : 0); - result = 31 * result + (trackingAnimationDurationMultiplier != +0.0f - ? Float.floatToIntBits(trackingAnimationDurationMultiplier) : 0); - result = 31 * result + (compassAnimationEnabled ? 1 : 0); - result = 31 * result + (accuracyAnimationEnabled ? 1 : 0); - return result; - } - - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - @Override - public LocationComponentOptions createFromParcel(Parcel in) { - return new LocationComponentOptions( - in.readFloat(), - in.readInt(), - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt(), - in.readInt() == 0 ? in.readString() : null, - in.readInt() == 0 ? in.readInt() : null, - in.readInt() == 0 ? in.readInt() : null, - in.readInt() == 0 ? in.readInt() : null, - in.readInt() == 0 ? in.readInt() : null, - in.readInt() == 0 ? in.readInt() : null, - in.readFloat(), - in.readInt() == 1, - in.readLong(), - in.createIntArray(), - in.readFloat(), - in.readFloat(), - in.readInt() == 1, - in.readFloat(), - in.readFloat(), - in.readString(), - in.readString(), - in.readFloat(), - in.readInt() == 1, - in.readInt() == 1 - ); - } - - @Override - public LocationComponentOptions[] newArray(int size) { - return new LocationComponentOptions[size]; - } - }; - - @Override - public void writeToParcel(@NonNull Parcel dest, int flags) { - dest.writeFloat(accuracyAlpha()); - dest.writeInt(accuracyColor()); - dest.writeInt(backgroundDrawableStale()); - if (backgroundStaleName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(backgroundStaleName()); - } - dest.writeInt(foregroundDrawableStale()); - if (foregroundStaleName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(foregroundStaleName()); - } - dest.writeInt(gpsDrawable()); - if (gpsName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(gpsName()); - } - dest.writeInt(foregroundDrawable()); - if (foregroundName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(foregroundName()); - } - dest.writeInt(backgroundDrawable()); - if (backgroundName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(backgroundName()); - } - dest.writeInt(bearingDrawable()); - if (bearingName() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeString(bearingName()); - } - if (bearingTintColor() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeInt(bearingTintColor()); - } - if (foregroundTintColor() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeInt(foregroundTintColor()); - } - if (backgroundTintColor() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeInt(backgroundTintColor()); - } - if (foregroundStaleTintColor() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeInt(foregroundStaleTintColor()); - } - if (backgroundStaleTintColor() == null) { - dest.writeInt(1); - } else { - dest.writeInt(0); - dest.writeInt(backgroundStaleTintColor()); - } - dest.writeFloat(elevation()); - dest.writeInt(enableStaleState() ? 1 : 0); - dest.writeLong(staleStateTimeout()); - dest.writeIntArray(padding()); - dest.writeFloat(maxZoomIconScale()); - dest.writeFloat(minZoomIconScale()); - dest.writeInt(trackingGesturesManagement() ? 1 : 0); - dest.writeFloat(trackingInitialMoveThreshold()); - dest.writeFloat(trackingMultiFingerMoveThreshold()); - dest.writeString(layerAbove()); - dest.writeString(layerBelow()); - dest.writeFloat(trackingAnimationDurationMultiplier); - dest.writeInt(compassAnimationEnabled() ? 1 : 0); - dest.writeInt(accuracyAnimationEnabled() ? 1 : 0); - } - - @Override - public int describeContents() { - return 0; - } - - /** - * Builder class for constructing a new instance of {@link LocationComponentOptions}. - */ - public static class Builder { - - /** - * Build a new instance of this {@link LocationComponentOptions} class. - * - * @return a new instance of {@link LocationComponentOptions} - */ - @NonNull - public LocationComponentOptions build() { - LocationComponentOptions locationComponentOptions = autoBuild(); - if (locationComponentOptions.accuracyAlpha() < 0 || locationComponentOptions.accuracyAlpha() > 1) { - throw new IllegalArgumentException( - "Accuracy alpha value must be between 0.0 and 1.0."); - } - - if (locationComponentOptions.elevation() < 0f) { - throw new IllegalArgumentException("Invalid shadow size " - + locationComponentOptions.elevation() + ". Must be >= 0"); - } - - if (locationComponentOptions.layerAbove() != null && locationComponentOptions.layerBelow() != null) { - throw new IllegalArgumentException("You cannot set both layerAbove and layerBelow options." - + "Choose one or the other."); - } - - return locationComponentOptions; - } - - private Float accuracyAlpha; - private Integer accuracyColor; - private Integer backgroundDrawableStale; - @Nullable - private String backgroundStaleName; - private Integer foregroundDrawableStale; - @Nullable - private String foregroundStaleName; - private Integer gpsDrawable; - @Nullable - private String gpsName; - private Integer foregroundDrawable; - @Nullable - private String foregroundName; - private Integer backgroundDrawable; - @Nullable - private String backgroundName; - private Integer bearingDrawable; - @Nullable - private String bearingName; - @Nullable - private Integer bearingTintColor; - @Nullable - private Integer foregroundTintColor; - @Nullable - private Integer backgroundTintColor; - @Nullable - private Integer foregroundStaleTintColor; - @Nullable - private Integer backgroundStaleTintColor; - private Float elevation; - private Boolean enableStaleState; - private Long staleStateTimeout; - @Nullable - private int[] padding; - private Float maxZoomIconScale; - private Float minZoomIconScale; - private Boolean trackingGesturesManagement; - private Float trackingInitialMoveThreshold; - private Float trackingMultiFingerMoveThreshold; - private String layerAbove; - private String layerBelow; - private Float trackingAnimationDurationMultiplier; - private Boolean compassAnimationEnabled; - private Boolean accuracyAnimationEnabled; - - Builder() { - } - - private Builder(LocationComponentOptions source) { - this.accuracyAlpha = source.accuracyAlpha(); - this.accuracyColor = source.accuracyColor(); - this.backgroundDrawableStale = source.backgroundDrawableStale(); - this.backgroundStaleName = source.backgroundStaleName(); - this.foregroundDrawableStale = source.foregroundDrawableStale(); - this.foregroundStaleName = source.foregroundStaleName(); - this.gpsDrawable = source.gpsDrawable(); - this.gpsName = source.gpsName(); - this.foregroundDrawable = source.foregroundDrawable(); - this.foregroundName = source.foregroundName(); - this.backgroundDrawable = source.backgroundDrawable(); - this.backgroundName = source.backgroundName(); - this.bearingDrawable = source.bearingDrawable(); - this.bearingName = source.bearingName(); - this.bearingTintColor = source.bearingTintColor(); - this.foregroundTintColor = source.foregroundTintColor(); - this.backgroundTintColor = source.backgroundTintColor(); - this.foregroundStaleTintColor = source.foregroundStaleTintColor(); - this.backgroundStaleTintColor = source.backgroundStaleTintColor(); - this.elevation = source.elevation(); - this.enableStaleState = source.enableStaleState(); - this.staleStateTimeout = source.staleStateTimeout(); - this.padding = source.padding(); - this.maxZoomIconScale = source.maxZoomIconScale(); - this.minZoomIconScale = source.minZoomIconScale(); - this.trackingGesturesManagement = source.trackingGesturesManagement(); - this.trackingInitialMoveThreshold = source.trackingInitialMoveThreshold(); - this.trackingMultiFingerMoveThreshold = source.trackingMultiFingerMoveThreshold(); - this.layerAbove = source.layerAbove(); - this.layerBelow = source.layerBelow(); - this.trackingAnimationDurationMultiplier = source.trackingAnimationDurationMultiplier(); - this.compassAnimationEnabled = source.compassAnimationEnabled(); - this.accuracyAnimationEnabled = source.accuracyAnimationEnabled(); - } - - /** - * Set the opacity of the accuracy view to a value from 0 to 1, where 0 means the accuracy view - * is completely transparent and 1 means the view is completely opaque. - * References style attribute R.styleable#LocationComponent_accuracyAlpha - * - * @param accuracyAlpha the opacity of the accuracy view - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder accuracyAlpha(float accuracyAlpha) { - this.accuracyAlpha = accuracyAlpha; - return this; - } - - /** - * Solid color to use as the accuracy view color property. - * References style attribute R.styleable#LocationComponent_accuracyColor - * - * @param accuracyColor the color of the accuracy view - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder accuracyColor(int accuracyColor) { - this.accuracyColor = accuracyColor; - return this; - } - - /** - * Defines the drawable used for the stale background icon. - * References style attribute R.styleable#LocationComponent_backgroundDrawableStale - * - * @param backgroundDrawableStale the drawable resource ID - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundDrawableStale(int backgroundDrawableStale) { - this.backgroundDrawableStale = backgroundDrawableStale; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_backgroundDrawableStale. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param backgroundStaleName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundStaleName(@Nullable String backgroundStaleName) { - this.backgroundStaleName = backgroundStaleName; - return this; - } - - /** - * Defines the drawable used for the stale foreground icon. - * References style attribute R.styleable#LocationComponent_foregroundDrawableStale - * - * @param foregroundDrawableStale the drawable resource ID - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundDrawableStale(int foregroundDrawableStale) { - this.foregroundDrawableStale = foregroundDrawableStale; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_foregroundDrawableStale. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param foregroundStaleName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundStaleName(@Nullable String foregroundStaleName) { - this.foregroundStaleName = foregroundStaleName; - return this; - } - - /** - * Defines the drawable used for the navigation state icon. - * References style attribute R.styleable#LocationComponent_gpsDrawable - * - * @param gpsDrawable the drawable resource ID - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder gpsDrawable(int gpsDrawable) { - this.gpsDrawable = gpsDrawable; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_gpsDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param gpsName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder gpsName(@Nullable String gpsName) { - this.gpsName = gpsName; - return this; - } - - /** - * Supply a Drawable that is to be rendered on top of all of the content in the Location Component layer stack. - * References style attribute R.styleable#LocationComponent_foregroundDrawable - * - * @param foregroundDrawable the drawable resource used for the foreground layer - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundDrawable(int foregroundDrawable) { - this.foregroundDrawable = foregroundDrawable; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_foregroundDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param foregroundName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundName(@Nullable String foregroundName) { - this.foregroundName = foregroundName; - return this; - } - - /** - * Defines the drawable used for the background state icon. - * References style attribute R.styleable#LocationComponent_backgroundDrawable - * - * @param backgroundDrawable the drawable resource ID - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundDrawable(int backgroundDrawable) { - this.backgroundDrawable = backgroundDrawable; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_backgroundDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param backgroundName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundName(@Nullable String backgroundName) { - this.backgroundName = backgroundName; - return this; - } - - /** - * Defines the drawable used for the bearing icon. - * References style attribute R.styleable#LocationComponent_bearingDrawable - * - * @param bearingDrawable the drawable resource ID - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder bearingDrawable(int bearingDrawable) { - this.bearingDrawable = bearingDrawable; - return this; - } - - /** - * Given a String image name, identical to one used in - * the first parameter of {@link com.mapbox.mapboxsdk.maps.Style.Builder#addImage(String, Bitmap)}, the - * component, will used this image in place of the provided or default mapbox_bearingDrawable. - *

- * A maki-icon name (example: "circle-15") may also be provided. These are images that can be loaded - * with certain styles. Note, this will fail if the provided icon name is not provided by the loaded map style. - *

- * - * @param bearingName String icon or maki-icon name - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder bearingName(@Nullable String bearingName) { - this.bearingName = bearingName; - return this; - } - - /** - * Defines the bearing icon color as an integer. - * References style attribute R.styleable#LocationComponent_bearingTintColor - * - * @param bearingTintColor the color integer resource - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder bearingTintColor(@Nullable Integer bearingTintColor) { - this.bearingTintColor = bearingTintColor; - return this; - } - - /** - * Defines the foreground color as an integer. - * References style attribute R.styleable#LocationComponent_foregroundTintColor - * - * @param foregroundTintColor the color integer resource - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundTintColor(@Nullable Integer foregroundTintColor) { - this.foregroundTintColor = foregroundTintColor; - return this; - } - - /** - * Defines the background color as an integer. - * References style attribute R.styleable#LocationComponent_backgroundTintColor - * - * @param backgroundTintColor the color integer resource - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundTintColor(@Nullable Integer backgroundTintColor) { - this.backgroundTintColor = backgroundTintColor; - return this; - } - - /** - * Defines the foreground stale color as an integer. - * References style attribute R.styleable#LocationComponent_foregroundStaleTintColor - * - * @param foregroundStaleTintColor the color integer resource - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder foregroundStaleTintColor(@Nullable Integer foregroundStaleTintColor) { - this.foregroundStaleTintColor = foregroundStaleTintColor; - return this; - } - - /** - * Defines the background stale color as an integer. - * References style attribute R.styleable#LocationComponent_backgroundStaleTintColor - * - * @param backgroundStaleTintColor the color integer resource - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder backgroundStaleTintColor(@Nullable Integer backgroundStaleTintColor) { - this.backgroundStaleTintColor = backgroundStaleTintColor; - return this; - } - - /** - * Sets the base elevation of this view, in pixels. - * References style attribute R.styleable#LocationComponent_elevation - * - * @param elevation the elevation currently set for the location icon - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder elevation(float elevation) { - this.elevation = elevation; - return this; - } - - /** - * Enable or disable to stale state mode. This mode indicates to the user that the location - * being displayed on the map hasn't been updated in a specific amount of time. - * References style attribute R.styleable#LocationComponent_enableStaleState - * - * @param enabled whether the stale state mode is enabled or not - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder enableStaleState(boolean enabled) { - this.enableStaleState = enabled; - return this; - } - - /** - * Set the timeout before the location icon becomes stale. The timer begins approximately when a - * new location update comes in and using this defined time, if an update hasn't occurred by the - * end, the location is considered stale. - * References style attribute R.styleable#LocationComponent_staleStateTimeout - * - * @param timeout the duration in milliseconds which it should take before the location is - * considered stale - * @return this builder for chaining options together - */ - @NonNull - public LocationComponentOptions.Builder staleStateTimeout(long timeout) { - this.staleStateTimeout = timeout; - return this; - } - - /** - * Sets the distance from the edges of the map view’s frame to the edges of the map - * view’s logical viewport. - *

- *

- * 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 - * frame from the viewport. For instance, if the only the top edge is inset, the - * map center is effectively shifted downward. - *

- * - * @param padding The margins for the map in pixels (left, top, right, bottom). - * @deprecated Use {@link CameraPosition.Builder#padding(double, double, double, double)} - * or {@link CameraUpdateFactory#paddingTo(double, double, double, double)} instead. - */ - @NonNull - @Deprecated - public LocationComponentOptions.Builder padding(@Nullable int[] padding) { - if (padding == null) { - throw new NullPointerException("Null padding"); - } - this.padding = padding; - return this; - } - - /** - * Sets the scale factor of the location icon when the map is zoomed in. - * Scaling is linear and the new pixel size of the image will be the original pixel size multiplied by the argument. - *

- * Set both this and {@link #minZoomIconScale(float)} to 1f to disable location icon scaling. - *

- * Scaling is based on the maps minimum and maximum zoom levels in time of component's style application. - * - * @param maxZoomIconScale icon scale factor - */ - @NonNull - public LocationComponentOptions.Builder maxZoomIconScale(float maxZoomIconScale) { - this.maxZoomIconScale = maxZoomIconScale; - return this; - } - - /** - * Sets the scale factor of the location icon when the map is zoomed out. - * Scaling is linear and the new pixel size of the image will be the original pixel size multiplied by the argument. - *

- * Set both this and {@link #maxZoomIconScale(float)} to 1f to disable location icon scaling. - *

- * Scaling is based on the maps minimum and maximum zoom levels in time of component's style application. - * - * @param minZoomIconScale icon scale factor - */ - @NonNull - public LocationComponentOptions.Builder minZoomIconScale(float minZoomIconScale) { - this.minZoomIconScale = minZoomIconScale; - return this; - } - - /** - * Set whether gesture threshold should be adjusted when camera is in one of the tracking modes. - * This will adjust the focal point and increase thresholds to enable camera manipulation, - * like zooming in and out, without breaking tracking. - *

- * Note: This can overwrite some of the gesture thresholds - * and the custom {@link com.mapbox.android.gestures.AndroidGesturesManager} that was set with - * {@link com.mapbox.mapboxsdk.maps.MapboxMap#setGesturesManager(AndroidGesturesManager, boolean, boolean)}. - * - * @param trackingGesturesManagement true if gestures should be adjusted when in one of the camera tracking modes, - * false otherwise - * @see Builder#trackingInitialMoveThreshold(float) - * @see Builder#trackingMultiFingerMoveThreshold(float) - */ - @NonNull - public LocationComponentOptions.Builder trackingGesturesManagement(boolean trackingGesturesManagement) { - this.trackingGesturesManagement = trackingGesturesManagement; - return this; - } - - /** - * Sets minimum single pointer movement (map pan) in pixels required to break camera tracking. - * - * @param moveThreshold the minimum movement - */ - @NonNull - public LocationComponentOptions.Builder trackingInitialMoveThreshold(float moveThreshold) { - this.trackingInitialMoveThreshold = moveThreshold; - return this; - } - - /** - * Sets minimum multi pointer movement (map pan) in pixels required to break camera tracking - * (for example during scale gesture). - * - * @param moveThreshold the minimum movement - */ - @NonNull - public LocationComponentOptions.Builder trackingMultiFingerMoveThreshold(float moveThreshold) { - this.trackingMultiFingerMoveThreshold = moveThreshold; - return this; - } - - /** - * Sets the id of the layer that's referenced when placing the component on the map using - * {@link com.mapbox.mapboxsdk.maps.Style#addLayerAbove(Layer, String)}. - *

- * The component is going to placed directly above this layer. - * - * @param layerAbove the id of the layer the component is going to placed directly above. - */ - @NonNull - public LocationComponentOptions.Builder layerAbove(String layerAbove) { - this.layerAbove = layerAbove; - return this; - } - - /** - * Sets the id of the layer that's referenced when placing the component on the map using - * {@link com.mapbox.mapboxsdk.maps.Style#addLayerBelow(Layer, String)}. - *

- * The component is going to placed directly below this layer. - * - * @param layerBelow the id of the layer the component is going to placed directly below. - */ - @NonNull - public LocationComponentOptions.Builder layerBelow(String layerBelow) { - this.layerBelow = layerBelow; - return this; - } - - /** - * Sets the tracking animation duration multiplier. - * - * @param trackingAnimationDurationMultiplier the tracking animation duration multiplier - */ - @NonNull - public LocationComponentOptions.Builder trackingAnimationDurationMultiplier( - float trackingAnimationDurationMultiplier) { - this.trackingAnimationDurationMultiplier = trackingAnimationDurationMultiplier; - return this; - } - - /** - * Enable or disable smooth animation of compass values for {@link com.mapbox.mapboxsdk.location.modes.CameraMode} - * and {@link com.mapbox.mapboxsdk.location.modes.RenderMode}. - * - * @return whether smooth compass animation is enabled - */ - public LocationComponentOptions.Builder compassAnimationEnabled(Boolean compassAnimationEnabled) { - this.compassAnimationEnabled = compassAnimationEnabled; - return this; - } - - /** - * Enable or disable smooth animation of the accuracy circle around the user's position. - * - * @return whether smooth animation of the accuracy circle is enabled - */ - public Builder accuracyAnimationEnabled(Boolean accuracyAnimationEnabled) { - this.accuracyAnimationEnabled = accuracyAnimationEnabled; - return this; - } - - @Nullable - LocationComponentOptions autoBuild() { - String missing = ""; - if (this.accuracyAlpha == null) { - missing += " accuracyAlpha"; - } - if (this.accuracyColor == null) { - missing += " accuracyColor"; - } - if (this.backgroundDrawableStale == null) { - missing += " backgroundDrawableStale"; - } - if (this.foregroundDrawableStale == null) { - missing += " foregroundDrawableStale"; - } - if (this.gpsDrawable == null) { - missing += " gpsDrawable"; - } - if (this.foregroundDrawable == null) { - missing += " foregroundDrawable"; - } - if (this.backgroundDrawable == null) { - missing += " backgroundDrawable"; - } - if (this.bearingDrawable == null) { - missing += " bearingDrawable"; - } - if (this.elevation == null) { - missing += " elevation"; - } - if (this.enableStaleState == null) { - missing += " enableStaleState"; - } - if (this.staleStateTimeout == null) { - missing += " staleStateTimeout"; - } - if (this.padding == null) { - missing += " padding"; - } - if (this.maxZoomIconScale == null) { - missing += " maxZoomIconScale"; - } - if (this.minZoomIconScale == null) { - missing += " minZoomIconScale"; - } - if (this.trackingGesturesManagement == null) { - missing += " trackingGesturesManagement"; - } - if (this.trackingInitialMoveThreshold == null) { - missing += " trackingInitialMoveThreshold"; - } - if (this.trackingMultiFingerMoveThreshold == null) { - missing += " trackingMultiFingerMoveThreshold"; - } - if (this.trackingAnimationDurationMultiplier == null) { - missing += " trackingAnimationDurationMultiplier"; - } - if (!missing.isEmpty()) { - throw new IllegalStateException("Missing required properties:" + missing); - } - return new LocationComponentOptions( - this.accuracyAlpha, - this.accuracyColor, - this.backgroundDrawableStale, - this.backgroundStaleName, - this.foregroundDrawableStale, - this.foregroundStaleName, - this.gpsDrawable, - this.gpsName, - this.foregroundDrawable, - this.foregroundName, - this.backgroundDrawable, - this.backgroundName, - this.bearingDrawable, - this.bearingName, - this.bearingTintColor, - this.foregroundTintColor, - this.backgroundTintColor, - this.foregroundStaleTintColor, - this.backgroundStaleTintColor, - this.elevation, - this.enableStaleState, - this.staleStateTimeout, - this.padding, - this.maxZoomIconScale, - this.minZoomIconScale, - trackingGesturesManagement, - this.trackingInitialMoveThreshold, - this.trackingMultiFingerMoveThreshold, - this.layerAbove, - this.layerBelow, - this.trackingAnimationDurationMultiplier, - this.compassAnimationEnabled, - this.accuracyAnimationEnabled); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManager.java deleted file mode 100644 index f2e4d0bb4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManager.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.maps.Style; -import com.mapbox.mapboxsdk.style.layers.Layer; - -class LocationComponentPositionManager { - - @NonNull - private final Style style; - - @Nullable - private String layerAbove; - - @Nullable - private String layerBelow; - - LocationComponentPositionManager(@NonNull Style style, @Nullable String layerAbove, @Nullable String layerBelow) { - this.style = style; - this.layerAbove = layerAbove; - this.layerBelow = layerBelow; - } - - /** - * Returns true whenever layer above/below configuration has changed and requires re-layout. - */ - boolean update(@Nullable String layerAbove, @Nullable String layerBelow) { - boolean requiresUpdate = - !(this.layerAbove == layerAbove || (this.layerAbove != null && this.layerAbove.equals(layerAbove))) - || !(this.layerBelow == layerBelow || (this.layerBelow != null && this.layerBelow.equals(layerBelow))); - - this.layerAbove = layerAbove; - this.layerBelow = layerBelow; - return requiresUpdate; - } - - void addLayerToMap(@NonNull Layer layer) { - if (layerAbove != null) { - style.addLayerAbove(layer, layerAbove); - } else if (layerBelow != null) { - style.addLayerBelow(layer, layerBelow); - } else { - style.addLayer(layer); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationLayerController.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationLayerController.java deleted file mode 100644 index 54f8ee6d1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/LocationLayerController.java +++ /dev/null @@ -1,464 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.support.annotation.ColorInt; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.VisibleForTesting; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.mapbox.geojson.Feature; -import com.mapbox.geojson.Point; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.location.modes.RenderMode; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Style; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.layers.SymbolLayer; -import com.mapbox.mapboxsdk.style.sources.GeoJsonSource; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.ACCURACY_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.LOCATION_SOURCE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_ALPHA; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_COLOR; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_RADIUS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BACKGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BACKGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_BEARING_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_LOCATION_STALE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_SHADOW_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_LAYER; -import static com.mapbox.mapboxsdk.style.expressions.Expression.interpolate; -import static com.mapbox.mapboxsdk.style.expressions.Expression.linear; -import static com.mapbox.mapboxsdk.style.expressions.Expression.stop; -import static com.mapbox.mapboxsdk.style.expressions.Expression.zoom; -import static com.mapbox.mapboxsdk.style.layers.Property.NONE; -import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconSize; -import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility; -import static com.mapbox.mapboxsdk.utils.ColorUtils.colorToRgbaString; - -final class LocationLayerController { - - @RenderMode.Mode - private int renderMode; - - private final MapboxMap mapboxMap; - private Style style; - private final LayerSourceProvider layerSourceProvider; - private final LayerBitmapProvider bitmapProvider; - private LocationComponentOptions options; - private final OnRenderModeChangedListener internalRenderModeChangedListener; - - @VisibleForTesting - final Set layerSet = new HashSet<>(); - private Feature locationFeature; - private GeoJsonSource locationSource; - - private boolean isHidden = true; - - private LocationComponentPositionManager positionManager; - - LocationLayerController(MapboxMap mapboxMap, Style style, LayerSourceProvider layerSourceProvider, - LayerFeatureProvider featureProvider, LayerBitmapProvider bitmapProvider, - @NonNull LocationComponentOptions options, - @NonNull OnRenderModeChangedListener internalRenderModeChangedListener) { - this.mapboxMap = mapboxMap; - this.style = style; - this.layerSourceProvider = layerSourceProvider; - this.bitmapProvider = bitmapProvider; - this.locationFeature = featureProvider.generateLocationFeature(locationFeature, options); - this.internalRenderModeChangedListener = internalRenderModeChangedListener; - initializeComponents(style, options); - } - - void initializeComponents(Style style, LocationComponentOptions options) { - this.style = style; - this.positionManager = new LocationComponentPositionManager(style, options.layerAbove(), options.layerBelow()); - addLocationSource(); - addLayers(); - applyStyle(options); - - if (isHidden) { - hide(); - } else { - show(); - } - } - - void applyStyle(@NonNull LocationComponentOptions options) { - if (positionManager.update(options.layerAbove(), options.layerBelow())) { - removeLayers(); - addLayers(); - if (isHidden) { - hide(); - } - } - - this.options = options; - - float elevation = options.elevation(); - // Only add icon elevation if the values greater than 0. - if (elevation > 0) { - styleShadow(options); - } - styleForeground(options); - styleBackground(options); - styleBearing(options); - styleAccuracy(options.accuracyAlpha(), options.accuracyColor()); - styleScaling(options); - determineIconsSource(options); - - if (!isHidden) { - show(); - } - } - - void setRenderMode(@RenderMode.Mode int renderMode) { - if (this.renderMode == renderMode) { - return; - } - this.renderMode = renderMode; - - styleForeground(options); - determineIconsSource(options); - if (!isHidden) { - show(); - } - internalRenderModeChangedListener.onRenderModeChanged(renderMode); - } - - int getRenderMode() { - return renderMode; - } - - // - // Layer action - // - - void show() { - isHidden = false; - boolean isStale = locationFeature.getBooleanProperty(PROPERTY_LOCATION_STALE); - switch (renderMode) { - case RenderMode.NORMAL: - setLayerVisibility(SHADOW_LAYER, true); - setLayerVisibility(FOREGROUND_LAYER, true); - setLayerVisibility(BACKGROUND_LAYER, true); - setLayerVisibility(ACCURACY_LAYER, !isStale); - setLayerVisibility(BEARING_LAYER, false); - break; - case RenderMode.COMPASS: - setLayerVisibility(SHADOW_LAYER, true); - setLayerVisibility(FOREGROUND_LAYER, true); - setLayerVisibility(BACKGROUND_LAYER, true); - setLayerVisibility(ACCURACY_LAYER, !isStale); - setLayerVisibility(BEARING_LAYER, true); - break; - case RenderMode.GPS: - setLayerVisibility(SHADOW_LAYER, false); - setLayerVisibility(FOREGROUND_LAYER, true); - setLayerVisibility(BACKGROUND_LAYER, true); - setLayerVisibility(ACCURACY_LAYER, false); - setLayerVisibility(BEARING_LAYER, false); - break; - default: - break; - } - } - - void hide() { - isHidden = true; - for (String layerId : layerSet) { - setLayerVisibility(layerId, false); - } - } - - void updateForegroundOffset(double tilt) { - JsonArray foregroundJsonArray = new JsonArray(); - foregroundJsonArray.add(0f); - foregroundJsonArray.add((float) (-0.05 * tilt)); - locationFeature.addProperty(PROPERTY_FOREGROUND_ICON_OFFSET, foregroundJsonArray); - - JsonArray backgroundJsonArray = new JsonArray(); - backgroundJsonArray.add(0f); - backgroundJsonArray.add((float) (0.05 * tilt)); - locationFeature.addProperty(PROPERTY_SHADOW_ICON_OFFSET, backgroundJsonArray); - - refreshSource(); - } - - void updateForegroundBearing(float bearing) { - if (renderMode != RenderMode.GPS) { - setBearingProperty(PROPERTY_GPS_BEARING, bearing); - } - } - - boolean isHidden() { - return isHidden; - } - - boolean isConsumingCompass() { - return renderMode == RenderMode.COMPASS; - } - - private void setLayerVisibility(@NonNull String layerId, boolean visible) { - Layer layer = style.getLayer(layerId); - if (layer != null) { - String targetVisibility = visible ? VISIBLE : NONE; - if (!layer.getVisibility().value.equals(targetVisibility)) { - layer.setProperties(visibility(visible ? VISIBLE : NONE)); - } - } - } - - private void addLayers() { - // positions the top-most reference layer - Layer layer = layerSourceProvider.generateLayer(BEARING_LAYER); - positionManager.addLayerToMap(layer); - layerSet.add(layer.getId()); - - // adds remaining layers while keeping the order - addSymbolLayer(FOREGROUND_LAYER, BEARING_LAYER); - addSymbolLayer(BACKGROUND_LAYER, FOREGROUND_LAYER); - addSymbolLayer(SHADOW_LAYER, BACKGROUND_LAYER); - addAccuracyLayer(); - } - - private void addSymbolLayer(@NonNull String layerId, @NonNull String beforeLayerId) { - Layer layer = layerSourceProvider.generateLayer(layerId); - addLayerToMap(layer, beforeLayerId); - } - - private void addAccuracyLayer() { - Layer accuracyLayer = layerSourceProvider.generateAccuracyLayer(); - addLayerToMap(accuracyLayer, BACKGROUND_LAYER); - } - - private void addLayerToMap(Layer layer, @NonNull String idBelowLayer) { - style.addLayerBelow(layer, idBelowLayer); - layerSet.add(layer.getId()); - } - - private void removeLayers() { - for (String layerId : layerSet) { - style.removeLayer(layerId); - } - layerSet.clear(); - } - - private void setBearingProperty(@NonNull String propertyId, float bearing) { - locationFeature.addNumberProperty(propertyId, bearing); - refreshSource(); - } - - private void updateAccuracyRadius(float accuracy) { - locationFeature.addNumberProperty(PROPERTY_ACCURACY_RADIUS, accuracy); - refreshSource(); - } - - // - // Source actions - // - - private void addLocationSource() { - locationSource = layerSourceProvider.generateSource(locationFeature); - style.addSource(locationSource); - } - - private void refreshSource() { - GeoJsonSource source = style.getSourceAs(LOCATION_SOURCE); - if (source != null) { - locationSource.setGeoJson(locationFeature); - } - } - - private void setLocationPoint(Point locationPoint) { - JsonObject properties = locationFeature.properties(); - if (properties != null) { - locationFeature = Feature.fromGeometry(locationPoint, properties); - refreshSource(); - } - } - - // - // Styling - // - - private void styleBackground(LocationComponentOptions options) { - Bitmap backgroundBitmap = bitmapProvider.generateBitmap( - options.backgroundDrawable(), options.backgroundTintColor() - ); - Bitmap backgroundStaleBitmap = bitmapProvider.generateBitmap( - options.backgroundDrawableStale(), options.backgroundStaleTintColor() - ); - style.addImage(BACKGROUND_ICON, backgroundBitmap); - style.addImage(BACKGROUND_STALE_ICON, backgroundStaleBitmap); - } - - private void styleShadow(@NonNull LocationComponentOptions options) { - style.addImage(SHADOW_ICON, bitmapProvider.generateShadowBitmap(options)); - } - - private void styleBearing(LocationComponentOptions options) { - Bitmap bearingBitmap = bitmapProvider.generateBitmap(options.bearingDrawable(), options.bearingTintColor()); - style.addImage(BEARING_ICON, bearingBitmap); - } - - private void styleAccuracy(float accuracyAlpha, @ColorInt int accuracyColor) { - locationFeature.addNumberProperty(PROPERTY_ACCURACY_ALPHA, accuracyAlpha); - locationFeature.addStringProperty(PROPERTY_ACCURACY_COLOR, colorToRgbaString(accuracyColor)); - refreshSource(); - } - - private void styleForeground(LocationComponentOptions options) { - Bitmap foregroundBitmap = bitmapProvider.generateBitmap( - options.foregroundDrawable(), options.foregroundTintColor() - ); - Bitmap foregroundBitmapStale = bitmapProvider.generateBitmap( - options.foregroundDrawableStale(), options.foregroundStaleTintColor() - ); - if (renderMode == RenderMode.GPS) { - foregroundBitmap = bitmapProvider.generateBitmap( - options.gpsDrawable(), options.foregroundTintColor() - ); - foregroundBitmapStale = bitmapProvider.generateBitmap( - options.gpsDrawable(), options.foregroundStaleTintColor() - ); - } - style.addImage(FOREGROUND_ICON, foregroundBitmap); - style.addImage(FOREGROUND_STALE_ICON, foregroundBitmapStale); - } - - private void styleScaling(@NonNull LocationComponentOptions options) { - for (String layerId : layerSet) { - Layer layer = style.getLayer(layerId); - if (layer instanceof SymbolLayer) { - layer.setProperties( - iconSize( - interpolate(linear(), zoom(), - stop(mapboxMap.getMinZoomLevel(), options.minZoomIconScale()), - stop(mapboxMap.getMaxZoomLevel(), options.maxZoomIconScale()) - ) - ) - ); - } - } - } - - private void determineIconsSource(LocationComponentOptions options) { - String foregroundIconString = buildIconString( - renderMode == RenderMode.GPS ? options.gpsName() : options.foregroundName(), FOREGROUND_ICON); - String foregroundStaleIconString = buildIconString(options.foregroundStaleName(), FOREGROUND_STALE_ICON); - String backgroundIconString = buildIconString(options.backgroundName(), BACKGROUND_ICON); - String backgroundStaleIconString = buildIconString(options.backgroundStaleName(), BACKGROUND_STALE_ICON); - String bearingIconString = buildIconString(options.bearingName(), BEARING_ICON); - - locationFeature.addStringProperty(PROPERTY_FOREGROUND_ICON, foregroundIconString); - locationFeature.addStringProperty(PROPERTY_BACKGROUND_ICON, backgroundIconString); - locationFeature.addStringProperty(PROPERTY_FOREGROUND_STALE_ICON, foregroundStaleIconString); - locationFeature.addStringProperty(PROPERTY_BACKGROUND_STALE_ICON, backgroundStaleIconString); - locationFeature.addStringProperty(PROPERTY_BEARING_ICON, bearingIconString); - refreshSource(); - } - - @NonNull - private String buildIconString(@Nullable String bitmapName, @NonNull String drawableName) { - if (bitmapName != null) { - return bitmapName; - } - return drawableName; - } - - void setLocationsStale(boolean isStale) { - locationFeature.addBooleanProperty(PROPERTY_LOCATION_STALE, isStale); - refreshSource(); - if (renderMode != RenderMode.GPS) { - setLayerVisibility(ACCURACY_LAYER, !isStale); - } - } - - // - // Map click event - // - - boolean onMapClick(@NonNull LatLng point) { - PointF screenLoc = mapboxMap.getProjection().toScreenLocation(point); - List features = mapboxMap.queryRenderedFeatures(screenLoc, - BACKGROUND_LAYER, - FOREGROUND_LAYER, - BEARING_LAYER - ); - return !features.isEmpty(); - } - - private final MapboxAnimator.AnimationsValueChangeListener latLngValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(LatLng value) { - Point point = Point.fromLngLat(value.getLongitude(), value.getLatitude()); - setLocationPoint(point); - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener gpsBearingValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - setBearingProperty(PROPERTY_GPS_BEARING, value); - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener compassBearingValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - setBearingProperty(PROPERTY_COMPASS_BEARING, value); - } - }; - - private final MapboxAnimator.AnimationsValueChangeListener accuracyValueListener = - new MapboxAnimator.AnimationsValueChangeListener() { - @Override - public void onNewAnimationValue(Float value) { - updateAccuracyRadius(value); - } - }; - - Set getAnimationListeners() { - Set holders = new HashSet<>(); - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_LAYER_LATLNG, latLngValueListener)); - - if (renderMode == RenderMode.GPS) { - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING, gpsBearingValueListener)); - } else if (renderMode == RenderMode.COMPASS) { - holders.add( - new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING, compassBearingValueListener)); - } - - if (renderMode == RenderMode.COMPASS || renderMode == RenderMode.NORMAL) { - holders.add(new AnimatorListenerHolder(MapboxAnimator.ANIMATOR_LAYER_ACCURACY, accuracyValueListener)); - } - - return holders; - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimator.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimator.java deleted file mode 100644 index dff7369cd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimator.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.animation.TypeEvaluator; -import android.animation.ValueAnimator; -import android.support.annotation.IntDef; -import android.support.annotation.NonNull; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Abstract class for all of the location component animators. - * - * @param Data type that will be animated. - */ -abstract class MapboxAnimator extends ValueAnimator implements ValueAnimator.AnimatorUpdateListener { - @Retention(RetentionPolicy.SOURCE) - @IntDef( { - ANIMATOR_LAYER_LATLNG, - ANIMATOR_CAMERA_LATLNG, - ANIMATOR_LAYER_GPS_BEARING, - ANIMATOR_LAYER_COMPASS_BEARING, - ANIMATOR_CAMERA_GPS_BEARING, - ANIMATOR_CAMERA_COMPASS_BEARING, - ANIMATOR_LAYER_ACCURACY, - ANIMATOR_ZOOM, - ANIMATOR_TILT - }) - @interface Type { - } - - static final int ANIMATOR_LAYER_LATLNG = 0; - static final int ANIMATOR_CAMERA_LATLNG = 1; - static final int ANIMATOR_LAYER_GPS_BEARING = 2; - static final int ANIMATOR_LAYER_COMPASS_BEARING = 3; - static final int ANIMATOR_CAMERA_GPS_BEARING = 4; - static final int ANIMATOR_CAMERA_COMPASS_BEARING = 5; - static final int ANIMATOR_LAYER_ACCURACY = 6; - static final int ANIMATOR_ZOOM = 7; - static final int ANIMATOR_TILT = 8; - - private final AnimationsValueChangeListener updateListener; - private final K target; - private K animatedValue; - - private final double minUpdateInterval; - private long timeElapsed; - - MapboxAnimator(@NonNull K previous, @NonNull K target, @NonNull AnimationsValueChangeListener updateListener, - int maxAnimationFps) { - minUpdateInterval = 1E9 / maxAnimationFps; - setObjectValues(previous, target); - setEvaluator(provideEvaluator()); - this.updateListener = updateListener; - this.target = target; - addUpdateListener(this); - addListener(new AnimatorListener()); - } - - @Override - public void onAnimationUpdate(ValueAnimator animation) { - animatedValue = (K) animation.getAnimatedValue(); - - long currentTime = System.nanoTime(); - if ((currentTime - timeElapsed) < minUpdateInterval) { - return; - } - - postUpdates(); - timeElapsed = currentTime; - } - - private class AnimatorListener extends AnimatorListenerAdapter { - @Override - public void onAnimationEnd(Animator animation) { - postUpdates(); - } - } - - private void postUpdates() { - updateListener.onNewAnimationValue(animatedValue); - } - - K getTarget() { - return target; - } - - abstract TypeEvaluator provideEvaluator(); - - interface AnimationsValueChangeListener { - void onNewAnimationValue(K value); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorProvider.java deleted file mode 100644 index 938f4ec74..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -final class MapboxAnimatorProvider { - - private static MapboxAnimatorProvider INSTANCE; - - private MapboxAnimatorProvider() { - // private constructor - } - - public static MapboxAnimatorProvider getInstance() { - if (INSTANCE == null) { - INSTANCE = new MapboxAnimatorProvider(); - } - return INSTANCE; - } - - MapboxLatLngAnimator latLngAnimator(LatLng previous, LatLng target, - MapboxAnimator.AnimationsValueChangeListener updateListener, - int maxAnimationFps) { - return new MapboxLatLngAnimator(previous, target, updateListener, maxAnimationFps); - } - - MapboxFloatAnimator floatAnimator(Float previous, Float target, - MapboxAnimator.AnimationsValueChangeListener updateListener, - int maxAnimationFps) { - return new MapboxFloatAnimator(previous, target, updateListener, maxAnimationFps); - } - - MapboxCameraAnimatorAdapter cameraAnimator(Float previous, Float target, - MapboxAnimator.AnimationsValueChangeListener updateListener, - @Nullable MapboxMap.CancelableCallback cancelableCallback) { - return new MapboxCameraAnimatorAdapter(previous, target, updateListener, cancelableCallback); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorSetProvider.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorSetProvider.java deleted file mode 100644 index 1d09f8ae7..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxAnimatorSetProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.Animator; -import android.animation.AnimatorSet; -import android.support.annotation.NonNull; -import android.view.animation.Interpolator; - -import java.util.List; - -class MapboxAnimatorSetProvider { - private static MapboxAnimatorSetProvider instance; - - private MapboxAnimatorSetProvider() { - // private constructor - } - - static MapboxAnimatorSetProvider getInstance() { - if (instance == null) { - instance = new MapboxAnimatorSetProvider(); - } - return instance; - } - - void startAnimation(@NonNull List animators, @NonNull Interpolator interpolator, - long duration) { - AnimatorSet locationAnimatorSet = new AnimatorSet(); - locationAnimatorSet.playTogether(animators); - locationAnimatorSet.setInterpolator(interpolator); - locationAnimatorSet.setDuration(duration); - locationAnimatorSet.start(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxCameraAnimatorAdapter.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxCameraAnimatorAdapter.java deleted file mode 100644 index 24bb82a2d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxCameraAnimatorAdapter.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.maps.MapboxMap; - -class MapboxCameraAnimatorAdapter extends MapboxFloatAnimator { - @Nullable - private final MapboxMap.CancelableCallback cancelableCallback; - - MapboxCameraAnimatorAdapter(Float previous, Float target, - AnimationsValueChangeListener updateListener, - @Nullable MapboxMap.CancelableCallback cancelableCallback) { - super(previous, target, updateListener, Integer.MAX_VALUE); - this.cancelableCallback = cancelableCallback; - addListener(new MapboxAnimatorListener()); - } - - private final class MapboxAnimatorListener extends AnimatorListenerAdapter { - @Override - public void onAnimationCancel(Animator animation) { - if (cancelableCallback != null) { - cancelableCallback.onCancel(); - } - } - - @Override - public void onAnimationEnd(Animator animation) { - if (cancelableCallback != null) { - cancelableCallback.onFinish(); - } - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxFloatAnimator.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxFloatAnimator.java deleted file mode 100644 index d7d518bc8..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxFloatAnimator.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.FloatEvaluator; -import android.animation.TypeEvaluator; -import android.support.annotation.NonNull; - -class MapboxFloatAnimator extends MapboxAnimator { - MapboxFloatAnimator(Float previous, Float target, AnimationsValueChangeListener updateListener, int maxAnimationFps) { - super(previous, target, updateListener, maxAnimationFps); - } - - @NonNull - @Override - TypeEvaluator provideEvaluator() { - return new FloatEvaluator(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxLatLngAnimator.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxLatLngAnimator.java deleted file mode 100644 index 507069114..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/MapboxLatLngAnimator.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.animation.TypeEvaluator; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -class MapboxLatLngAnimator extends MapboxAnimator { - - MapboxLatLngAnimator(LatLng previous, LatLng target, AnimationsValueChangeListener updateListener, - int maxAnimationFps) { - super(previous, target, updateListener, maxAnimationFps); - } - - @NonNull - @Override - TypeEvaluator provideEvaluator() { - return new LatLngEvaluator(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraMoveInvalidateListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraMoveInvalidateListener.java deleted file mode 100644 index 6594e543f..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraMoveInvalidateListener.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -interface OnCameraMoveInvalidateListener { - - void onInvalidateCameraMove(); - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraTrackingChangedListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraTrackingChangedListener.java deleted file mode 100644 index 1ea80d26a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnCameraTrackingChangedListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import com.mapbox.mapboxsdk.location.modes.CameraMode; - -/** - * Listener that gets invoked when camera tracking state changes. - */ -public interface OnCameraTrackingChangedListener { - /** - * Invoked whenever camera tracking is broken. - * This callback gets invoked just after {@link #onCameraTrackingChanged(int)}, if needed. - */ - void onCameraTrackingDismissed(); - - /** - * Invoked on every {@link CameraMode} change. - * - * @param currentMode current active {@link CameraMode}. - */ - void onCameraTrackingChanged(@CameraMode.Mode int currentMode); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationCameraTransitionListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationCameraTransitionListener.java deleted file mode 100644 index 824432efc..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationCameraTransitionListener.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import com.mapbox.mapboxsdk.location.modes.CameraMode; - -/** - * Callback for {@link CameraMode } transition state. - */ -public interface OnLocationCameraTransitionListener { - /** - * Invoked when the camera mode transition animation has been finished. - * - * @param cameraMode camera mode change that initiated the transition - */ - void onLocationCameraTransitionFinished(@CameraMode.Mode int cameraMode); - - /** - * Invoked when the camera mode transition animation has been canceled. - *

- * The camera mode is set regardless of the cancellation of the transition animation. - * - * @param cameraMode camera mode change that initiated the transition - */ - void onLocationCameraTransitionCanceled(@CameraMode.Mode int cameraMode); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationClickListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationClickListener.java deleted file mode 100644 index fdd2aeb81..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationClickListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -/** - * The Location Component exposes an API for listening to when the user clicks on the location - * layer icon visible on the map. When this event occurs, the {@link #onLocationComponentClick()} method - * gets invoked. - */ -public interface OnLocationClickListener { - - /** - * Called whenever user clicks on the location layer drawn on the map. - */ - void onLocationComponentClick(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationLongClickListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationLongClickListener.java deleted file mode 100644 index 0c34614f3..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationLongClickListener.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -/** - * The Location Component exposes an API for listening to when the user long clicks on the location - * layer icon visible on the map. when this event occurs, the {@link #onLocationComponentLongClick()} method - * gets invoked. - */ -public interface OnLocationLongClickListener { - - /** - * Called whenever user long clicks on the location layer drawn on the map. - */ - void onLocationComponentLongClick(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationStaleListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationStaleListener.java deleted file mode 100644 index 6bbe7f34b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnLocationStaleListener.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -/** - * Listener that can be added as a callback when the last location update - * is considered stale. - *

- * The time from the last location update that determines if a location update - * is stale or not is provided by {@link LocationComponentOptions#staleStateTimeout()}. - */ -public interface OnLocationStaleListener { - - /** - * Called when the stale state changes. - * @param isStale true if location is stale, false otherwise - */ - void onStaleStateChange(boolean isStale); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnRenderModeChangedListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnRenderModeChangedListener.java deleted file mode 100644 index 12ac220c5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/OnRenderModeChangedListener.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import com.mapbox.mapboxsdk.location.modes.RenderMode; - -/** - * Listener that gets invoked when layer render mode changes. - */ -public interface OnRenderModeChangedListener { - - /** - * Invoked on every {@link RenderMode} change. - * - * @param currentMode current active {@link RenderMode}. - */ - void onRenderModeChanged(@RenderMode.Mode int currentMode); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/StaleStateManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/StaleStateManager.java deleted file mode 100644 index 74c2e3a73..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/StaleStateManager.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.os.Handler; -import android.os.Message; -import android.support.annotation.NonNull; - -import java.lang.ref.WeakReference; - -/** - * Class controls the location stale state when the {@link android.location.Location} hasn't - * been updated in 'x' amount of time. {@link LocationComponentOptions#staleStateTimeout()} can be used to - * control the amount of time before the location's considered stale. - * {@link LocationComponentOptions#enableStaleState()} is available for disabling this behaviour. - */ -class StaleStateManager { - - private boolean isEnabled; - private final OnLocationStaleListener innerOnLocationStaleListeners; - @NonNull - private final StaleMessageHandler handler; - private boolean isStale = true; - private long delayTime; - - private final int staleStateMessage = 1; - - StaleStateManager(OnLocationStaleListener innerListener, LocationComponentOptions options) { - innerOnLocationStaleListeners = innerListener; - handler = new StaleMessageHandler(this); - isEnabled = options.enableStaleState(); - delayTime = options.staleStateTimeout(); - } - - void setEnabled(boolean enabled) { - if (enabled) { - setState(isStale); - } else if (isEnabled) { - onStop(); - innerOnLocationStaleListeners.onStaleStateChange(false); - } - isEnabled = enabled; - } - - boolean isStale() { - return isStale; - } - - void updateLatestLocationTime() { - setState(false); - postTheCallback(); - } - - void setDelayTime(long delayTime) { - this.delayTime = delayTime; - if (handler.hasMessages(staleStateMessage)) { - postTheCallback(); - } - } - - void onStart() { - if (!isStale) { - postTheCallback(); - } - } - - void onStop() { - handler.removeCallbacksAndMessages(null); - } - - private void postTheCallback() { - handler.removeCallbacksAndMessages(null); - handler.sendEmptyMessageDelayed(staleStateMessage, delayTime); - } - - private void setState(boolean stale) { - if (stale != isStale) { - isStale = stale; - if (isEnabled) { - innerOnLocationStaleListeners.onStaleStateChange(stale); - } - } - } - - private static class StaleMessageHandler extends Handler { - - private final WeakReference managerWeakReference; - - private StaleMessageHandler(StaleStateManager staleStateManager) { - this.managerWeakReference = new WeakReference<>(staleStateManager); - } - - @Override - public void handleMessage(Message msg) { - StaleStateManager manager = managerWeakReference.get(); - if (manager != null) { - manager.setState(true); - } - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/Utils.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/Utils.java deleted file mode 100644 index 178183ca0..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/Utils.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.GradientDrawable; -import android.graphics.drawable.LayerDrawable; -import android.location.Location; -import android.os.Build; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.INSTANT_LOCATION_TRANSITION_THRESHOLD; - -public final class Utils { - - private static final String TAG = "Mbgl-com.mapbox.mapboxsdk.location.Utils"; - - private Utils() { - // Class should not be initialized - } - - /** - * Util for finding the shortest path from the current rotated degree to the new degree. - * - * @param heading the new position of the rotation - * @param previousHeading the current position of the rotation - * @return the shortest degree of rotation possible - */ - public static float shortestRotation(float heading, float previousHeading) { - double diff = previousHeading - heading; - if (diff > 180.0f) { - heading += 360.0f; - } else if (diff < -180.0f) { - heading -= 360.f; - } - return heading; - } - - /** - * Normalizes an angle to be in the [0, 360] range. - * - * @param angle the provided angle - * @return the normalized angle - */ - public static float normalize(float angle) { - return (angle % 360 + 360) % 360; - } - - static Bitmap generateShadow(Drawable drawable, float elevation) { - int width = drawable.getIntrinsicWidth(); - int height = drawable.getIntrinsicHeight(); - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - try { - drawable.draw(canvas); - } catch (IllegalArgumentException ex) { - if (ex.getMessage().equals("radius must be > 0") && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { - Logger.w(TAG, - "Location's shadow gradient drawable has a radius <= 0px, resetting to 1px in order to avoid crashing"); - ensureShadowGradientRadius(drawable); - return generateShadow(drawable, elevation); - } else { - throw ex; - } - } - bitmap = Bitmap.createScaledBitmap(bitmap, - toEven(width + elevation), toEven(height + elevation), false); - return bitmap; - } - - /** - * We need to ensure that the radius of any {@link GradientDrawable} is greater than 0 for API levels < 21. - * - * @see mapbox-gl-native-#15026 - */ - private static void ensureShadowGradientRadius(Drawable drawable) { - if (drawable instanceof GradientDrawable) { - ((GradientDrawable) drawable).setGradientRadius(1); - } else if (drawable instanceof LayerDrawable) { - LayerDrawable layerDrawable = (LayerDrawable) drawable; - for (int i = 0; i < layerDrawable.getNumberOfLayers(); i++) { - Drawable layers = layerDrawable.getDrawable(i); - if (layers instanceof GradientDrawable) { - ((GradientDrawable) layers).setGradientRadius(1); - } - } - } - } - - static float calculateZoomLevelRadius(@NonNull MapboxMap mapboxMap, @Nullable Location location) { - if (location == null) { - return 0; - } - double metersPerPixel = mapboxMap.getProjection().getMetersPerPixelAtLatitude(location.getLatitude()); - return (float) (location.getAccuracy() * (1 / metersPerPixel)); - } - - static boolean immediateAnimation(@NonNull Projection projection, @NonNull LatLng current, @NonNull LatLng target) { - double metersPerPixel = projection.getMetersPerPixelAtLatitude((current.getLatitude() + target.getLatitude()) / 2); - double distance = current.distanceTo(target); - return distance / metersPerPixel > INSTANT_LOCATION_TRANSITION_THRESHOLD; - } - - /** - * Casts the value to an even integer. - */ - private static int toEven(float value) { - int i = (int) (value + .5f); - if (i % 2 == 1) { - return i - 1; - } - return i; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/CameraMode.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/CameraMode.java deleted file mode 100644 index 51806a33c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/CameraMode.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.mapbox.mapboxsdk.location.modes; - -import android.location.Location; -import android.support.annotation.IntDef; - -import com.mapbox.mapboxsdk.location.LocationComponent; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Contains the variety of camera modes which determine how the camera will track - * the user location. - */ -public final class CameraMode { - - private CameraMode() { - // Class should not be initialized - } - - /** - * Determine the camera tracking behavior in the {@link LocationComponent}. - */ - @IntDef( {NONE, NONE_COMPASS, NONE_GPS, TRACKING, TRACKING_COMPASS, TRACKING_GPS, TRACKING_GPS_NORTH}) - @Retention(RetentionPolicy.SOURCE) - public @interface Mode { - } - - /** - * No camera tracking. - */ - public static final int NONE = 0x00000008; - - /** - * Camera does not track location, but does track compass bearing. - */ - public static final int NONE_COMPASS = 0x00000010; - - /** - * Camera does not track location, but does track GPS {@link Location} bearing. - */ - public static final int NONE_GPS = 0x00000016; - - /** - * Camera tracks the user location. - */ - public static final int TRACKING = 0x00000018; - - /** - * Camera tracks the user location, with bearing - * provided by a compass. - */ - public static final int TRACKING_COMPASS = 0x00000020; - - /** - * Camera tracks the user location, with bearing - * provided by a normalized {@link Location#getBearing()}. - */ - public static final int TRACKING_GPS = 0x00000022; - - /** - * Camera tracks the user location, with bearing - * always set to north (0). - */ - public static final int TRACKING_GPS_NORTH = 0x00000024; -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/RenderMode.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/RenderMode.java deleted file mode 100644 index 3d20313df..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/RenderMode.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.mapbox.mapboxsdk.location.modes; - -import android.support.annotation.IntDef; - -import com.mapbox.mapboxsdk.location.CompassEngine; -import com.mapbox.mapboxsdk.location.LocationComponent; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Contains the variety of ways the user location can be rendered on the map. - */ -public final class RenderMode { - - private RenderMode() { - // Class should not be initialized - } - - /** - * One of these constants should be used with {@link LocationComponent#setRenderMode(int)}. - * Mode can be switched at anytime by calling the {@code setLocationLayerMode} method passing - * in the new mode you'd like the location layer to be in. - */ - @IntDef( {COMPASS, GPS, NORMAL}) - @Retention(RetentionPolicy.SOURCE) - public @interface Mode { - } - - /** - * Basic tracking is enabled, bearing ignored. - */ - public static final int NORMAL = 0x00000012; - - /** - * Tracking the user location with bearing considered - * from a {@link CompassEngine}. - */ - public static final int COMPASS = 0x00000004; - - /** - * Tracking the user location with bearing considered from {@link android.location.Location}. - */ - public static final int GPS = 0x00000008; -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/package-info.java deleted file mode 100644 index 70dd8cf27..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/modes/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Location layer component camera and render modes. - */ -package com.mapbox.mapboxsdk.location.modes; \ 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 d37eddffc..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/location/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Location layer component. - */ -package com.mapbox.mapboxsdk.location; \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/Logger.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/Logger.java deleted file mode 100644 index b6c4bc872..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/Logger.java +++ /dev/null @@ -1,321 +0,0 @@ -package com.mapbox.mapboxsdk.log; - -import android.support.annotation.IntDef; -import android.support.annotation.Keep; -import android.util.Log; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - - -/** - * Logger for the Mapbox Maps SDK for Android - *

- * Default implementation relies on {@link Log}. - * Alternative implementations can be set with {@link #setLoggerDefinition(LoggerDefinition)}. - *

- */ -@Keep -public final class Logger { - - private static final LoggerDefinition DEFAULT = new LoggerDefinition() { - - @Override - public void v(String tag, String msg) { - Log.v(tag, msg); - } - - @Override - public void v(String tag, String msg, Throwable tr) { - Log.v(tag, msg, tr); - } - - @Override - public void d(String tag, String msg) { - Log.d(tag, msg); - } - - @Override - public void d(String tag, String msg, Throwable tr) { - Log.d(tag, msg, tr); - } - - @Override - public void i(String tag, String msg) { - Log.i(tag, msg); - } - - @Override - public void i(String tag, String msg, Throwable tr) { - Log.i(tag, msg, tr); - } - - @Override - public void w(String tag, String msg) { - Log.w(tag, msg); - } - - @Override - public void w(String tag, String msg, Throwable tr) { - Log.w(tag, msg, tr); - } - - @Override - public void e(String tag, String msg) { - Log.e(tag, msg); - } - - @Override - public void e(String tag, String msg, Throwable tr) { - Log.e(tag, msg, tr); - } - }; - - private static volatile LoggerDefinition logger = DEFAULT; - - @LogLevel - private static int logLevel; - - /** - * Set the verbosity of the Logger. - *

- * This configuration can be used to have more granular control over which logs are emitted by the - * Mapbox Maps SDK for Android. - *

- * - * @param logLevel the verbosity level - */ - public static void setVerbosity(@LogLevel int logLevel) { - Logger.logLevel = logLevel; - } - - /** - * Replace the current used logger definition. - * - * @param loggerDefinition the definition of the logger - */ - public static void setLoggerDefinition(LoggerDefinition loggerDefinition) { - logger = loggerDefinition; - } - - /** - * Send a verbose log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - public static void v(String tag, String msg) { - if (logLevel <= VERBOSE) { - logger.v(tag, msg); - } - } - - /** - * Send a verbose log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - public static void v(String tag, String msg, Throwable tr) { - if (logLevel <= VERBOSE) { - logger.v(tag, msg, tr); - } - } - - /** - * Send a debug log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - public static void d(String tag, String msg) { - if (logLevel <= DEBUG) { - logger.d(tag, msg); - } - } - - /** - * Send a debug log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - public static void d(String tag, String msg, Throwable tr) { - if (logLevel <= DEBUG) { - logger.d(tag, msg, tr); - } - } - - /** - * Send an info log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - public static void i(String tag, String msg) { - if (logLevel <= INFO) { - logger.i(tag, msg); - } - } - - /** - * Send an info log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - public static void i(String tag, String msg, Throwable tr) { - if (logLevel <= INFO) { - logger.i(tag, msg, tr); - } - } - - /** - * Send a warning log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - public static void w(String tag, String msg) { - if (logLevel <= WARN) { - logger.w(tag, msg); - } - } - - /** - * Send a warning log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - public static void w(String tag, String msg, Throwable tr) { - if (logLevel <= WARN) { - logger.w(tag, msg, tr); - } - } - - /** - * Send an error log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - public static void e(String tag, String msg) { - if (logLevel <= ERROR) { - logger.e(tag, msg); - } - } - - /** - * Send an error log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - public static void e(String tag, String msg, Throwable tr) { - if (logLevel <= ERROR) { - logger.e(tag, msg, tr); - } - } - - /** - * Send a log message based on severity. - * - * @param severity the log severity - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param message The message you would like logged. - */ - public static void log(int severity, String tag, String message) { - switch (severity) { - case Log.VERBOSE: - Logger.v(tag, message); - break; - case Log.DEBUG: - Logger.d(tag, message); - break; - case Log.INFO: - Logger.i(tag, message); - break; - case Log.WARN: - Logger.w(tag, message); - break; - case Log.ERROR: - Logger.e(tag, message); - break; - default: - throw new UnsupportedOperationException(); - } - } - - /** - * Priority constant for the println method; use Logger.v - *

- * This log level will print all logs. - *

- */ - public static final int VERBOSE = Log.VERBOSE; - - /** - * Priority constant for the println method; use Logger.d. - *

- * This log level will print all logs except verbose. - *

- */ - public static final int DEBUG = Log.DEBUG; - - /** - * Priority constant for the println method; use Logger.i. - *

- * This log level will print all logs except verbose and debug. - *

- */ - public static final int INFO = Log.INFO; - - /** - * Priority constant for the println method; use Logger.w. - *

- * This log level will print only warn and error logs. - *

- */ - public static final int WARN = Log.WARN; - - /** - * Priority constant for the println method; use Logger.e. - *

- * This log level will print only error logs. - *

- */ - public static final int ERROR = Log.ERROR; - - /** - * Priority constant for the println method. - *

- * This log level won't print any logs. - *

- */ - public static final int NONE = 99; - - /** - * Log level indicates which logs are allowed to be emitted by the Mapbox Maps SDK for Android. - */ - @IntDef( {VERBOSE, DEBUG, INFO, WARN, ERROR, NONE}) - @Retention(RetentionPolicy.SOURCE) - public @interface LogLevel { - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/LoggerDefinition.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/LoggerDefinition.java deleted file mode 100644 index 60b6eb000..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/LoggerDefinition.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.mapbox.mapboxsdk.log; - -/** - * Definition of a logger for the Mapbox Maps SDK for Android. - */ -public interface LoggerDefinition { - - /** - * Send a verbose log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - void v(String tag, String msg); - - /** - * Send a verbose log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - void v(String tag, String msg, Throwable tr); - - /** - * Send a debug log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - void d(String tag, String msg); - - /** - * Send a debug log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - void d(String tag, String msg, Throwable tr); - - /** - * Send an info log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - void i(String tag, String msg); - - /** - * Send an info log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - void i(String tag, String msg, Throwable tr); - - /** - * Send a warning log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - void w(String tag, String msg); - - /** - * Send a warning log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - void w(String tag, String msg, Throwable tr); - - /** - * Send an error log message. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - */ - void e(String tag, String msg); - - /** - * Send an error log message and log the exception. - * - * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param msg The message you would like logged. - * @param tr An exception to log - */ - void e(String tag, String msg, Throwable tr); -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/package-info.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/package-info.java deleted file mode 100644 index 3476ff7cd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/log/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Contains the Mapbox Maps Android Log API classes. - */ -package com.mapbox.mapboxsdk.log; \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationContainer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationContainer.java deleted file mode 100644 index e5bf51279..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationContainer.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; - -import java.util.ArrayList; -import java.util.List; - -/** - * Encapsulates {@link Annotation}'s functionality.. - */ -class AnnotationContainer implements Annotations { - - private final NativeMap nativeMap; - private final LongSparseArray annotations; - - AnnotationContainer(NativeMap nativeMap, LongSparseArray annotations) { - this.nativeMap = nativeMap; - this.annotations = annotations; - } - - @Override - public Annotation obtainBy(long id) { - return annotations.get(id); - } - - @NonNull - @Override - public List obtainAll() { - List annotations = new ArrayList<>(); - for (int i = 0; i < this.annotations.size(); i++) { - annotations.add(this.annotations.get(this.annotations.keyAt(i))); - } - return annotations; - } - - @Override - public void removeBy(long id) { - if (nativeMap != null) { - nativeMap.removeAnnotation(id); - } - annotations.remove(id); - } - - @Override - public void removeBy(@NonNull Annotation annotation) { - long id = annotation.getId(); - removeBy(id); - } - - @Override - public void removeBy(@NonNull List annotationList) { - int count = annotationList.size(); - long[] ids = new long[count]; - for (int i = 0; i < count; i++) { - ids[i] = annotationList.get(i).getId(); - } - - removeNativeAnnotations(ids); - - for (long id : ids) { - annotations.remove(id); - } - } - - @Override - public void removeAll() { - int count = annotations.size(); - long[] ids = new long[count]; - for (int i = 0; i < count; i++) { - ids[i] = annotations.keyAt(i); - } - - removeNativeAnnotations(ids); - - annotations.clear(); - } - - private void removeNativeAnnotations(long[] ids) { - if (nativeMap != null) { - nativeMap.removeAnnotations(ids); - } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationManager.java deleted file mode 100644 index 8875e7164..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AnnotationManager.java +++ /dev/null @@ -1,519 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.graphics.Rect; -import android.graphics.RectF; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v4.util.LongSparseArray; -import android.view.View; -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.PolygonOptions; -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.annotations.PolylineOptions; -import com.mapbox.mapboxsdk.log.Logger; - -import java.util.ArrayList; -import java.util.List; - -/** - * Responsible for managing and tracking state of Annotations linked to Map. All events related to - * annotations that occur on {@link MapboxMap} are forwarded to this class. - *

- * Responsible for referencing {@link InfoWindowManager}. - *

- *

- * Exposes convenience methods to add/remove/update all subtypes of annotations found in - * com.mapbox.mapboxsdk.annotations. - *

- */ -class AnnotationManager { - - private static final String TAG = "Mbgl-AnnotationManager"; - - private static final long NO_ANNOTATION_ID = -1; - - @NonNull - private final MapView mapView; - private final IconManager iconManager; - private final InfoWindowManager infoWindowManager = new InfoWindowManager(); - private final LongSparseArray annotationsArray; - private final List selectedMarkers = new ArrayList<>(); - - private MapboxMap mapboxMap; - @Nullable - private MapboxMap.OnMarkerClickListener onMarkerClickListener; - @Nullable - private MapboxMap.OnPolygonClickListener onPolygonClickListener; - @Nullable - private MapboxMap.OnPolylineClickListener onPolylineClickListener; - - private Annotations annotations; - private ShapeAnnotations shapeAnnotations; - private Markers markers; - private Polygons polygons; - private Polylines polylines; - - AnnotationManager(@NonNull MapView mapView, LongSparseArray annotationsArray, - IconManager iconManager, Annotations annotations, Markers markers, Polygons polygons, - Polylines polylines, ShapeAnnotations shapeAnnotations) { - this.mapView = mapView; - this.annotationsArray = annotationsArray; - this.iconManager = iconManager; - this.annotations = annotations; - this.markers = markers; - this.polygons = polygons; - this.polylines = polylines; - this.shapeAnnotations = shapeAnnotations; - } - - // TODO refactor MapboxMap out for Projection and Transform - // Requires removing MapboxMap from Annotations by using Peer model from #6912 - @NonNull - AnnotationManager bind(MapboxMap mapboxMap) { - this.mapboxMap = mapboxMap; - return this; - } - - void update() { - infoWindowManager.update(); - } - - // - // Annotations - // - - Annotation getAnnotation(long id) { - return annotations.obtainBy(id); - } - - List getAnnotations() { - return annotations.obtainAll(); - } - - void removeAnnotation(long id) { - annotations.removeBy(id); - } - - void removeAnnotation(@NonNull Annotation annotation) { - if (annotation instanceof Marker) { - Marker marker = (Marker) annotation; - marker.hideInfoWindow(); - if (selectedMarkers.contains(marker)) { - selectedMarkers.remove(marker); - } - // do icon cleanup - iconManager.iconCleanup(marker.getIcon()); - } - annotations.removeBy(annotation); - } - - void removeAnnotations(@NonNull List annotationList) { - for (Annotation annotation : annotationList) { - if (annotation instanceof Marker) { - Marker marker = (Marker) annotation; - marker.hideInfoWindow(); - if (selectedMarkers.contains(marker)) { - selectedMarkers.remove(marker); - } - iconManager.iconCleanup(marker.getIcon()); - } - } - annotations.removeBy(annotationList); - } - - void removeAnnotations() { - Annotation annotation; - int count = annotationsArray.size(); - long[] ids = new long[count]; - selectedMarkers.clear(); - for (int i = 0; i < count; i++) { - ids[i] = annotationsArray.keyAt(i); - annotation = annotationsArray.get(ids[i]); - if (annotation instanceof Marker) { - Marker marker = (Marker) annotation; - marker.hideInfoWindow(); - iconManager.iconCleanup(marker.getIcon()); - } - } - annotations.removeAll(); - } - - // - // Markers - // - - Marker addMarker(@NonNull BaseMarkerOptions markerOptions, @NonNull MapboxMap mapboxMap) { - return markers.addBy(markerOptions, mapboxMap); - } - - List addMarkers(@NonNull List markerOptionsList, @NonNull MapboxMap mapboxMap) { - return markers.addBy(markerOptionsList, mapboxMap); - } - - void updateMarker(@NonNull Marker updatedMarker, @NonNull MapboxMap mapboxMap) { - if (!isAddedToMap(updatedMarker)) { - logNonAdded(updatedMarker); - return; - } - markers.update(updatedMarker, mapboxMap); - } - - List getMarkers() { - return markers.obtainAll(); - } - - @NonNull - List getMarkersInRect(@NonNull RectF rectangle) { - return markers.obtainAllIn(rectangle); - } - - void reloadMarkers() { - markers.reload(); - } - - // - // Polygons - // - - Polygon addPolygon(@NonNull PolygonOptions polygonOptions, @NonNull MapboxMap mapboxMap) { - return polygons.addBy(polygonOptions, mapboxMap); - } - - List addPolygons(@NonNull List polygonOptionsList, @NonNull MapboxMap mapboxMap) { - return polygons.addBy(polygonOptionsList, mapboxMap); - } - - void updatePolygon(@NonNull Polygon polygon) { - if (!isAddedToMap(polygon)) { - logNonAdded(polygon); - return; - } - polygons.update(polygon); - } - - List getPolygons() { - return polygons.obtainAll(); - } - - // - // Polylines - // - - Polyline addPolyline(@NonNull PolylineOptions polylineOptions, @NonNull MapboxMap mapboxMap) { - return polylines.addBy(polylineOptions, mapboxMap); - } - - List addPolylines(@NonNull List polylineOptionsList, @NonNull MapboxMap mapboxMap) { - return polylines.addBy(polylineOptionsList, mapboxMap); - } - - void updatePolyline(@NonNull Polyline polyline) { - if (!isAddedToMap(polyline)) { - logNonAdded(polyline); - return; - } - polylines.update(polyline); - } - - List getPolylines() { - return polylines.obtainAll(); - } - - // TODO Refactor from here still in progress - void setOnMarkerClickListener(@Nullable MapboxMap.OnMarkerClickListener listener) { - onMarkerClickListener = listener; - } - - void setOnPolygonClickListener(@Nullable MapboxMap.OnPolygonClickListener listener) { - onPolygonClickListener = listener; - } - - void setOnPolylineClickListener(@Nullable MapboxMap.OnPolylineClickListener listener) { - onPolylineClickListener = listener; - } - - void selectMarker(@NonNull Marker marker) { - if (selectedMarkers.contains(marker)) { - return; - } - - // Need to deselect any currently selected annotation first - if (!infoWindowManager.isAllowConcurrentMultipleOpenInfoWindows()) { - deselectMarkers(); - } - - if (infoWindowManager.isInfoWindowValidForMarker(marker) || infoWindowManager.getInfoWindowAdapter() != null) { - infoWindowManager.add(marker.showInfoWindow(mapboxMap, mapView)); - } - - // only add to selected markers if user didn't handle the click event themselves #3176 - selectedMarkers.add(marker); - } - - void deselectMarkers() { - if (selectedMarkers.isEmpty()) { - return; - } - - for (Marker marker : selectedMarkers) { - if (marker != null) { - if (marker.isInfoWindowShown()) { - marker.hideInfoWindow(); - } - } - } - - // Removes all selected markers from the list - selectedMarkers.clear(); - } - - void deselectMarker(@NonNull Marker marker) { - if (!selectedMarkers.contains(marker)) { - return; - } - - if (marker.isInfoWindowShown()) { - marker.hideInfoWindow(); - } - selectedMarkers.remove(marker); - } - - @NonNull - List getSelectedMarkers() { - return selectedMarkers; - } - - @NonNull - InfoWindowManager getInfoWindowManager() { - return infoWindowManager; - } - - void adjustTopOffsetPixels(@NonNull MapboxMap mapboxMap) { - int count = annotationsArray.size(); - for (int i = 0; i < count; i++) { - Annotation annotation = annotationsArray.get(i); - if (annotation instanceof Marker) { - Marker marker = (Marker) annotation; - marker.setTopOffsetPixels( - iconManager.getTopOffsetPixelsForIcon(marker.getIcon())); - } - } - - for (Marker marker : selectedMarkers) { - if (marker.isInfoWindowShown()) { - marker.hideInfoWindow(); - marker.showInfoWindow(mapboxMap, mapView); - } - } - } - - private boolean isAddedToMap(@Nullable Annotation annotation) { - return annotation != null && annotation.getId() != -1 && annotationsArray.indexOfKey(annotation.getId()) > -1; - } - - private void logNonAdded(@NonNull Annotation annotation) { - Logger.w(TAG, String.format( - "Attempting to update non-added %s with value %s", annotation.getClass().getCanonicalName(), annotation) - ); - } - - // - // Click event - // - - boolean onTap(@NonNull PointF tapPoint) { - MarkerHit markerHit = getMarkerHitFromTouchArea(tapPoint); - long markerId = new MarkerHitResolver(mapboxMap).execute(markerHit); - if (markerId != NO_ANNOTATION_ID) { - if (isClickHandledForMarker(markerId)) { - return true; - } - } - - ShapeAnnotationHit shapeAnnotationHit = getShapeAnnotationHitFromTap(tapPoint); - Annotation annotation = new ShapeAnnotationHitResolver(shapeAnnotations).execute(shapeAnnotationHit); - return annotation != null && handleClickForShapeAnnotation(annotation); - } - - private ShapeAnnotationHit getShapeAnnotationHitFromTap(PointF tapPoint) { - float touchTargetSide = Mapbox.getApplicationContext().getResources().getDimension(R.dimen.mapbox_eight_dp); - RectF tapRect = new RectF( - tapPoint.x - touchTargetSide, - tapPoint.y - touchTargetSide, - tapPoint.x + touchTargetSide, - tapPoint.y + touchTargetSide - ); - return new ShapeAnnotationHit(tapRect); - } - - private boolean handleClickForShapeAnnotation(Annotation annotation) { - if (annotation instanceof Polygon && onPolygonClickListener != null) { - onPolygonClickListener.onPolygonClick((Polygon) annotation); - return true; - } else if (annotation instanceof Polyline && onPolylineClickListener != null) { - onPolylineClickListener.onPolylineClick((Polyline) annotation); - return true; - } - return false; - } - - private MarkerHit getMarkerHitFromTouchArea(PointF tapPoint) { - int touchSurfaceWidth = (int) (iconManager.getHighestIconHeight() * 1.5); - int touchSurfaceHeight = (int) (iconManager.getHighestIconWidth() * 1.5); - final RectF tapRect = new RectF(tapPoint.x - touchSurfaceWidth, - tapPoint.y - touchSurfaceHeight, - tapPoint.x + touchSurfaceWidth, - tapPoint.y + touchSurfaceHeight - ); - return new MarkerHit(tapRect, getMarkersInRect(tapRect)); - } - - private boolean isClickHandledForMarker(long markerId) { - Marker marker = (Marker) getAnnotation(markerId); - boolean handledDefaultClick = onClickMarker(marker); - if (!handledDefaultClick) { - toggleMarkerSelectionState(marker); - } - return true; - } - - private boolean onClickMarker(@NonNull Marker marker) { - return onMarkerClickListener != null && onMarkerClickListener.onMarkerClick(marker); - } - - private void toggleMarkerSelectionState(@NonNull Marker marker) { - if (!selectedMarkers.contains(marker)) { - selectMarker(marker); - } else { - deselectMarker(marker); - } - } - - private static class ShapeAnnotationHitResolver { - - private ShapeAnnotations shapeAnnotations; - - ShapeAnnotationHitResolver(ShapeAnnotations shapeAnnotations) { - this.shapeAnnotations = shapeAnnotations; - } - - @Nullable - public Annotation execute(@NonNull ShapeAnnotationHit shapeHit) { - Annotation foundAnnotation = null; - List annotations = shapeAnnotations.obtainAllIn(shapeHit.tapPoint); - if (annotations.size() > 0) { - foundAnnotation = annotations.get(0); - } - return foundAnnotation; - } - } - - private static class MarkerHitResolver { - - @NonNull - private final Projection projection; - private final int minimalTouchSize; - - @Nullable - private View view; - - private Bitmap bitmap; - private int bitmapWidth; - private int bitmapHeight; - private PointF markerLocation; - - @NonNull - private Rect hitRectView = new Rect(); - @NonNull - private RectF hitRectMarker = new RectF(); - @NonNull - private RectF highestSurfaceIntersection = new RectF(); - - private long closestMarkerId = NO_ANNOTATION_ID; - - MarkerHitResolver(@NonNull MapboxMap mapboxMap) { - this.projection = mapboxMap.getProjection(); - this.minimalTouchSize = (int) (32 * Mapbox.getApplicationContext().getResources().getDisplayMetrics().density); - } - - public long execute(@NonNull MarkerHit markerHit) { - resolveForMarkers(markerHit); - return closestMarkerId; - } - - private void resolveForMarkers(MarkerHit markerHit) { - for (Marker marker : markerHit.markers) { - resolveForMarker(markerHit, marker); - } - } - - private void resolveForMarker(@NonNull MarkerHit markerHit, Marker marker) { - markerLocation = projection.toScreenLocation(marker.getPosition()); - bitmap = marker.getIcon().getBitmap(); - - bitmapHeight = bitmap.getHeight(); - if (bitmapHeight < minimalTouchSize) { - bitmapHeight = minimalTouchSize; - } - - bitmapWidth = bitmap.getWidth(); - if (bitmapWidth < minimalTouchSize) { - bitmapWidth = minimalTouchSize; - } - - hitRectMarker.set(0, 0, bitmapWidth, bitmapHeight); - hitRectMarker.offsetTo( - markerLocation.x - bitmapWidth / 2, - markerLocation.y - bitmapHeight / 2 - ); - hitTestMarker(markerHit, marker, hitRectMarker); - } - - private void hitTestMarker(MarkerHit markerHit, @NonNull Marker marker, RectF hitRectMarker) { - if (hitRectMarker.contains(markerHit.getTapPointX(), markerHit.getTapPointY())) { - hitRectMarker.intersect(markerHit.tapRect); - if (isRectangleHighestSurfaceIntersection(hitRectMarker)) { - highestSurfaceIntersection = new RectF(hitRectMarker); - closestMarkerId = marker.getId(); - } - } - } - - private boolean isRectangleHighestSurfaceIntersection(RectF rectF) { - return rectF.width() * rectF.height() > highestSurfaceIntersection.width() * highestSurfaceIntersection.height(); - } - } - - private static class ShapeAnnotationHit { - private final RectF tapPoint; - - ShapeAnnotationHit(RectF tapPoint) { - this.tapPoint = tapPoint; - } - } - - private static class MarkerHit { - private final RectF tapRect; - private final List markers; - - MarkerHit(RectF tapRect, List markers) { - this.tapRect = tapRect; - this.markers = markers; - } - - float getTapPointX() { - return tapRect.centerX(); - } - - float getTapPointY() { - return tapRect.centerY(); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Annotations.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Annotations.java deleted file mode 100644 index ae41cbb0c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Annotations.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.annotations.Annotation; - -import java.util.List; - -/** - * Interface that defines convenient methods for working with a {@link Annotation}'s collection. - */ -interface Annotations { - Annotation obtainBy(long id); - - List obtainAll(); - - void removeBy(long id); - - void removeBy(@NonNull Annotation annotation); - - void removeBy(@NonNull List annotationList); - - void removeAll(); -} 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 deleted file mode 100644 index 5384a29fc..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/AttributionDialogManager.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.ActivityNotFoundException; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.net.Uri; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.View; -import android.widget.ArrayAdapter; -import android.widget.Toast; -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.Mapbox; -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 java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Responsible for managing attribution interactions on the map. - *

- * When the user clicks the attribution icon, {@link AttributionDialogManager#onClick(View)} will be invoked. - * An attribution dialog will be shown to the user with contents based on the attributions found in the map style. - * Additionally an telemetry option item is shown to configure telemetry settings. - *

- */ -public class AttributionDialogManager implements View.OnClickListener, DialogInterface.OnClickListener { - private static final String MAP_FEEDBACK_URL = "https://apps.mapbox.com/feedback"; - private static final String MAP_FEEDBACK_URL_OLD = "https://www.mapbox.com/map-feedback"; - private static final String MAP_FEEDBACK_URL_LOCATION_FRAGMENT_FORMAT = "/%f/%f/%f/%f/%d"; - private static final String MAP_FEEDBACK_STYLE_URI_REGEX = "^(.*://[^:^/]*)/(.*)/(.*)"; - - @NonNull - private final Context context; - @NonNull - private final MapboxMap mapboxMap; - private Set attributionSet; - private AlertDialog dialog; - - public AttributionDialogManager(@NonNull Context context, @NonNull MapboxMap mapboxMap) { - this.context = context; - this.mapboxMap = mapboxMap; - } - - // Called when someone presses the attribution icon on the map - @Override - public void onClick(@NonNull View view) { - attributionSet = new AttributionBuilder(mapboxMap, view.getContext()).build(); - - boolean isActivityFinishing = false; - if (context instanceof Activity) { - isActivityFinishing = ((Activity) context).isFinishing(); - } - - // check is hosting activity isn't finishing - // https://github.com/mapbox/mapbox-gl-native/issues/11238 - if (!isActivityFinishing) { - showAttributionDialog(getAttributionTitles()); - } - } - - protected void showAttributionDialog(@NonNull 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); - dialog = builder.show(); - } - - private String[] getAttributionTitles() { - List titles = new ArrayList<>(); - for (Attribution attribution : attributionSet) { - titles.add(attribution.getTitle()); - } - return titles.toArray(new String[titles.size()]); - } - - // Called when someone selects an attribution or telemetry settings from the dialog - @Override - public void onClick(DialogInterface dialog, int which) { - if (isLatestEntry(which)) { - showTelemetryDialog(); - } else { - showMapAttributionWebPage(which); - } - } - - public void onStop() { - if (dialog != null && dialog.isShowing()) { - dialog.dismiss(); - } - } - - private boolean isLatestEntry(int attributionKeyIndex) { - return attributionKeyIndex == getAttributionTitles().length - 1; - } - - private void showTelemetryDialog() { - AlertDialog.Builder builder = new AlertDialog.Builder(context); - builder.setTitle(R.string.mapbox_attributionTelemetryTitle); - builder.setMessage(R.string.mapbox_attributionTelemetryMessage); - builder.setPositiveButton(R.string.mapbox_attributionTelemetryPositive, new DialogInterface.OnClickListener() { - @Override - public void onClick(@NonNull DialogInterface dialog, int which) { - TelemetryDefinition telemetry = Mapbox.getTelemetry(); - if (telemetry != null) { - telemetry.setUserTelemetryRequestState(true); - } - dialog.cancel(); - } - }); - builder.setNeutralButton(R.string.mapbox_attributionTelemetryNeutral, new DialogInterface.OnClickListener() { - @Override - public void onClick(@NonNull DialogInterface dialog, int which) { - showWebPage(context.getResources().getString(R.string.mapbox_telemetryLink)); - dialog.cancel(); - } - }); - builder.setNegativeButton(R.string.mapbox_attributionTelemetryNegative, new DialogInterface.OnClickListener() { - @Override - public void onClick(@NonNull DialogInterface dialog, int which) { - TelemetryDefinition telemetry = Mapbox.getTelemetry(); - if (telemetry != null) { - telemetry.setUserTelemetryRequestState(false); - } - dialog.cancel(); - } - }); - builder.show(); - } - - private void showMapAttributionWebPage(int which) { - Attribution[] attributions = attributionSet.toArray(new Attribution[attributionSet.size()]); - String url = attributions[which].getUrl(); - if (url.contains(MAP_FEEDBACK_URL_OLD) || url.contains(MAP_FEEDBACK_URL)) { - url = buildMapFeedbackMapUrl(Mapbox.getAccessToken()); - } - showWebPage(url); - } - - @NonNull - String buildMapFeedbackMapUrl(@Nullable String accessToken) { - // TODO Add Android Maps SDK version to the query parameter, currently the version API is not available. - // TODO Keep track of this issue at [#15632](https://github.com/mapbox/mapbox-gl-native/issues/15632) - - Uri.Builder builder = Uri.parse(MAP_FEEDBACK_URL).buildUpon(); - - CameraPosition cameraPosition = mapboxMap.getCameraPosition(); - if (cameraPosition != null) { - builder.encodedFragment(String.format(Locale.getDefault(), MAP_FEEDBACK_URL_LOCATION_FRAGMENT_FORMAT, - cameraPosition.target.getLongitude(), cameraPosition.target.getLatitude(), - cameraPosition.zoom, cameraPosition.bearing, (int) cameraPosition.tilt)); - } - - String packageName = context.getApplicationContext().getPackageName(); - if (packageName != null) { - builder.appendQueryParameter("referrer", packageName); - } - - if (accessToken != null) { - builder.appendQueryParameter("access_token", accessToken); - } - - Style style = mapboxMap.getStyle(); - if (style != null) { - String styleUri = style.getUri(); - Pattern pattern = Pattern.compile(MAP_FEEDBACK_STYLE_URI_REGEX); - Matcher matcher = pattern.matcher(styleUri); - - if (matcher.find()) { - String styleOwner = matcher.group(2); - String styleId = matcher.group(3); - - builder.appendQueryParameter("owner", styleOwner) - .appendQueryParameter("id", styleId); - } - } - - return builder.build().toString(); - } - - private void showWebPage(@NonNull String url) { - try { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setData(Uri.parse(url)); - context.startActivity(intent); - } catch (ActivityNotFoundException exception) { - // explicitly handling if the device hasn't have a web browser installed. #8899 - Toast.makeText(context, R.string.mapbox_attributionErrorNoBrowser, Toast.LENGTH_LONG).show(); - MapStrictMode.strictModeViolation(exception); - } - } - - private static class AttributionBuilder { - - private final MapboxMap mapboxMap; - @NonNull - private final WeakReference context; - - AttributionBuilder(MapboxMap mapboxMap, Context context) { - this.mapboxMap = mapboxMap; - this.context = new WeakReference<>(context); - } - - private Set build() { - Context context = this.context.get(); - if (context == null) { - return Collections.emptySet(); - } - - List attributions = new ArrayList<>(); - String attribution; - - Style style = mapboxMap.getStyle(); - if (style != null) { - for (Source source : style.getSources()) { - attribution = source.getAttribution(); - if (!attribution.isEmpty()) { - attributions.add(attribution); - } - } - } - - return new AttributionParser.Options(context) - .withCopyrightSign(true) - .withImproveMap(true) - .withTelemetryAttribution(true) - .withAttributionData(attributions.toArray(new String[attributions.size()])) - .build().getAttributions(); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CameraChangeDispatcher.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CameraChangeDispatcher.java deleted file mode 100644 index a1fd4e7e3..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/CameraChangeDispatcher.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.os.Handler; -import android.os.Message; -import android.support.annotation.IntDef; -import android.support.annotation.NonNull; - -import java.lang.annotation.Retention; -import java.lang.ref.WeakReference; -import java.util.concurrent.CopyOnWriteArrayList; - -import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraIdleListener; -import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveCanceledListener; -import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveListener; -import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener; -import static java.lang.annotation.RetentionPolicy.SOURCE; - -/** - * Class responsible for dispatching camera change events to registered listeners. - */ -class CameraChangeDispatcher implements MapboxMap.OnCameraMoveStartedListener, MapboxMap.OnCameraMoveListener, - MapboxMap.OnCameraMoveCanceledListener, OnCameraIdleListener { - - private final CameraChangeHandler handler = new CameraChangeHandler(this); - - private boolean idle = true; - private int moveStartedReason; - - private final CopyOnWriteArrayList onCameraMoveStarted = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onCameraMoveCanceled = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onCameraMove = new CopyOnWriteArrayList<>(); - private final CopyOnWriteArrayList onCameraIdle = new CopyOnWriteArrayList<>(); - - @Retention(SOURCE) - @IntDef( {MOVE_STARTED, MOVE, MOVE_CANCELED, IDLE}) - @interface CameraChange { - } - - private static final int MOVE_STARTED = 0; - private static final int MOVE = 1; - private static final int MOVE_CANCELED = 2; - private static final int IDLE = 3; - - @Override - public void onCameraMoveStarted(final int reason) { - moveStartedReason = reason; - handler.scheduleMessage(MOVE_STARTED); - } - - @Override - public void onCameraMove() { - handler.scheduleMessage(MOVE); - } - - @Override - public void onCameraMoveCanceled() { - handler.scheduleMessage(MOVE_CANCELED); - } - - @Override - public void onCameraIdle() { - handler.scheduleMessage(IDLE); - } - - void addOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { - onCameraIdle.add(listener); - } - - void removeOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { - if (onCameraIdle.contains(listener)) { - onCameraIdle.remove(listener); - } - } - - void addOnCameraMoveCancelListener(OnCameraMoveCanceledListener listener) { - onCameraMoveCanceled.add(listener); - } - - void removeOnCameraMoveCancelListener(OnCameraMoveCanceledListener listener) { - if (onCameraMoveCanceled.contains(listener)) { - onCameraMoveCanceled.remove(listener); - } - } - - void addOnCameraMoveStartedListener(OnCameraMoveStartedListener listener) { - onCameraMoveStarted.add(listener); - } - - void removeOnCameraMoveStartedListener(OnCameraMoveStartedListener listener) { - if (onCameraMoveStarted.contains(listener)) { - onCameraMoveStarted.remove(listener); - } - } - - void addOnCameraMoveListener(OnCameraMoveListener listener) { - onCameraMove.add(listener); - } - - void removeOnCameraMoveListener(OnCameraMoveListener listener) { - if (onCameraMove.contains(listener)) { - onCameraMove.remove(listener); - } - } - - private void executeOnCameraMoveStarted() { - if (!idle) { - return; - } - idle = false; - if (!onCameraMoveStarted.isEmpty()) { - for (OnCameraMoveStartedListener cameraMoveStartedListener : onCameraMoveStarted) { - cameraMoveStartedListener.onCameraMoveStarted(moveStartedReason); - } - } - } - - private void executeOnCameraMove() { - if (!onCameraMove.isEmpty() && !idle) { - for (OnCameraMoveListener cameraMoveListener : onCameraMove) { - cameraMoveListener.onCameraMove(); - } - } - } - - private void executeOnCameraMoveCancelled() { - if (!onCameraMoveCanceled.isEmpty() && !idle) { - for (OnCameraMoveCanceledListener cameraMoveCanceledListener : onCameraMoveCanceled) { - cameraMoveCanceledListener.onCameraMoveCanceled(); - } - } - } - - private void executeOnCameraIdle() { - if (idle) { - return; - } - idle = true; - if (!onCameraIdle.isEmpty()) { - for (OnCameraIdleListener cameraIdleListener : onCameraIdle) { - cameraIdleListener.onCameraIdle(); - } - } - } - - void onDestroy() { - handler.removeCallbacksAndMessages(null); - onCameraMoveStarted.clear(); - onCameraMoveCanceled.clear(); - onCameraMove.clear(); - onCameraIdle.clear(); - } - - private static class CameraChangeHandler extends Handler { - - private WeakReference dispatcherWeakReference; - - CameraChangeHandler(CameraChangeDispatcher dispatcher) { - super(); - this.dispatcherWeakReference = new WeakReference<>(dispatcher); - } - - @Override - public void handleMessage(@NonNull Message msg) { - CameraChangeDispatcher dispatcher = dispatcherWeakReference.get(); - if (dispatcher != null) { - switch (msg.what) { - case MOVE_STARTED: - dispatcher.executeOnCameraMoveStarted(); - break; - case MOVE: - dispatcher.executeOnCameraMove(); - break; - case MOVE_CANCELED: - dispatcher.executeOnCameraMoveCancelled(); - break; - case IDLE: - dispatcher.executeOnCameraIdle(); - break; - } - } - } - - void scheduleMessage(@CameraChange int change) { - CameraChangeDispatcher dispatcher = dispatcherWeakReference.get(); - if (dispatcher != null) { - // if there is a movement that is cancelled/stopped and restarted in the same code block - // we can safely assume that the movement will continue, no need for dispatching unnecessary callbacks sequence - if (change == MOVE_STARTED) { - boolean shouldReturn = !dispatcher.idle && (hasMessages(IDLE) || hasMessages(MOVE_CANCELED)); - removeMessages(IDLE); - removeMessages(MOVE_CANCELED); - - if (shouldReturn) { - return; - } - } - - Message message = new Message(); - message.what = change; - this.sendMessage(message); - } - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/FocalPointChangeListener.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/FocalPointChangeListener.java deleted file mode 100644 index aec9a848b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/FocalPointChangeListener.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.PointF; - -/** - * Interface definition of a callback that is invoked when the focal point will change. - */ -public interface FocalPointChangeListener { - - void onFocalPointChanged(PointF pointF); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/IconManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/IconManager.java deleted file mode 100644 index 3a0824ad1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/IconManager.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Bitmap; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.annotations.Icon; -import com.mapbox.mapboxsdk.annotations.IconFactory; -import com.mapbox.mapboxsdk.annotations.Marker; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Responsible for managing icons added to the Map. - *

- * Maintains a {@link List} of {@link Icon} and is responsible for initialising default markers. - *

- *

- * Keep track of icons added and the resulting average icon size. This is used internally by our - * gestures detection to calculate the size of a touch target. - *

- */ -class IconManager { - - private final Map iconMap = new HashMap<>(); - - private NativeMap nativeMap; - private int highestIconWidth; - private int highestIconHeight; - - IconManager(NativeMap nativeMap) { - this.nativeMap = nativeMap; - } - - Icon loadIconForMarker(@NonNull Marker marker) { - Icon icon = marker.getIcon(); - if (icon == null) { - // TODO replace with anchor implementation, we are faking an anchor by adding extra pixels and diving height by 2 - icon = loadDefaultIconForMarker(marker); - } else { - updateHighestIconSize(icon); - } - addIcon(icon); - return icon; - } - - int getTopOffsetPixelsForIcon(@NonNull Icon icon) { - return (int) (nativeMap.getTopOffsetPixelsForAnnotationSymbol(icon.getId()) * nativeMap.getPixelRatio()); - } - - int getHighestIconWidth() { - return highestIconWidth; - } - - int getHighestIconHeight() { - return highestIconHeight; - } - - private Icon loadDefaultIconForMarker(Marker marker) { - Icon icon = IconFactory.getInstance(Mapbox.getApplicationContext()).defaultMarker(); - Bitmap bitmap = icon.getBitmap(); - updateHighestIconSize(bitmap.getWidth(), bitmap.getHeight() / 2); - marker.setIcon(icon); - return icon; - } - - private void addIcon(@NonNull Icon icon) { - addIcon(icon, true); - } - - private void addIcon(@NonNull Icon icon, boolean addIconToMap) { - if (!iconMap.keySet().contains(icon)) { - iconMap.put(icon, 1); - if (addIconToMap) { - loadIcon(icon); - } - } else { - iconMap.put(icon, iconMap.get(icon) + 1); - } - } - - private void updateHighestIconSize(Icon icon) { - updateHighestIconSize(icon.getBitmap()); - } - - private void updateHighestIconSize(Bitmap bitmap) { - updateHighestIconSize(bitmap.getWidth(), bitmap.getHeight()); - } - - private void updateHighestIconSize(int width, int height) { - if (width > highestIconWidth) { - highestIconWidth = width; - } - - if (height > highestIconHeight) { - highestIconHeight = height; - } - } - - private void loadIcon(Icon icon) { - Bitmap bitmap = icon.getBitmap(); - nativeMap.addAnnotationIcon(icon.getId(), - bitmap.getWidth(), - bitmap.getHeight(), - icon.getScale(), - icon.toBytes()); - } - - void reloadIcons() { - for (Icon icon : iconMap.keySet()) { - loadIcon(icon); - } - } - - void ensureIconLoaded(@NonNull Marker marker, @NonNull MapboxMap mapboxMap) { - Icon icon = marker.getIcon(); - if (icon == null) { - icon = loadDefaultIconForMarker(marker); - } - addIcon(icon); - setTopOffsetPixels(marker, mapboxMap, icon); - } - - private void setTopOffsetPixels(Marker marker, @NonNull MapboxMap mapboxMap, @NonNull Icon icon) { - // this seems to be a costly operation according to the profiler so I'm trying to save some calls - Marker previousMarker = marker.getId() != -1 ? (Marker) mapboxMap.getAnnotation(marker.getId()) : null; - if (previousMarker == null || previousMarker.getIcon() == null || previousMarker.getIcon() != marker.getIcon()) { - marker.setTopOffsetPixels(getTopOffsetPixelsForIcon(icon)); - } - } - - void iconCleanup(@NonNull Icon icon) { - Integer refCounter = iconMap.get(icon); - if (refCounter != null) { - refCounter--; - if (refCounter == 0) { - remove(icon); - } else { - updateIconRefCounter(icon, refCounter); - } - } - } - - private void remove(Icon icon) { - nativeMap.removeAnnotationIcon(icon.getId()); - iconMap.remove(icon); - } - - private void updateIconRefCounter(Icon icon, int refCounter) { - iconMap.put(icon, refCounter); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Image.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Image.java deleted file mode 100644 index a261c2f4b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Image.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.support.annotation.Keep; - -@Keep -class Image { - private final byte[] buffer; - private final float pixelRatio; - private final String name; - private final int width; - private final int height; - private final boolean sdf; - - public Image(byte[] buffer, float pixelRatio, String name, int width, int height, boolean sdf) { - this.buffer = buffer; - this.pixelRatio = pixelRatio; - this.name = name; - this.width = width; - this.height = height; - this.sdf = sdf; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/InfoWindowManager.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/InfoWindowManager.java deleted file mode 100644 index 434244a7c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/InfoWindowManager.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.support.annotation.Nullable; -import android.text.TextUtils; - -import com.mapbox.mapboxsdk.annotations.InfoWindow; -import com.mapbox.mapboxsdk.annotations.Marker; - -import java.util.ArrayList; -import java.util.List; - -/** - * Responsible for managing InfoWindows shown on the Map. - *

- * Maintains a {@link List} of opened {@link InfoWindow} and tracks configurations as - * allowConcurrentMultipleInfoWindows which allows to have multiple {@link InfoWindow} open at the - * same time. Responsible for managing listeners as - * {@link com.mapbox.mapboxsdk.maps.MapboxMap.OnInfoWindowClickListener} and - * {@link com.mapbox.mapboxsdk.maps.MapboxMap.OnInfoWindowLongClickListener}. - *

- */ -class InfoWindowManager { - - private final List infoWindows = new ArrayList<>(); - - @Nullable - private MapboxMap.InfoWindowAdapter infoWindowAdapter; - private boolean allowConcurrentMultipleInfoWindows; - - @Nullable - private MapboxMap.OnInfoWindowClickListener onInfoWindowClickListener; - @Nullable - private MapboxMap.OnInfoWindowLongClickListener onInfoWindowLongClickListener; - @Nullable - private MapboxMap.OnInfoWindowCloseListener onInfoWindowCloseListener; - - void update() { - if (!infoWindows.isEmpty()) { - for (InfoWindow infoWindow : infoWindows) { - infoWindow.update(); - } - } - } - - void setInfoWindowAdapter(@Nullable MapboxMap.InfoWindowAdapter infoWindowAdapter) { - this.infoWindowAdapter = infoWindowAdapter; - } - - @Nullable - MapboxMap.InfoWindowAdapter getInfoWindowAdapter() { - return infoWindowAdapter; - } - - void setAllowConcurrentMultipleOpenInfoWindows(boolean allow) { - allowConcurrentMultipleInfoWindows = allow; - } - - boolean isAllowConcurrentMultipleOpenInfoWindows() { - return allowConcurrentMultipleInfoWindows; - } - - boolean isInfoWindowValidForMarker(@Nullable Marker marker) { - return marker != null && (!TextUtils.isEmpty(marker.getTitle()) || !TextUtils.isEmpty(marker.getSnippet())); - } - - void setOnInfoWindowClickListener(@Nullable MapboxMap.OnInfoWindowClickListener listener) { - onInfoWindowClickListener = listener; - } - - @Nullable - MapboxMap.OnInfoWindowClickListener getOnInfoWindowClickListener() { - return onInfoWindowClickListener; - } - - void setOnInfoWindowLongClickListener(@Nullable MapboxMap.OnInfoWindowLongClickListener listener) { - onInfoWindowLongClickListener = listener; - } - - @Nullable - MapboxMap.OnInfoWindowLongClickListener getOnInfoWindowLongClickListener() { - return onInfoWindowLongClickListener; - } - - void setOnInfoWindowCloseListener(@Nullable MapboxMap.OnInfoWindowCloseListener listener) { - onInfoWindowCloseListener = listener; - } - - @Nullable - MapboxMap.OnInfoWindowCloseListener getOnInfoWindowCloseListener() { - return onInfoWindowCloseListener; - } - - public void add(InfoWindow infoWindow) { - infoWindows.add(infoWindow); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapChangeReceiver.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapChangeReceiver.java deleted file mode 100644 index 5932f6fbf..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapChangeReceiver.java +++ /dev/null @@ -1,395 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import com.mapbox.mapboxsdk.log.Logger; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -class MapChangeReceiver implements NativeMapView.StateCallback { - - private static final String TAG = "Mbgl-MapChangeReceiver"; - - private final List onCameraWillChangeListenerList = new CopyOnWriteArrayList<>(); - private final List onCameraIsChangingListenerList = new CopyOnWriteArrayList<>(); - private final List onCameraDidChangeListenerList = new CopyOnWriteArrayList<>(); - private final List onWillStartLoadingMapListenerList - = new CopyOnWriteArrayList<>(); - private final List onDidFinishLoadingMapListenerList - = new CopyOnWriteArrayList<>(); - private final List onDidFailLoadingMapListenerList - = new CopyOnWriteArrayList<>(); - private final List onWillStartRenderingFrameList - = new CopyOnWriteArrayList<>(); - private final List onDidFinishRenderingFrameList - = new CopyOnWriteArrayList<>(); - private final List onWillStartRenderingMapListenerList - = new CopyOnWriteArrayList<>(); - private final List onDidFinishRenderingMapListenerList - = new CopyOnWriteArrayList<>(); - private final List onDidBecomeIdleListenerList - = new CopyOnWriteArrayList<>(); - private final List onDidFinishLoadingStyleListenerList - = new CopyOnWriteArrayList<>(); - private final List onSourceChangedListenerList = new CopyOnWriteArrayList<>(); - private final List onStyleImageMissingListenerList - = new CopyOnWriteArrayList<>(); - private final List onCanRemoveUnusedStyleImageListenerList - = new CopyOnWriteArrayList<>(); - - @Override - public void onCameraWillChange(boolean animated) { - try { - if (!onCameraWillChangeListenerList.isEmpty()) { - for (MapView.OnCameraWillChangeListener onCameraWillChangeListener : onCameraWillChangeListenerList) { - onCameraWillChangeListener.onCameraWillChange(animated); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onCameraWillChange", err); - throw err; - } - } - - @Override - public void onCameraIsChanging() { - try { - if (!onCameraIsChangingListenerList.isEmpty()) { - for (MapView.OnCameraIsChangingListener onCameraIsChangingListener : onCameraIsChangingListenerList) { - onCameraIsChangingListener.onCameraIsChanging(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onCameraIsChanging", err); - throw err; - } - } - - @Override - public void onCameraDidChange(boolean animated) { - try { - if (!onCameraDidChangeListenerList.isEmpty()) { - for (MapView.OnCameraDidChangeListener onCameraDidChangeListener : onCameraDidChangeListenerList) { - onCameraDidChangeListener.onCameraDidChange(animated); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onCameraDidChange", err); - throw err; - } - } - - @Override - public void onWillStartLoadingMap() { - try { - if (!onWillStartLoadingMapListenerList.isEmpty()) { - for (MapView.OnWillStartLoadingMapListener onWillStartLoadingMapListener : onWillStartLoadingMapListenerList) { - onWillStartLoadingMapListener.onWillStartLoadingMap(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onWillStartLoadingMap", err); - throw err; - } - } - - @Override - public void onDidFinishLoadingMap() { - try { - if (!onDidFinishLoadingMapListenerList.isEmpty()) { - for (MapView.OnDidFinishLoadingMapListener onDidFinishLoadingMapListener : onDidFinishLoadingMapListenerList) { - onDidFinishLoadingMapListener.onDidFinishLoadingMap(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidFinishLoadingMap", err); - throw err; - } - } - - @Override - public void onDidFailLoadingMap(String error) { - try { - if (!onDidFailLoadingMapListenerList.isEmpty()) { - for (MapView.OnDidFailLoadingMapListener onDidFailLoadingMapListener : onDidFailLoadingMapListenerList) { - onDidFailLoadingMapListener.onDidFailLoadingMap(error); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidFailLoadingMap", err); - throw err; - } - } - - @Override - public void onWillStartRenderingFrame() { - try { - if (!onWillStartRenderingFrameList.isEmpty()) { - for (MapView.OnWillStartRenderingFrameListener listener : onWillStartRenderingFrameList) { - listener.onWillStartRenderingFrame(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onWillStartRenderingFrame", err); - throw err; - } - } - - @Override - public void onDidFinishRenderingFrame(boolean fully) { - try { - if (!onDidFinishRenderingFrameList.isEmpty()) { - for (MapView.OnDidFinishRenderingFrameListener listener : onDidFinishRenderingFrameList) { - listener.onDidFinishRenderingFrame(fully); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidFinishRenderingFrame", err); - throw err; - } - } - - @Override - public void onWillStartRenderingMap() { - try { - if (!onWillStartRenderingMapListenerList.isEmpty()) { - for (MapView.OnWillStartRenderingMapListener listener : onWillStartRenderingMapListenerList) { - listener.onWillStartRenderingMap(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onWillStartRenderingMap", err); - throw err; - } - } - - @Override - public void onDidFinishRenderingMap(boolean fully) { - try { - if (!onDidFinishRenderingMapListenerList.isEmpty()) { - for (MapView.OnDidFinishRenderingMapListener listener : onDidFinishRenderingMapListenerList) { - listener.onDidFinishRenderingMap(fully); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidFinishRenderingMap", err); - throw err; - } - } - - @Override - public void onDidBecomeIdle() { - try { - if (!onDidBecomeIdleListenerList.isEmpty()) { - for (MapView.OnDidBecomeIdleListener listener : onDidBecomeIdleListenerList) { - listener.onDidBecomeIdle(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidBecomeIdle", err); - throw err; - } - } - - @Override - public void onDidFinishLoadingStyle() { - try { - if (!onDidFinishLoadingStyleListenerList.isEmpty()) { - for (MapView.OnDidFinishLoadingStyleListener listener : onDidFinishLoadingStyleListenerList) { - listener.onDidFinishLoadingStyle(); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onDidFinishLoadingStyle", err); - throw err; - } - } - - @Override - public void onSourceChanged(String sourceId) { - try { - if (!onSourceChangedListenerList.isEmpty()) { - for (MapView.OnSourceChangedListener onSourceChangedListener : onSourceChangedListenerList) { - onSourceChangedListener.onSourceChangedListener(sourceId); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onSourceChanged", err); - throw err; - } - } - - @Override - public void onStyleImageMissing(String imageId) { - try { - if (!onStyleImageMissingListenerList.isEmpty()) { - for (MapView.OnStyleImageMissingListener listener : onStyleImageMissingListenerList) { - listener.onStyleImageMissing(imageId); - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onStyleImageMissing", err); - throw err; - } - } - - @Override - public boolean onCanRemoveUnusedStyleImage(String imageId) { - if (onCanRemoveUnusedStyleImageListenerList.isEmpty()) { - return true; - } - - try { - if (!onCanRemoveUnusedStyleImageListenerList.isEmpty()) { - boolean canRemove = true; - for (MapView.OnCanRemoveUnusedStyleImageListener listener : onCanRemoveUnusedStyleImageListenerList) { - canRemove &= listener.onCanRemoveUnusedStyleImage(imageId); - } - - return canRemove; - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onCanRemoveUnusedStyleImage", err); - throw err; - } - - return true; - } - - void addOnCameraWillChangeListener(MapView.OnCameraWillChangeListener listener) { - onCameraWillChangeListenerList.add(listener); - } - - void removeOnCameraWillChangeListener(MapView.OnCameraWillChangeListener listener) { - onCameraWillChangeListenerList.remove(listener); - } - - void addOnCameraIsChangingListener(MapView.OnCameraIsChangingListener listener) { - onCameraIsChangingListenerList.add(listener); - } - - void removeOnCameraIsChangingListener(MapView.OnCameraIsChangingListener listener) { - onCameraIsChangingListenerList.remove(listener); - } - - void addOnCameraDidChangeListener(MapView.OnCameraDidChangeListener listener) { - onCameraDidChangeListenerList.add(listener); - } - - void removeOnCameraDidChangeListener(MapView.OnCameraDidChangeListener listener) { - onCameraDidChangeListenerList.remove(listener); - } - - void addOnWillStartLoadingMapListener(MapView.OnWillStartLoadingMapListener listener) { - onWillStartLoadingMapListenerList.add(listener); - } - - void removeOnWillStartLoadingMapListener(MapView.OnWillStartLoadingMapListener listener) { - onWillStartLoadingMapListenerList.remove(listener); - } - - void addOnDidFinishLoadingMapListener(MapView.OnDidFinishLoadingMapListener listener) { - onDidFinishLoadingMapListenerList.add(listener); - } - - void removeOnDidFinishLoadingMapListener(MapView.OnDidFinishLoadingMapListener listener) { - onDidFinishLoadingMapListenerList.remove(listener); - } - - void addOnDidFailLoadingMapListener(MapView.OnDidFailLoadingMapListener listener) { - onDidFailLoadingMapListenerList.add(listener); - } - - void removeOnDidFailLoadingMapListener(MapView.OnDidFailLoadingMapListener listener) { - onDidFailLoadingMapListenerList.remove(listener); - } - - void addOnWillStartRenderingFrameListener(MapView.OnWillStartRenderingFrameListener listener) { - onWillStartRenderingFrameList.add(listener); - } - - void removeOnWillStartRenderingFrameListener(MapView.OnWillStartRenderingFrameListener listener) { - onWillStartRenderingFrameList.remove(listener); - } - - void addOnDidFinishRenderingFrameListener(MapView.OnDidFinishRenderingFrameListener listener) { - onDidFinishRenderingFrameList.add(listener); - } - - void removeOnDidFinishRenderingFrameListener(MapView.OnDidFinishRenderingFrameListener listener) { - onDidFinishRenderingFrameList.remove(listener); - } - - void addOnWillStartRenderingMapListener(MapView.OnWillStartRenderingMapListener listener) { - onWillStartRenderingMapListenerList.add(listener); - } - - void removeOnWillStartRenderingMapListener(MapView.OnWillStartRenderingMapListener listener) { - onWillStartRenderingMapListenerList.remove(listener); - } - - void addOnDidFinishRenderingMapListener(MapView.OnDidFinishRenderingMapListener listener) { - onDidFinishRenderingMapListenerList.add(listener); - } - - void removeOnDidFinishRenderingMapListener(MapView.OnDidFinishRenderingMapListener listener) { - onDidFinishRenderingMapListenerList.remove(listener); - } - - void addOnDidBecomeIdleListener(MapView.OnDidBecomeIdleListener listener) { - onDidBecomeIdleListenerList.add(listener); - } - - void removeOnDidBecomeIdleListener(MapView.OnDidBecomeIdleListener listener) { - onDidBecomeIdleListenerList.remove(listener); - } - - void addOnDidFinishLoadingStyleListener(MapView.OnDidFinishLoadingStyleListener listener) { - onDidFinishLoadingStyleListenerList.add(listener); - } - - void removeOnDidFinishLoadingStyleListener(MapView.OnDidFinishLoadingStyleListener listener) { - onDidFinishLoadingStyleListenerList.remove(listener); - } - - void addOnSourceChangedListener(MapView.OnSourceChangedListener listener) { - onSourceChangedListenerList.add(listener); - } - - void removeOnSourceChangedListener(MapView.OnSourceChangedListener listener) { - onSourceChangedListenerList.remove(listener); - } - - void addOnStyleImageMissingListener(MapView.OnStyleImageMissingListener listener) { - onStyleImageMissingListenerList.add(listener); - } - - void removeOnStyleImageMissingListener(MapView.OnStyleImageMissingListener listener) { - onStyleImageMissingListenerList.remove(listener); - } - - void addOnCanRemoveUnusedStyleImageListener(MapView.OnCanRemoveUnusedStyleImageListener listener) { - onCanRemoveUnusedStyleImageListenerList.add(listener); - } - - void removeOnCanRemoveUnusedStyleImageListener(MapView.OnCanRemoveUnusedStyleImageListener listener) { - onCanRemoveUnusedStyleImageListenerList.remove(listener); - } - - void clear() { - onCameraWillChangeListenerList.clear(); - onCameraIsChangingListenerList.clear(); - onCameraDidChangeListenerList.clear(); - onWillStartLoadingMapListenerList.clear(); - onDidFinishLoadingMapListenerList.clear(); - onDidFailLoadingMapListenerList.clear(); - onWillStartRenderingFrameList.clear(); - onDidFinishRenderingFrameList.clear(); - onWillStartRenderingMapListenerList.clear(); - onDidFinishRenderingMapListenerList.clear(); - onDidBecomeIdleListenerList.clear(); - onDidFinishLoadingStyleListenerList.clear(); - onSourceChangedListenerList.clear(); - onStyleImageMissingListenerList.clear(); - onCanRemoveUnusedStyleImageListenerList.clear(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapFragment.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapFragment.java deleted file mode 100644 index 8af9f2c6a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapFragment.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.app.Fragment; -import android.content.Context; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.util.AttributeSet; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.mapbox.mapboxsdk.utils.MapFragmentUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - * Fragment wrapper around a map view. - *

- * A Map component in an app. This fragment is the simplest way to place a map in an application. - * It's a wrapper around a view of a map to automatically handle the necessary life cycle needs. - * Being a fragment, this component can be added to an activity's layout or can dynamically be added - * using a FragmentManager. - *

- *

- * To get a reference to the MapView, use {@link #getMapAsync(OnMapReadyCallback)}} - *

- * - * @see #getMapAsync(OnMapReadyCallback) - */ -public final class MapFragment extends Fragment implements OnMapReadyCallback { - - private final List mapReadyCallbackList = new ArrayList<>(); - private OnMapViewReadyCallback mapViewReadyCallback; - private MapboxMap mapboxMap; - private MapView map; - - /** - * Creates a default MapFragment instance - * - * @return MapFragment instantiated - */ - public static MapFragment newInstance() { - return new MapFragment(); - } - - /** - * Creates a MapFragment instance - * - * @param mapboxMapOptions The configuration options to be used. - * @return MapFragment instantiated. - */ - @NonNull - public static MapFragment newInstance(@Nullable MapboxMapOptions mapboxMapOptions) { - MapFragment mapFragment = new MapFragment(); - mapFragment.setArguments(MapFragmentUtils.createFragmentArgs(mapboxMapOptions)); - return mapFragment; - } - - /** - * Called when this fragment is inflated, parses XML tag attributes. - * - * @param context The context inflating this fragment. - * @param attrs The XML tag attributes. - * @param savedInstanceState The saved instance state for the map fragment. - */ - @Override - public void onInflate(@NonNull Context context, AttributeSet attrs, Bundle savedInstanceState) { - super.onInflate(context, attrs, savedInstanceState); - setArguments(MapFragmentUtils.createFragmentArgs(MapboxMapOptions.createFromAttributes(context, attrs))); - } - - /** - * Called when the context attaches to this fragment. - * - * @param context the context attaching - */ - @Override - public void onAttach(Context context) { - super.onAttach(context); - if (context instanceof OnMapViewReadyCallback) { - mapViewReadyCallback = (OnMapViewReadyCallback) context; - } - } - - /** - * Creates the fragment view hierarchy. - * - * @param inflater Inflater used to inflate content. - * @param container The parent layout for the map fragment. - * @param savedInstanceState The saved instance state for the map fragment. - * @return The view created - */ - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - super.onCreateView(inflater, container, savedInstanceState); - Context context = inflater.getContext(); - map = new MapView(context, MapFragmentUtils.resolveArgs(context, getArguments())); - return map; - } - - /** - * Called when the fragment view hierarchy is created. - * - * @param view The content view of the fragment - * @param savedInstanceState The saved instance state of the fragment - */ - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - map.onCreate(savedInstanceState); - map.getMapAsync(this); - - // notify listeners about mapview creation - if (mapViewReadyCallback != null) { - mapViewReadyCallback.onMapViewReady(map); - } - } - - /** - * Called when the style of the map has successfully loaded. - * - * @param mapboxMap The public api controller of the map - */ - @Override - public void onMapReady(@NonNull MapboxMap mapboxMap) { - this.mapboxMap = mapboxMap; - for (OnMapReadyCallback onMapReadyCallback : mapReadyCallbackList) { - onMapReadyCallback.onMapReady(mapboxMap); - } - } - - /** - * Called when the fragment is visible for the users. - */ - @Override - public void onStart() { - super.onStart(); - map.onStart(); - } - - /** - * Called when the fragment is ready to be interacted with. - */ - @Override - public void onResume() { - super.onResume(); - map.onResume(); - } - - /** - * Called when the fragment is pausing. - */ - @Override - public void onPause() { - super.onPause(); - map.onPause(); - } - - /** - * Called when the fragment state needs to be saved. - * - * @param outState The saved state - */ - @Override - public void onSaveInstanceState(@NonNull Bundle outState) { - super.onSaveInstanceState(outState); - if (map != null && !map.isDestroyed()) { - map.onSaveInstanceState(outState); - } - } - - /** - * Called when the fragment is no longer visible for the user. - */ - @Override - public void onStop() { - super.onStop(); - map.onStop(); - } - - /** - * Called when the fragment receives onLowMemory call from the hosting Activity. - */ - @Override - public void onLowMemory() { - super.onLowMemory(); - if (map != null && !map.isDestroyed()) { - map.onLowMemory(); - } - } - - /** - * Called when the fragment is view hiearchy is being destroyed. - */ - @Override - public void onDestroyView() { - super.onDestroyView(); - map.onDestroy(); - } - - /** - * Called when the fragment is destroyed. - */ - @Override - public void onDestroy() { - super.onDestroy(); - mapReadyCallbackList.clear(); - } - - /** - * Sets a callback object which will be triggered when the MapboxMap instance is ready to be used. - * - * @param onMapReadyCallback The callback to be invoked. - */ - public void getMapAsync(@NonNull final OnMapReadyCallback onMapReadyCallback) { - if (mapboxMap == null) { - mapReadyCallbackList.add(onMapReadyCallback); - } else { - onMapReadyCallback.onMapReady(mapboxMap); - } - } - - /** - * Callback to be invoked when the map fragment has inflated its MapView. - *

- * To use this interface the context hosting the fragment must implement this interface. - * That instance will be set as part of Fragment#onAttach(Context context). - *

- */ - public interface OnMapViewReadyCallback { - - /** - * Called when the map has been created. - * - * @param mapView The created mapview - */ - void onMapViewReady(MapView mapView); - } -} 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 deleted file mode 100644 index 90e3934f7..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapGestureDetector.java +++ /dev/null @@ -1,1140 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.animation.Animator; -import android.animation.AnimatorListenerAdapter; -import android.animation.ValueAnimator; -import android.content.Context; -import android.content.res.Resources; -import android.graphics.PointF; -import android.os.Handler; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.InputDevice; -import android.view.MotionEvent; -import android.view.animation.DecelerateInterpolator; - -import com.mapbox.android.gestures.AndroidGesturesManager; -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.mapboxsdk.R; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -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.constants.MapboxConstants.MAXIMUM_ANGULAR_VELOCITY; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.MAX_ABSOLUTE_SCALE_VELOCITY_CHANGE; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.QUICK_ZOOM_MAX_ZOOM_CHANGE; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.ROTATE_VELOCITY_RATIO_THRESHOLD; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.SCALE_VELOCITY_ANIMATION_DURATION_MULTIPLIER; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.SCALE_VELOCITY_RATIO_THRESHOLD; -import static com.mapbox.mapboxsdk.constants.MapboxConstants.ZOOM_RATE; -import static com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_API_GESTURE; -import static com.mapbox.mapboxsdk.utils.MathUtils.normalize; - -/** - * Manages gestures events on a MapView. - */ -final class MapGestureDetector { - - private final Transform transform; - private final Projection projection; - private final UiSettings uiSettings; - private final AnnotationManager annotationManager; - private final CameraChangeDispatcher cameraChangeDispatcher; - - // new map touch API - private final CopyOnWriteArrayList onMapClickListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onMapLongClickListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onFlingListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onMoveListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onRotateListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onScaleListenerList - = new CopyOnWriteArrayList<>(); - - private final CopyOnWriteArrayList onShoveListenerList - = new CopyOnWriteArrayList<>(); - - /** - * User-set focal point. - */ - @Nullable - private PointF constantFocalPoint; - - @NonNull - private PointF doubleTapFocalPoint = new PointF(); - - private AndroidGesturesManager gesturesManager; - - private Animator scaleAnimator; - private Animator rotateAnimator; - private final List scheduledAnimators = new ArrayList<>(); - - /** - * Cancels scheduled velocity animations if user doesn't lift fingers within - * {@link MapboxConstants#SCHEDULED_ANIMATION_TIMEOUT} - */ - @NonNull - private Handler animationsTimeoutHandler = new Handler(); - - private boolean doubleTapRegistered; - - MapGestureDetector(@Nullable Context context, Transform transform, Projection projection, UiSettings uiSettings, - AnnotationManager annotationManager, CameraChangeDispatcher cameraChangeDispatcher) { - this.annotationManager = annotationManager; - this.transform = transform; - this.projection = projection; - this.uiSettings = uiSettings; - this.cameraChangeDispatcher = cameraChangeDispatcher; - - // Checking for context != null for testing purposes - if (context != null) { - // Initialize gestures manager - AndroidGesturesManager androidGesturesManager = new AndroidGesturesManager(context); - initializeGesturesManager(androidGesturesManager, true); - - // Initialize gesture listeners - initializeGestureListeners(context, true); - } - } - - private void initializeGestureListeners(@NonNull Context context, boolean attachDefaultListeners) { - if (attachDefaultListeners) { - StandardGestureListener standardGestureListener = new StandardGestureListener( - context.getResources().getDimension( - com.mapbox.android.gestures.R.dimen.mapbox_defaultScaleSpanSinceStartThreshold)); - MoveGestureListener moveGestureListener = new MoveGestureListener(); - ScaleGestureListener scaleGestureListener = new ScaleGestureListener( - context.getResources().getDimension(R.dimen.mapbox_density_constant), - context.getResources().getDimension(R.dimen.mapbox_minimum_scale_speed), - context.getResources().getDimension(R.dimen.mapbox_minimum_angled_scale_speed), - 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_density_constant), - context.getResources().getDimension(R.dimen.mapbox_angular_velocity_multiplier), - context.getResources().getDimension(R.dimen.mapbox_minimum_angular_velocity), - context.getResources().getDimension( - com.mapbox.android.gestures.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(@NonNull AndroidGesturesManager androidGesturesManager, - boolean setDefaultMutuallyExclusives) { - if (setDefaultMutuallyExclusives) { - Set shoveScaleSet = new HashSet<>(); - shoveScaleSet.add(AndroidGesturesManager.GESTURE_TYPE_SHOVE); - shoveScaleSet.add(AndroidGesturesManager.GESTURE_TYPE_SCALE); - - Set shoveRotateSet = new HashSet<>(); - shoveRotateSet.add(AndroidGesturesManager.GESTURE_TYPE_SHOVE); - shoveRotateSet.add(AndroidGesturesManager.GESTURE_TYPE_ROTATE); - - Set ScaleLongPressSet = new HashSet<>(); - ScaleLongPressSet.add(AndroidGesturesManager.GESTURE_TYPE_SCALE); - ScaleLongPressSet.add(AndroidGesturesManager.GESTURE_TYPE_LONG_PRESS); - - androidGesturesManager.setMutuallyExclusiveGestures(shoveScaleSet, shoveRotateSet, ScaleLongPressSet); - } - - gesturesManager = androidGesturesManager; - gesturesManager.getRotateGestureDetector().setAngleThreshold(3f); - } - - /** - * Set the gesture focal point. - *

- * This is the center point used for calculate transformations from gestures, value is - * overridden if end user provides his own through {@link UiSettings#setFocalPoint(PointF)}. - *

- * - * @param focalPoint the center point for gestures - */ - void setFocalPoint(@Nullable PointF focalPoint) { - if (focalPoint == null) { - // resetting focal point, - if (uiSettings.getFocalPoint() != null) { - // using user provided one to reset - focalPoint = uiSettings.getFocalPoint(); - } - } - this.constantFocalPoint = focalPoint; - } - - /** - * Called when user touches the screen, all positions are absolute. - *

- * Forwards event to the related gesture detectors. - *

- * - * @param motionEvent the MotionEvent - * @return True if touch event is handled - */ - boolean onTouchEvent(@Nullable 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 ((motionEvent.getButtonState() != 0) && (motionEvent.getButtonState() != MotionEvent.BUTTON_PRIMARY)) { - return false; - } - - if (motionEvent.getActionMasked() == MotionEvent.ACTION_DOWN) { - cancelAnimators(); - transform.setGestureInProgress(true); - } - - boolean result = gesturesManager.onTouchEvent(motionEvent); - - switch (motionEvent.getActionMasked()) { - case MotionEvent.ACTION_POINTER_DOWN: - doubleTapFinished(); - break; - - case MotionEvent.ACTION_UP: - doubleTapFinished(); - transform.setGestureInProgress(false); - - if (!scheduledAnimators.isEmpty()) { - // Start all awaiting velocity animations - animationsTimeoutHandler.removeCallbacksAndMessages(null); - for (Animator animator : scheduledAnimators) { - animator.start(); - } - scheduledAnimators.clear(); - } - break; - - case MotionEvent.ACTION_CANCEL: - scheduledAnimators.clear(); - transform.setGestureInProgress(false); - doubleTapFinished(); - break; - } - - return result; - } - - void cancelAnimators() { - animationsTimeoutHandler.removeCallbacksAndMessages(null); - scheduledAnimators.clear(); - - cancelAnimator(scaleAnimator); - cancelAnimator(rotateAnimator); - - dispatchCameraIdle(); - } - - private void cancelAnimator(@Nullable Animator animator) { - if (animator != null && animator.isStarted()) { - animator.cancel(); - } - } - - /** - * Posted on main thread with {@link #animationsTimeoutHandler}. Cancels all scheduled animators if needed. - */ - @NonNull - private final Runnable cancelAnimatorsRunnable = new Runnable() { - @Override - public void run() { - cancelAnimators(); - } - }; - - /** - * Schedules a velocity animator to be executed when user lifts 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); - } - - /** - * Called for events that don't fit the other handlers. - *

- * Examples of such events are mouse scroll events, mouse moves, joystick & trackpad. - *

- * - * @param event The MotionEvent occurred - * @return True is the event is handled - */ - boolean onGenericMotionEvent(MotionEvent event) { - // Mouse events - // if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { // this is not available before API 18 - if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) == InputDevice.SOURCE_CLASS_POINTER) { - // Choose the action - switch (event.getActionMasked()) { - // Mouse scrolls - case MotionEvent.ACTION_SCROLL: - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Get the vertical scroll amount, one click = 1 - float scrollDist = event.getAxisValue(MotionEvent.AXIS_VSCROLL); - - // Scale the map by the appropriate power of two factor - transform.zoomBy(scrollDist, new PointF(event.getX(), event.getY())); - - return true; - - default: - // We are not interested in this event - return false; - } - } - - // We are not interested in this event - return false; - } - - private final class StandardGestureListener extends StandardGestureDetector.SimpleStandardOnGestureListener { - private final float doubleTapMovementThreshold; - - StandardGestureListener(float doubleTapMovementThreshold) { - this.doubleTapMovementThreshold = doubleTapMovementThreshold; - } - - @Override - public boolean onDown(MotionEvent motionEvent) { - return true; - } - - @Override - public boolean onSingleTapUp(MotionEvent motionEvent) { - transform.cancelTransitions(); - return true; - } - - @Override - public boolean onSingleTapConfirmed(MotionEvent motionEvent) { - PointF tapPoint = new PointF(motionEvent.getX(), motionEvent.getY()); - boolean tapHandled = annotationManager.onTap(tapPoint); - - if (!tapHandled) { - if (uiSettings.isDeselectMarkersOnTap()) { - // deselect any selected marker - annotationManager.deselectMarkers(); - } - - notifyOnMapClickListeners(tapPoint); - } - - return true; - } - - @Override - public boolean onDoubleTapEvent(MotionEvent motionEvent) { - int action = motionEvent.getActionMasked(); - if (action == MotionEvent.ACTION_DOWN) { - doubleTapFocalPoint = new PointF(motionEvent.getX(), motionEvent.getY()); - doubleTapStarted(); - } - - if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) { - float diffX = Math.abs(motionEvent.getX() - doubleTapFocalPoint.x); - float diffY = Math.abs(motionEvent.getY() - doubleTapFocalPoint.y); - if (diffX > doubleTapMovementThreshold || diffY > doubleTapMovementThreshold) { - // Ignore double-tap event because we've started the quick-zoom. See #14013. - return false; - } - - if (!uiSettings.isZoomGesturesEnabled() || !uiSettings.isDoubleTapGesturesEnabled()) { - return false; - } - - // Single finger double tap - if (constantFocalPoint != null) { - // User provided focal point - doubleTapFocalPoint = constantFocalPoint; - } - - zoomInAnimated(doubleTapFocalPoint, false); - - 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 (!uiSettings.isScrollGesturesEnabled()) { - // don't allow a fling if scroll is disabled - return false; - } - - notifyOnFlingListeners(); - - if (!uiSettings.isFlingVelocityAnimationEnabled()) { - return false; - } - - float screenDensity = uiSettings.getPixelRatio(); - - // calculate velocity vector for xy dimensions, independent from screen size - double velocityXY = Math.hypot(velocityX / screenDensity, velocityY / screenDensity); - if (velocityXY < MapboxConstants.VELOCITY_THRESHOLD_IGNORE_FLING) { - // ignore short flings, these can occur when other gestures just have finished executing - return false; - } - - transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - - // tilt results in a bigger translation, limiting input for #5281 - double tilt = transform.getTilt(); - double tiltFactor = 1.5 + ((tilt != 0) ? (tilt / 10) : 0); - double offsetX = velocityX / tiltFactor / screenDensity; - double offsetY = velocityY / tiltFactor / screenDensity; - - // calculate animation time based on displacement - long animationTime = (long) (velocityXY / 7 / tiltFactor + MapboxConstants.ANIMATION_DURATION_FLING_BASE); - - // update transformation - transform.moveBy(offsetX, offsetY, animationTime); - - return true; - } - } - - private void doubleTapStarted() { - // disable the move detector in preparation for the quickzoom, - // so that we don't move the map's center slightly before the quickzoom is started (see #14227) - gesturesManager.getMoveGestureDetector().setEnabled(false); - doubleTapRegistered = true; - } - - private void doubleTapFinished() { - if (doubleTapRegistered) { - // re-enable the move detector in case of double tap - gesturesManager.getMoveGestureDetector().setEnabled(true); - doubleTapRegistered = false; - } - } - - private final class MoveGestureListener extends MoveGestureDetector.SimpleOnMoveGestureListener { - @Override - public boolean onMoveBegin(@NonNull MoveGestureDetector detector) { - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - cancelTransitionsIfRequired(); - notifyOnMoveBeginListeners(detector); - return true; - } - - @Override - public boolean onMove(@NonNull MoveGestureDetector detector, float distanceX, float distanceY) { - // first move event is often delivered with no displacement - if (distanceX != 0 || distanceY != 0) { - // dispatching camera start event only when the movement actually occurred - cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); - - // Scroll the map - transform.moveBy(-distanceX, -distanceY, 0 /*no duration*/); - - notifyOnMoveListeners(detector); - } - return true; - } - - @Override - public void onMoveEnd(@NonNull MoveGestureDetector detector, float velocityX, float velocityY) { - dispatchCameraIdle(); - notifyOnMoveEndListeners(detector); - } - } - - private final class ScaleGestureListener extends StandardScaleGestureDetector.SimpleStandardOnScaleGestureListener { - - private final float minimumGestureSpeed; - private final float minimumAngledGestureSpeed; - private final float minimumVelocity; - private final double scaleVelocityRatioThreshold; - private boolean quickZoom; - private float spanSinceLast; - private double screenHeight; - private double startZoom; - - ScaleGestureListener(double densityMultiplier, float minimumGestureSpeed, float minimumAngledGestureSpeed, - float minimumVelocity) { - this.minimumGestureSpeed = minimumGestureSpeed; - this.minimumAngledGestureSpeed = minimumAngledGestureSpeed; - this.minimumVelocity = minimumVelocity; - this.scaleVelocityRatioThreshold = SCALE_VELOCITY_RATIO_THRESHOLD * densityMultiplier; - } - - @Override - public boolean onScaleBegin(@NonNull StandardScaleGestureDetector detector) { - quickZoom = detector.getPointersCount() == 1; - - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } - - if (quickZoom) { - if (!uiSettings.isQuickZoomGesturesEnabled()) { - return false; - } - // re-try disabling the move detector in case double tap has been interrupted before quickzoom started - gesturesManager.getMoveGestureDetector().setEnabled(false); - } else { - if (detector.getPreviousSpan() > 0) { - float currSpan = detector.getCurrentSpan(); - float prevSpan = detector.getPreviousSpan(); - double currTime = detector.getCurrentEvent().getEventTime(); - double prevTime = detector.getPreviousEvent().getEventTime(); - if (currTime == prevTime) { - return false; - } - double speed = Math.abs(currSpan - prevSpan) / (currTime - prevTime); - if (speed < minimumGestureSpeed) { - // do not scale if the minimal gesture speed is not met - return false; - } else if (!gesturesManager.getRotateGestureDetector().isInProgress()) { - float rotationDeltaSinceLast = gesturesManager.getRotateGestureDetector().getDeltaSinceLast(); - if (Math.abs(rotationDeltaSinceLast) > 0.4 && speed < minimumAngledGestureSpeed) { - // do not scale in case we're preferring to start rotation - return false; - } - - if (uiSettings.isDisableRotateWhenScaling()) { - // disable rotate gesture when scale is detected first - gesturesManager.getRotateGestureDetector().setEnabled(false); - } - } - } else { - return false; - } - } - - screenHeight = Resources.getSystem().getDisplayMetrics().heightPixels; - startZoom = transform.getRawZoom(); - - cancelTransitionsIfRequired(); - - notifyOnScaleBeginListeners(detector); - - spanSinceLast = Math.abs(detector.getCurrentSpan() - detector.getPreviousSpan()); - - return true; - } - - @Override - public boolean onScale(@NonNull StandardScaleGestureDetector detector) { - // dispatching camera start event only when the movement actually occurred - cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); - - PointF focalPoint = getScaleFocalPoint(detector); - if (quickZoom) { - double pixelDeltaChange = Math.abs(detector.getCurrentEvent().getY() - doubleTapFocalPoint.y); - boolean zoomedOut = detector.getCurrentEvent().getY() < doubleTapFocalPoint.y; - - // normalize the pixel delta change, ranging from 0 to screen height, to a constant zoom change range - double normalizedDeltaChange = normalize(pixelDeltaChange, 0, screenHeight, 0, QUICK_ZOOM_MAX_ZOOM_CHANGE); - - // calculate target zoom and adjust for a multiplier - double targetZoom = (zoomedOut ? startZoom - normalizedDeltaChange : startZoom + normalizedDeltaChange); - targetZoom *= uiSettings.getZoomRate(); - - transform.setZoom(targetZoom, focalPoint); - } else { - double zoomBy = - (Math.log(detector.getScaleFactor()) / Math.log(Math.PI / 2)) * ZOOM_RATE * uiSettings.getZoomRate(); - transform.zoomBy(zoomBy, focalPoint); - } - - notifyOnScaleListeners(detector); - - spanSinceLast = Math.abs(detector.getCurrentSpan() - detector.getPreviousSpan()); - - return true; - } - - @Override - public void onScaleEnd(@NonNull StandardScaleGestureDetector detector, float velocityX, float velocityY) { - if (quickZoom) { - // re-enabled the move detector if the quickzoom happened - gesturesManager.getMoveGestureDetector().setEnabled(true); - } else { - // re-enable rotation in case it's been disabled - gesturesManager.getRotateGestureDetector().setEnabled(true); - } - - notifyOnScaleEndListeners(detector); - - float velocityXY = Math.abs(velocityX) + Math.abs(velocityY); - - if (!uiSettings.isScaleVelocityAnimationEnabled() - || velocityXY < minimumVelocity - || spanSinceLast / velocityXY < scaleVelocityRatioThreshold) { - // notifying listeners that camera is idle only if there is no follow-up animation - dispatchCameraIdle(); - return; - } - - double zoomAddition = calculateScale(velocityXY, detector.isScalingOut()); - double currentZoom = transform.getRawZoom(); - PointF focalPoint = getScaleFocalPoint(detector); - // (log(x + 1 / e^2) + 2) * 150, x=0 to 2.5 (MapboxConstants#MAX_ABSOLUTE_SCALE_VELOCITY_CHANGE) - long animationTime = (long) ((Math.log((Math.abs(zoomAddition)) + 1 / Math.pow(Math.E, 2)) + 2) - * SCALE_VELOCITY_ANIMATION_DURATION_MULTIPLIER); - scaleAnimator = createScaleAnimator(currentZoom, zoomAddition, focalPoint, animationTime); - scheduleAnimator(scaleAnimator); - } - - @NonNull - private PointF getScaleFocalPoint(@NonNull StandardScaleGestureDetector detector) { - if (constantFocalPoint != null) { - // around user provided focal point - return constantFocalPoint; - } else if (quickZoom) { - // around center - return new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - } else { - // around gesture - return detector.getFocalPoint(); - } - } - - private double calculateScale(double velocityXY, boolean isScalingOut) { - double zoomAddition = velocityXY * MAX_ABSOLUTE_SCALE_VELOCITY_CHANGE * 1e-4; - zoomAddition = MathUtils.clamp(zoomAddition, 0, MAX_ABSOLUTE_SCALE_VELOCITY_CHANGE); - if (isScalingOut) { - zoomAddition = -zoomAddition; - } - return zoomAddition; - } - } - - private final class RotateGestureListener extends RotateGestureDetector.SimpleOnRotateGestureListener { - private final float minimumScaleSpanWhenRotating; - private final float angularVelocityMultiplier; - private final float minimumAngularVelocity; - private final double rotateVelocityRatioThreshold; - private final float defaultSpanSinceStartThreshold; - - RotateGestureListener(float minimumScaleSpanWhenRotating, double densityMultiplier, float angularVelocityMultiplier, - float minimumAngularVelocity, float defaultSpanSinceStartThreshold) { - this.minimumScaleSpanWhenRotating = minimumScaleSpanWhenRotating; - this.angularVelocityMultiplier = angularVelocityMultiplier; - this.minimumAngularVelocity = minimumAngularVelocity; - this.rotateVelocityRatioThreshold = ROTATE_VELOCITY_RATIO_THRESHOLD * densityMultiplier; - this.defaultSpanSinceStartThreshold = defaultSpanSinceStartThreshold; - } - - @Override - public boolean onRotateBegin(@NonNull RotateGestureDetector detector) { - if (!uiSettings.isRotateGesturesEnabled()) { - return false; - } - - float deltaSinceLast = Math.abs(detector.getDeltaSinceLast()); - double currTime = detector.getCurrentEvent().getEventTime(); - double prevTime = detector.getPreviousEvent().getEventTime(); - if (currTime == prevTime) { - return false; - } - double speed = deltaSinceLast / (currTime - prevTime); - float deltaSinceStart = Math.abs(detector.getDeltaSinceStart()); - - // adjust the responsiveness of a rotation gesture - the higher the speed, the bigger the threshold - if (speed < 0.04 - || (speed > 0.07 && deltaSinceStart < 5) - || (speed > 0.15 && deltaSinceStart < 7) - || (speed > 0.5 && deltaSinceStart < 15) - ) { - return false; - } - - 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(); - } - - cancelTransitionsIfRequired(); - - notifyOnRotateBeginListeners(detector); - - return true; - } - - @Override - public boolean onRotate(@NonNull RotateGestureDetector detector, float rotationDegreesSinceLast, - float rotationDegreesSinceFirst) { - // dispatching camera start event only when the movement actually occurred - cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); - - // Calculate map bearing value - double bearing = transform.getRawBearing() + rotationDegreesSinceLast; - - // Rotate the map - PointF focalPoint = getRotateFocalPoint(detector); - transform.setBearing(bearing, focalPoint.x, focalPoint.y); - - notifyOnRotateListeners(detector); - - return true; - } - - @Override - public void onRotateEnd(@NonNull RotateGestureDetector detector, float velocityX, - float velocityY, float angularVelocity) { - if (uiSettings.isIncreaseScaleThresholdWhenRotating()) { - // resetting default scale threshold values - gesturesManager.getStandardScaleGestureDetector().setSpanSinceStartThreshold(defaultSpanSinceStartThreshold); - } - - notifyOnRotateEndListeners(detector); - - angularVelocity = angularVelocity * angularVelocityMultiplier; - angularVelocity = MathUtils.clamp(angularVelocity, -MAXIMUM_ANGULAR_VELOCITY, MAXIMUM_ANGULAR_VELOCITY); - - float velocityXY = Math.abs(velocityX) + Math.abs(velocityY); - float delta = Math.abs(detector.getDeltaSinceLast()); - double ratio = delta / velocityXY; - - if (!uiSettings.isRotateVelocityAnimationEnabled() - || Math.abs(angularVelocity) < minimumAngularVelocity - || (gesturesManager.getStandardScaleGestureDetector().isInProgress() && ratio < rotateVelocityRatioThreshold)) { - // notifying listeners that camera is idle only if there is no follow-up animation - dispatchCameraIdle(); - return; - } - - long animationTime = (long) ((Math.log((Math.abs(angularVelocity)) + 1 / Math.pow(Math.E, 2)) + 2) - * SCALE_VELOCITY_ANIMATION_DURATION_MULTIPLIER); - - PointF focalPoint = getRotateFocalPoint(detector); - rotateAnimator = createRotateAnimator(angularVelocity, animationTime, focalPoint); - scheduleAnimator(rotateAnimator); - } - - @NonNull - private PointF getRotateFocalPoint(@NonNull RotateGestureDetector detector) { - if (constantFocalPoint != null) { - // User provided focal point - return constantFocalPoint; - } else { - // around gesture - return detector.getFocalPoint(); - } - } - - private Animator createRotateAnimator(float angularVelocity, long animationTime, - @NonNull final PointF animationFocalPoint) { - ValueAnimator animator = ValueAnimator.ofFloat(angularVelocity, 0f); - animator.setDuration(animationTime); - animator.setInterpolator(new DecelerateInterpolator()); - animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { - @Override - public void onAnimationUpdate(@NonNull ValueAnimator animation) { - transform.setBearing( - transform.getRawBearing() + (float) animation.getAnimatedValue(), - animationFocalPoint.x, animationFocalPoint.y, - 0L - ); - } - }); - - animator.addListener(new AnimatorListenerAdapter() { - - @Override - public void onAnimationStart(Animator animation) { - transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - } - - @Override - public void onAnimationCancel(Animator animation) { - transform.cancelTransitions(); - } - - @Override - public void onAnimationEnd(Animator animation) { - dispatchCameraIdle(); - } - }); - - return animator; - } - } - - private final class ShoveGestureListener extends ShoveGestureDetector.SimpleOnShoveGestureListener { - @Override - public boolean onShoveBegin(@NonNull ShoveGestureDetector detector) { - if (!uiSettings.isTiltGesturesEnabled()) { - return false; - } - - cancelTransitionsIfRequired(); - - // disabling move gesture during shove - gesturesManager.getMoveGestureDetector().setEnabled(false); - - notifyOnShoveBeginListeners(detector); - - return true; - } - - @Override - public boolean onShove(@NonNull ShoveGestureDetector detector, - float deltaPixelsSinceLast, float deltaPixelsSinceStart) { - // dispatching camera start event only when the movement actually occurred - cameraChangeDispatcher.onCameraMoveStarted(CameraChangeDispatcher.REASON_API_GESTURE); - - // 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); - - // Tilt the map - transform.setTilt(pitch); - - notifyOnShoveListeners(detector); - - return true; - } - - @Override - public void onShoveEnd(@NonNull ShoveGestureDetector detector, float velocityX, float velocityY) { - dispatchCameraIdle(); - - // re-enabling move gesture - gesturesManager.getMoveGestureDetector().setEnabled(true); - - notifyOnShoveEndListeners(detector); - } - } - - private final class TapGestureListener implements MultiFingerTapGestureDetector.OnMultiFingerTapGestureListener { - @Override - public boolean onMultiFingerTap(@NonNull MultiFingerTapGestureDetector detector, int pointersCount) { - if (!uiSettings.isZoomGesturesEnabled() || pointersCount != 2) { - return false; - } - - transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - - PointF zoomFocalPoint; - // Single finger double tap - if (constantFocalPoint != null) { - // User provided focal point - zoomFocalPoint = constantFocalPoint; - } else { - // Zoom in on gesture - zoomFocalPoint = detector.getFocalPoint(); - } - - zoomOutAnimated(zoomFocalPoint, false); - - return true; - } - } - - private Animator createScaleAnimator(double currentZoom, double zoomAddition, - @NonNull 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(@NonNull ValueAnimator animation) { - transform.setZoom((Float) animation.getAnimatedValue(), animationFocalPoint); - } - }); - - animator.addListener(new AnimatorListenerAdapter() { - - @Override - public void onAnimationStart(Animator animation) { - transform.cancelTransitions(); - cameraChangeDispatcher.onCameraMoveStarted(REASON_API_GESTURE); - } - - @Override - public void onAnimationCancel(Animator animation) { - transform.cancelTransitions(); - } - - @Override - public void onAnimationEnd(Animator animation) { - dispatchCameraIdle(); - } - }); - 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(@NonNull 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(@NonNull PointF zoomFocalPoint, boolean runImmediately) { - zoomAnimated(false, zoomFocalPoint, runImmediately); - } - - private void zoomAnimated(boolean zoomIn, @NonNull 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 dispatchCameraIdle() { - // we need to dispatch camera idle callback only if there is no other gestures in progress - if (noGesturesInProgress()) { - // invalidate the camera position, so that it's valid when fetched from the #onIdle event - // and doesn't rely on the last frame being rendered - transform.invalidateCameraPosition(); - cameraChangeDispatcher.onCameraIdle(); - } - } - - private void cancelTransitionsIfRequired() { - // we need to cancel core transitions only if there is no started gesture yet - if (noGesturesInProgress()) { - transform.cancelTransitions(); - } - } - - private boolean noGesturesInProgress() { - return (!uiSettings.isScrollGesturesEnabled() || !gesturesManager.getMoveGestureDetector().isInProgress()) - && (!uiSettings.isZoomGesturesEnabled() || !gesturesManager.getStandardScaleGestureDetector().isInProgress()) - && (!uiSettings.isRotateGesturesEnabled() || !gesturesManager.getRotateGestureDetector().isInProgress()) - && (!uiSettings.isTiltGesturesEnabled() || !gesturesManager.getShoveGestureDetector().isInProgress()); - } - - void notifyOnMapClickListeners(@NonNull PointF tapPoint) { - for (MapboxMap.OnMapClickListener listener : onMapClickListenerList) { - if (listener.onMapClick(projection.fromScreenLocation(tapPoint))) { - return; - } - } - } - - void notifyOnMapLongClickListeners(@NonNull PointF longClickPoint) { - for (MapboxMap.OnMapLongClickListener listener : onMapLongClickListenerList) { - if (listener.onMapLongClick(projection.fromScreenLocation(longClickPoint))) { - return; - } - } - } - - void notifyOnFlingListeners() { - for (MapboxMap.OnFlingListener listener : onFlingListenerList) { - listener.onFling(); - } - } - - void notifyOnMoveBeginListeners(@NonNull MoveGestureDetector detector) { - for (MapboxMap.OnMoveListener listener : onMoveListenerList) { - listener.onMoveBegin(detector); - } - } - - void notifyOnMoveListeners(@NonNull MoveGestureDetector detector) { - for (MapboxMap.OnMoveListener listener : onMoveListenerList) { - listener.onMove(detector); - } - } - - void notifyOnMoveEndListeners(@NonNull MoveGestureDetector detector) { - for (MapboxMap.OnMoveListener listener : onMoveListenerList) { - listener.onMoveEnd(detector); - } - } - - void notifyOnRotateBeginListeners(@NonNull RotateGestureDetector detector) { - for (MapboxMap.OnRotateListener listener : onRotateListenerList) { - listener.onRotateBegin(detector); - } - } - - void notifyOnRotateListeners(@NonNull RotateGestureDetector detector) { - for (MapboxMap.OnRotateListener listener : onRotateListenerList) { - listener.onRotate(detector); - } - } - - void notifyOnRotateEndListeners(@NonNull RotateGestureDetector detector) { - for (MapboxMap.OnRotateListener listener : onRotateListenerList) { - listener.onRotateEnd(detector); - } - } - - void notifyOnScaleBeginListeners(@NonNull StandardScaleGestureDetector detector) { - for (MapboxMap.OnScaleListener listener : onScaleListenerList) { - listener.onScaleBegin(detector); - } - } - - void notifyOnScaleListeners(@NonNull StandardScaleGestureDetector detector) { - for (MapboxMap.OnScaleListener listener : onScaleListenerList) { - listener.onScale(detector); - } - } - - void notifyOnScaleEndListeners(@NonNull StandardScaleGestureDetector detector) { - for (MapboxMap.OnScaleListener listener : onScaleListenerList) { - listener.onScaleEnd(detector); - } - } - - void notifyOnShoveBeginListeners(@NonNull ShoveGestureDetector detector) { - for (MapboxMap.OnShoveListener listener : onShoveListenerList) { - listener.onShoveBegin(detector); - } - } - - void notifyOnShoveListeners(@NonNull ShoveGestureDetector detector) { - for (MapboxMap.OnShoveListener listener : onShoveListenerList) { - listener.onShove(detector); - } - } - - void notifyOnShoveEndListeners(@NonNull ShoveGestureDetector detector) { - for (MapboxMap.OnShoveListener listener : onShoveListenerList) { - listener.onShoveEnd(detector); - } - } - - void addOnMapClickListener(MapboxMap.OnMapClickListener onMapClickListener) { - onMapClickListenerList.add(onMapClickListener); - } - - void removeOnMapClickListener(MapboxMap.OnMapClickListener onMapClickListener) { - onMapClickListenerList.remove(onMapClickListener); - } - - void addOnMapLongClickListener(MapboxMap.OnMapLongClickListener onMapLongClickListener) { - onMapLongClickListenerList.add(onMapLongClickListener); - } - - void removeOnMapLongClickListener(MapboxMap.OnMapLongClickListener onMapLongClickListener) { - onMapLongClickListenerList.remove(onMapLongClickListener); - } - - void addOnFlingListener(MapboxMap.OnFlingListener onFlingListener) { - onFlingListenerList.add(onFlingListener); - } - - void removeOnFlingListener(MapboxMap.OnFlingListener onFlingListener) { - onFlingListenerList.remove(onFlingListener); - } - - 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(@NonNull Context context, @NonNull 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 deleted file mode 100644 index afb80027d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapKeyListener.java +++ /dev/null @@ -1,271 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.PointF; -import android.os.Handler; -import android.os.Looper; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.view.KeyEvent; -import android.view.MotionEvent; -import android.view.ViewConfiguration; - -/** - * Manages key events on a MapView. - *

- *

    - *
  • Uses {@link Transform} to change the map state
  • - *
  • Uses {@link UiSettings} to verify validity of user restricted movement.
  • - *
- *

- */ -final class MapKeyListener { - - private final Transform transform; - private final UiSettings uiSettings; - private final MapGestureDetector mapGestureDetector; - - @Nullable - private TrackballLongPressTimeOut currentTrackballLongPressTimeOut; - - MapKeyListener(Transform transform, UiSettings uiSettings, MapGestureDetector mapGestureDetector) { - this.transform = transform; - this.uiSettings = uiSettings; - this.mapGestureDetector = mapGestureDetector; - } - - /** - * Called when the user presses a key, alse called for repeated keys held down. - * - * @param keyCode the id of the pressed key - * @param event the related key event - * @return true if the wevent is handled - */ - boolean onKeyDown(int keyCode, @NonNull KeyEvent event) { - // If the user has held the scroll key down for a while then accelerate - // the scroll speed - double scrollDist = event.getRepeatCount() >= 5 ? 50.0 : 10.0; - - // Check which key was pressed via hardware/real key code - switch (keyCode) { - // Tell the system to track these keys for long presses on - // onKeyLongPress is fired - case KeyEvent.KEYCODE_ENTER: - case KeyEvent.KEYCODE_DPAD_CENTER: - event.startTracking(); - return true; - - case KeyEvent.KEYCODE_DPAD_LEFT: - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Move left - transform.moveBy(scrollDist, 0.0, 0 /*no animation*/); - return true; - - case KeyEvent.KEYCODE_DPAD_RIGHT: - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Move right - transform.moveBy(-scrollDist, 0.0, 0 /*no animation*/); - return true; - - case KeyEvent.KEYCODE_DPAD_UP: - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Move up - transform.moveBy(0.0, scrollDist, 0 /*no animation*/); - return true; - - case KeyEvent.KEYCODE_DPAD_DOWN: - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Move down - transform.moveBy(0.0, -scrollDist, 0 /*no animation*/); - return true; - - default: - // We are not interested in this key - return false; - } - } - - /** - * Called when the user long presses a key that is being tracked. - * - * @param keyCode the id of the long pressed key - * @param event the related key event - * @return true if event is handled - */ - boolean onKeyLongPress(int keyCode, KeyEvent event) { - // Check which key was pressed via hardware/real key code - switch (keyCode) { - // Tell the system to track these keys for long presses on - // onKeyLongPress is fired - case KeyEvent.KEYCODE_ENTER: - case KeyEvent.KEYCODE_DPAD_CENTER: - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } - - // Zoom out - PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - mapGestureDetector.zoomOutAnimated(focalPoint, true); - return true; - - default: - // We are not interested in this key - return false; - } - } - - /** - * Called when the user releases a key. - * - * @param keyCode the id of the released key - * @param event the related key event - * @return true if the event is handled - */ - boolean onKeyUp(int keyCode, KeyEvent event) { - // Check if the key action was canceled (used for virtual keyboards) - if (event.isCanceled()) { - return false; - } - - // Check which key was pressed via hardware/real key code - // Note if keyboard does not have physical key (ie primary non-shifted - // key) then it will not appear here - // Must use the key character map as physical to character is not - // fixed/guaranteed - switch (keyCode) { - case KeyEvent.KEYCODE_ENTER: - case KeyEvent.KEYCODE_DPAD_CENTER: - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } - - // Zoom in - PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - mapGestureDetector.zoomInAnimated(focalPoint, true); - return true; - } - - // We are not interested in this key - return false; - } - - /** - * Called for trackball events, all motions are relative in device specific units. - * - * @param event the related motion event - * @return true if the event is handled - */ - boolean onTrackballEvent(MotionEvent event) { - // Choose the action - switch (event.getActionMasked()) { - // The trackball was rotated - case MotionEvent.ACTION_MOVE: - if (!uiSettings.isScrollGesturesEnabled()) { - return false; - } - - // Cancel any animation - transform.cancelTransitions(); - - // Scroll the map - transform.moveBy(-10.0 * event.getX(), -10.0 * event.getY(), 0 /*no animation*/); - return true; - - // Trackball was pushed in so start tracking and tell system we are - // interested - // We will then get the up action - case MotionEvent.ACTION_DOWN: - // Set up a delayed callback to check if trackball is still - // After waiting the system long press time out - if (currentTrackballLongPressTimeOut != null) { - currentTrackballLongPressTimeOut.cancel(); - currentTrackballLongPressTimeOut = null; - } - currentTrackballLongPressTimeOut = new TrackballLongPressTimeOut(); - new Handler(Looper.getMainLooper()).postDelayed(currentTrackballLongPressTimeOut, - ViewConfiguration.getLongPressTimeout()); - return true; - - // Trackball was released - case MotionEvent.ACTION_UP: - if (!uiSettings.isZoomGesturesEnabled()) { - return false; - } - - // Only handle if we have not already long pressed - if (currentTrackballLongPressTimeOut != null) { - // Zoom in - PointF focalPoint = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - mapGestureDetector.zoomInAnimated(focalPoint, true); - } - return true; - - // Trackball was cancelled - case MotionEvent.ACTION_CANCEL: - if (currentTrackballLongPressTimeOut != null) { - currentTrackballLongPressTimeOut.cancel(); - currentTrackballLongPressTimeOut = null; - } - return true; - - default: - // We are not interested in this event - return false; - } - } - - /** - * This class implements the trackball long press time out callback - */ - private class TrackballLongPressTimeOut implements Runnable { - - // Track if we have been cancelled - private boolean cancelled; - - TrackballLongPressTimeOut() { - cancelled = false; - } - - // Cancel the timeout - public void cancel() { - cancelled = true; - } - - // Called when long press time out expires - @Override - public void run() { - // Check if the trackball is still pressed - if (!cancelled) { - // Zoom out - PointF pointF = new PointF(uiSettings.getWidth() / 2, uiSettings.getHeight() / 2); - 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 deleted file mode 100644 index 4521d2ae6..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapView.java +++ /dev/null @@ -1,1350 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.graphics.drawable.ColorDrawable; -import android.os.Bundle; -import android.support.annotation.CallSuper; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.UiThread; -import android.support.v4.util.LongSparseArray; -import android.util.AttributeSet; -import android.view.KeyEvent; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.TextureView; -import android.view.View; -import android.widget.FrameLayout; -import android.widget.ImageView; - -import com.mapbox.android.gestures.AndroidGesturesManager; -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.Mapbox; -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.exceptions.MapboxConfigurationException; -import com.mapbox.mapboxsdk.location.LocationComponent; -import com.mapbox.mapboxsdk.maps.renderer.MapRenderer; -import com.mapbox.mapboxsdk.maps.renderer.glsurfaceview.GLSurfaceViewMapRenderer; -import com.mapbox.mapboxsdk.maps.renderer.glsurfaceview.MapboxGLSurfaceView; -import com.mapbox.mapboxsdk.maps.renderer.textureview.TextureViewMapRenderer; -import com.mapbox.mapboxsdk.maps.widgets.CompassView; -import com.mapbox.mapboxsdk.net.ConnectivityReceiver; -import com.mapbox.mapboxsdk.storage.FileSource; -import com.mapbox.mapboxsdk.utils.BitmapUtils; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.microedition.khronos.egl.EGLConfig; -import javax.microedition.khronos.opengles.GL10; - -import static com.mapbox.mapboxsdk.maps.widgets.CompassView.TIME_MAP_NORTH_ANIMATION; -import static com.mapbox.mapboxsdk.maps.widgets.CompassView.TIME_WAIT_IDLE; - -/** - *

- * A {@code MapView} provides an embeddable map interface. - * You use this class to display map information and to manipulate the map contents from your application. - * You can center the map on a given coordinate, specify the size of the area you want to display, - * and style the features of the map to fit your application's use case. - *

- *

- * Use of {@code MapView} requires a Mapbox API access token. - * Obtain an access token on the Mapbox account page. - *

- * Warning: Please note that you are responsible for getting permission to use the map data, - * and for ensuring your use adheres to the relevant terms of use. - */ -public class MapView extends FrameLayout implements NativeMapView.ViewCallback { - - private final MapChangeReceiver mapChangeReceiver = new MapChangeReceiver(); - private final MapCallback mapCallback = new MapCallback(); - private final InitialRenderCallback initialRenderCallback = new InitialRenderCallback(); - - @Nullable - private NativeMap nativeMapView; - @Nullable - private MapboxMap mapboxMap; - private AttributionClickListener attributionClickListener; - private MapboxMapOptions mapboxMapOptions; - private MapRenderer mapRenderer; - private boolean destroyed; - - private CompassView compassView; - private PointF focalPoint; - private ImageView attrView; - private ImageView logoView; - - @Nullable - private MapGestureDetector mapGestureDetector; - @Nullable - private MapKeyListener mapKeyListener; - @Nullable - private Bundle savedInstanceState; - private boolean isStarted; - - @UiThread - public MapView(@NonNull Context context) { - super(context); - initialize(context, MapboxMapOptions.createFromAttributes(context)); - } - - @UiThread - public MapView(@NonNull Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - initialize(context, MapboxMapOptions.createFromAttributes(context, attrs)); - } - - @UiThread - public MapView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - initialize(context, MapboxMapOptions.createFromAttributes(context, attrs)); - } - - @UiThread - public MapView(@NonNull Context context, @Nullable MapboxMapOptions options) { - super(context); - initialize(context, options == null ? MapboxMapOptions.createFromAttributes(context) : options); - } - - @CallSuper - @UiThread - protected void initialize(@NonNull final Context context, @NonNull final MapboxMapOptions options) { - if (isInEditMode()) { - // in IDE layout editor, just return - return; - } - - if (!Mapbox.hasInstance()) { - throw new MapboxConfigurationException(); - } - - // hide surface until map is fully loaded #10990 - setForeground(new ColorDrawable(options.getForegroundLoadColor())); - - mapboxMapOptions = options; - - // inflate view - View view = LayoutInflater.from(context).inflate(R.layout.mapbox_mapview_internal, this); - compassView = view.findViewById(R.id.compassView); - attrView = view.findViewById(R.id.attributionView); - attrView.setImageDrawable(BitmapUtils.getDrawableFromRes(getContext(), R.drawable.mapbox_info_bg_selector)); - logoView = view.findViewById(R.id.logoView); - logoView.setImageDrawable(BitmapUtils.getDrawableFromRes(getContext(), R.drawable.mapbox_logo_icon)); - - // add accessibility support - setContentDescription(context.getString(R.string.mapbox_mapActionDescription)); - setWillNotDraw(false); - initialiseDrawingSurface(options); - } - - private void initialiseMap() { - Context context = getContext(); - - // callback for focal point invalidation - final FocalPointInvalidator focalInvalidator = new FocalPointInvalidator(); - focalInvalidator.addListener(createFocalPointChangeListener()); - - // callback for registering touch listeners - GesturesManagerInteractionListener registerTouchListener = new GesturesManagerInteractionListener(); - - // callback for camera change events - final CameraChangeDispatcher cameraDispatcher = new CameraChangeDispatcher(); - - // setup components for MapboxMap creation - Projection proj = new Projection(nativeMapView, this); - UiSettings uiSettings = new UiSettings(proj, focalInvalidator, compassView, attrView, logoView, getPixelRatio()); - LongSparseArray annotationsArray = new LongSparseArray<>(); - IconManager iconManager = new IconManager(nativeMapView); - Annotations annotations = new AnnotationContainer(nativeMapView, annotationsArray); - Markers markers = new MarkerContainer(nativeMapView, annotationsArray, iconManager); - Polygons polygons = new PolygonContainer(nativeMapView, annotationsArray); - Polylines polylines = new PolylineContainer(nativeMapView, annotationsArray); - ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(nativeMapView, annotationsArray); - AnnotationManager annotationManager = new AnnotationManager(this, annotationsArray, iconManager, - annotations, markers, polygons, polylines, shapeAnnotations); - Transform transform = new Transform(this, nativeMapView, cameraDispatcher); - - // MapboxMap - List developerAnimationListeners = new ArrayList<>(); - mapboxMap = new MapboxMap(nativeMapView, transform, uiSettings, proj, registerTouchListener, cameraDispatcher, - developerAnimationListeners); - mapboxMap.injectAnnotationManager(annotationManager); - - // user input - mapGestureDetector = new MapGestureDetector(context, transform, proj, uiSettings, - annotationManager, cameraDispatcher); - mapKeyListener = new MapKeyListener(transform, uiSettings, mapGestureDetector); - - // compass - compassView.injectCompassAnimationListener(createCompassAnimationListener(cameraDispatcher)); - compassView.setOnClickListener(createCompassClickListener(cameraDispatcher)); - - // LocationComponent - mapboxMap.injectLocationComponent(new LocationComponent(mapboxMap, transform, developerAnimationListeners)); - - // inject widgets with MapboxMap - attrView.setOnClickListener(attributionClickListener = new AttributionClickListener(context, mapboxMap)); - - // Ensure this view is interactable - setClickable(true); - setLongClickable(true); - setFocusable(true); - setFocusableInTouchMode(true); - requestDisallowInterceptTouchEvent(true); - - // notify Map object about current connectivity state - nativeMapView.setReachability(Mapbox.isConnected()); - - // initialise MapboxMap - if (savedInstanceState == null) { - mapboxMap.initialise(context, mapboxMapOptions); - } else { - mapboxMap.onRestoreInstanceState(savedInstanceState); - } - - mapCallback.initialised(); - } - - private FocalPointChangeListener createFocalPointChangeListener() { - return new FocalPointChangeListener() { - @Override - public void onFocalPointChanged(PointF pointF) { - focalPoint = pointF; - } - }; - } - - private MapboxMap.OnCompassAnimationListener createCompassAnimationListener(@NonNull final CameraChangeDispatcher - cameraChangeDispatcher) { - return new MapboxMap.OnCompassAnimationListener() { - @Override - public void onCompassAnimation() { - cameraChangeDispatcher.onCameraMove(); - } - - @Override - public void onCompassAnimationFinished() { - compassView.isAnimating(false); - cameraChangeDispatcher.onCameraIdle(); - } - }; - } - - private OnClickListener createCompassClickListener(@NonNull final CameraChangeDispatcher cameraChangeDispatcher) { - return new OnClickListener() { - @Override - public void onClick(View v) { - if (mapboxMap != null && compassView != null) { - if (focalPoint != null) { - mapboxMap.setFocalBearing(0, focalPoint.x, focalPoint.y, TIME_MAP_NORTH_ANIMATION); - } else { - mapboxMap.setFocalBearing(0, mapboxMap.getWidth() / 2, mapboxMap.getHeight() / 2, TIME_MAP_NORTH_ANIMATION); - } - cameraChangeDispatcher.onCameraMoveStarted(MapboxMap.OnCameraMoveStartedListener.REASON_API_ANIMATION); - compassView.isAnimating(true); - compassView.postDelayed(compassView, TIME_WAIT_IDLE + TIME_MAP_NORTH_ANIMATION); - } - } - }; - } - - // - // Lifecycle events - // - - /** - *

- * You must call this method from the parent's Activity#onCreate(Bundle)} or - * Fragment#onViewCreated(View, Bundle). - *

- * 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. - * - * @param savedInstanceState Pass in the parent's savedInstanceState. - * @see com.mapbox.mapboxsdk.Mapbox#getInstance(Context, String) - */ - @UiThread - public void onCreate(@Nullable Bundle savedInstanceState) { - if (savedInstanceState == null) { - TelemetryDefinition telemetry = Mapbox.getTelemetry(); - if (telemetry != null) { - telemetry.onAppUserTurnstileEvent(); - } - } else if (savedInstanceState.getBoolean(MapboxConstants.STATE_HAS_SAVED_STATE)) { - this.savedInstanceState = savedInstanceState; - } - } - - private void initialiseDrawingSurface(MapboxMapOptions options) { - String localFontFamily = options.getLocalIdeographFontFamily(); - if (options.getTextureMode()) { - TextureView textureView = new TextureView(getContext()); - boolean translucentSurface = options.getTranslucentTextureSurface(); - mapRenderer = new TextureViewMapRenderer(getContext(), - textureView, localFontFamily, translucentSurface) { - @Override - protected void onSurfaceCreated(GL10 gl, EGLConfig config) { - MapView.this.onSurfaceCreated(); - super.onSurfaceCreated(gl, config); - } - }; - - addView(textureView, 0); - } else { - MapboxGLSurfaceView glSurfaceView = new MapboxGLSurfaceView(getContext()); - glSurfaceView.setZOrderMediaOverlay(mapboxMapOptions.getRenderSurfaceOnTop()); - mapRenderer = new GLSurfaceViewMapRenderer(getContext(), glSurfaceView, localFontFamily) { - @Override - public void onSurfaceCreated(GL10 gl, EGLConfig config) { - MapView.this.onSurfaceCreated(); - super.onSurfaceCreated(gl, config); - } - }; - - addView(glSurfaceView, 0); - } - - boolean crossSourceCollisions = mapboxMapOptions.getCrossSourceCollisions(); - nativeMapView = new NativeMapView( - getContext(), getPixelRatio(), crossSourceCollisions, this, mapChangeReceiver, mapRenderer - ); - } - - private void onSurfaceCreated() { - post(new Runnable() { - @Override - public void run() { - // Initialise only when not destroyed and only once - if (!destroyed && mapboxMap == null) { - MapView.this.initialiseMap(); - mapboxMap.onStart(); - } - } - }); - } - - /** - * You must call this method from the parent's Activity#onSaveInstanceState(Bundle) - * or Fragment#onSaveInstanceState(Bundle). - * - * @param outState Pass in the parent's outState. - */ - @UiThread - public void onSaveInstanceState(@NonNull Bundle outState) { - if (mapboxMap != null) { - outState.putBoolean(MapboxConstants.STATE_HAS_SAVED_STATE, true); - mapboxMap.onSaveInstanceState(outState); - } - } - - /** - * You must call this method from the parent's Activity#onStart() or Fragment#onStart() - */ - @UiThread - public void onStart() { - if (!isStarted) { - ConnectivityReceiver.instance(getContext()).activate(); - FileSource.getInstance(getContext()).activate(); - isStarted = true; - } - if (mapboxMap != null) { - mapboxMap.onStart(); - } - - if (mapRenderer != null) { - mapRenderer.onStart(); - } - } - - /** - * You must call this method from the parent's Activity#onResume() or Fragment#onResume(). - */ - @UiThread - public void onResume() { - if (mapRenderer != null) { - mapRenderer.onResume(); - } - } - - /** - * You must call this method from the parent's Activity#onPause() or Fragment#onPause(). - */ - @UiThread - public void onPause() { - if (mapRenderer != null) { - mapRenderer.onPause(); - } - } - - /** - * You must call this method from the parent's Activity#onStop() or Fragment#onStop(). - */ - @UiThread - public void onStop() { - if (attributionClickListener != null) { - attributionClickListener.onStop(); - } - - if (mapboxMap != null) { - // map was destroyed before it was started - mapGestureDetector.cancelAnimators(); - mapboxMap.onStop(); - } - - if (mapRenderer != null) { - mapRenderer.onStop(); - } - - if (isStarted) { - ConnectivityReceiver.instance(getContext()).deactivate(); - FileSource.getInstance(getContext()).deactivate(); - isStarted = false; - } - } - - /** - * You must call this method from the parent's Activity#onDestroy() or Fragment#onDestroyView(). - */ - @UiThread - public void onDestroy() { - destroyed = true; - mapChangeReceiver.clear(); - mapCallback.onDestroy(); - initialRenderCallback.onDestroy(); - - if (compassView != null) { - // avoid leaking context through animator #13742 - compassView.resetAnimation(); - } - - if (mapboxMap != null) { - mapboxMap.onDestroy(); - } - - if (nativeMapView != null) { - // null when destroying an activity programmatically mapbox-navigation-android/issues/503 - nativeMapView.destroy(); - nativeMapView = null; - } - - if (mapRenderer != null) { - mapRenderer.onDestroy(); - } - } - - /** - * The maximum frame rate at which the map view is rendered, - * but it can't excess the ability of device hardware. - * - * @param maximumFps Can be set to arbitrary integer values. - */ - public void setMaximumFps(int maximumFps) { - if (mapRenderer != null) { - mapRenderer.setMaximumFps(maximumFps); - } else { - throw new IllegalStateException("Calling MapView#setMaximumFps before mapRenderer is created."); - } - } - - /** - * Returns if the map has been destroyed. - *

- * This method can be used to determine if the result of an asynchronous operation should be set. - *

- * - * @return true, if the map has been destroyed - */ - @UiThread - public boolean isDestroyed() { - return destroyed; - } - - @Override - public boolean onTouchEvent(MotionEvent event) { - if (!isGestureDetectorInitialized()) { - return super.onTouchEvent(event); - } - - return mapGestureDetector.onTouchEvent(event) || super.onTouchEvent(event); - } - - @Override - public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) { - return mapKeyListener.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); - } - - @Override - public boolean onKeyLongPress(int keyCode, KeyEvent event) { - return mapKeyListener.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event); - } - - @Override - public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) { - return mapKeyListener.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event); - } - - @Override - public boolean onTrackballEvent(@NonNull MotionEvent event) { - return mapKeyListener.onTrackballEvent(event) || super.onTrackballEvent(event); - } - - @Override - public boolean onGenericMotionEvent(@NonNull MotionEvent event) { - if (!isGestureDetectorInitialized()) { - return super.onGenericMotionEvent(event); - } - return mapGestureDetector.onGenericMotionEvent(event) || super.onGenericMotionEvent(event); - } - - /** - * You must call this method from the parent's Activity#onLowMemory() or Fragment#onLowMemory(). - */ - @UiThread - public void onLowMemory() { - if (nativeMapView != null && mapboxMap != null && !destroyed) { - nativeMapView.onLowMemory(); - } - } - - // - // Rendering - // - - @Override - protected void onSizeChanged(int width, int height, int oldw, int oldh) { - if (!isInEditMode() && nativeMapView != null) { - // null-checking the nativeMapView, see #13277 - nativeMapView.resizeView(width, height); - } - } - - private float getPixelRatio() { - // check is user defined his own pixel ratio value - float pixelRatio = mapboxMapOptions.getPixelRatio(); - if (pixelRatio == 0) { - // if not, get the one defined by the system - pixelRatio = getResources().getDisplayMetrics().density; - } - return pixelRatio; - } - - // - // ViewCallback - // - - @Nullable - @Override - public Bitmap getViewContent() { - return BitmapUtils.createBitmapFromView(this); - } - - // - // Map events - // - - /** - * Set a callback that's invoked when the camera region will change. - * - * @param listener The callback that's invoked when the camera region will change - */ - public void addOnCameraWillChangeListener(@NonNull OnCameraWillChangeListener listener) { - mapChangeReceiver.addOnCameraWillChangeListener(listener); - } - - /** - * Remove a callback that's invoked when the camera region will change. - * - * @param listener The callback that's invoked when the camera region will change - */ - public void removeOnCameraWillChangeListener(@NonNull OnCameraWillChangeListener listener) { - mapChangeReceiver.removeOnCameraWillChangeListener(listener); - } - - /** - * Set a callback that's invoked when the camera is changing. - * - * @param listener The callback that's invoked when the camera is changing - */ - public void addOnCameraIsChangingListener(@NonNull OnCameraIsChangingListener listener) { - mapChangeReceiver.addOnCameraIsChangingListener(listener); - } - - /** - * Remove a callback that's invoked when the camera is changing. - * - * @param listener The callback that's invoked when the camera is changing - */ - public void removeOnCameraIsChangingListener(@NonNull OnCameraIsChangingListener listener) { - mapChangeReceiver.removeOnCameraIsChangingListener(listener); - } - - /** - * Set a callback that's invoked when the camera region did change. - * - * @param listener The callback that's invoked when the camera region did change - */ - public void addOnCameraDidChangeListener(@NonNull OnCameraDidChangeListener listener) { - mapChangeReceiver.addOnCameraDidChangeListener(listener); - } - - /** - * Set a callback that's invoked when the camera region did change. - * - * @param listener The callback that's invoked when the camera region did change - */ - public void removeOnCameraDidChangeListener(@NonNull OnCameraDidChangeListener listener) { - mapChangeReceiver.removeOnCameraDidChangeListener(listener); - } - - /** - * Set a callback that's invoked when the map will start loading. - * - * @param listener The callback that's invoked when the map will start loading - */ - public void addOnWillStartLoadingMapListener(@NonNull OnWillStartLoadingMapListener listener) { - mapChangeReceiver.addOnWillStartLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map will start loading. - * - * @param listener The callback that's invoked when the map will start loading - */ - public void removeOnWillStartLoadingMapListener(@NonNull OnWillStartLoadingMapListener listener) { - mapChangeReceiver.removeOnWillStartLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map has finished loading. - * - * @param listener The callback that's invoked when the map has finished loading - */ - public void addOnDidFinishLoadingMapListener(@NonNull OnDidFinishLoadingMapListener listener) { - mapChangeReceiver.addOnDidFinishLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map has finished loading. - * - * @param listener The callback that's invoked when the map has finished loading - */ - public void removeOnDidFinishLoadingMapListener(@NonNull OnDidFinishLoadingMapListener listener) { - mapChangeReceiver.removeOnDidFinishLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map failed to load. - * - * @param listener The callback that's invoked when the map failed to load - */ - public void addOnDidFailLoadingMapListener(@NonNull OnDidFailLoadingMapListener listener) { - mapChangeReceiver.addOnDidFailLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map failed to load. - * - * @param listener The callback that's invoked when the map failed to load - */ - public void removeOnDidFailLoadingMapListener(@NonNull OnDidFailLoadingMapListener listener) { - mapChangeReceiver.removeOnDidFailLoadingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map will start rendering a frame. - * - * @param listener The callback that's invoked when the camera will start rendering a frame - */ - public void addOnWillStartRenderingFrameListener(@NonNull OnWillStartRenderingFrameListener listener) { - mapChangeReceiver.addOnWillStartRenderingFrameListener(listener); - } - - /** - * Set a callback that's invoked when the map will start rendering a frame. - * - * @param listener The callback that's invoked when the camera will start rendering a frame - */ - public void removeOnWillStartRenderingFrameListener(@NonNull OnWillStartRenderingFrameListener listener) { - mapChangeReceiver.removeOnWillStartRenderingFrameListener(listener); - } - - /** - * Set a callback that's invoked when the map has finished rendering a frame. - * - * @param listener The callback that's invoked when the map has finished rendering a frame - */ - public void addOnDidFinishRenderingFrameListener(@NonNull OnDidFinishRenderingFrameListener listener) { - mapChangeReceiver.addOnDidFinishRenderingFrameListener(listener); - } - - /** - * Set a callback that's invoked when the map has finished rendering a frame. - * - * @param listener The callback that's invoked when the map has finished rendering a frame - */ - public void removeOnDidFinishRenderingFrameListener(@NonNull OnDidFinishRenderingFrameListener listener) { - mapChangeReceiver.removeOnDidFinishRenderingFrameListener(listener); - } - - /** - * Set a callback that's invoked when the map will start rendering. - * - * @param listener The callback that's invoked when the map will start rendering - */ - public void addOnWillStartRenderingMapListener(@NonNull OnWillStartRenderingMapListener listener) { - mapChangeReceiver.addOnWillStartRenderingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map will start rendering. - * - * @param listener The callback that's invoked when the map will start rendering - */ - public void removeOnWillStartRenderingMapListener(@NonNull OnWillStartRenderingMapListener listener) { - mapChangeReceiver.removeOnWillStartRenderingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map has finished rendering. - * - * @param listener The callback that's invoked when the map has finished rendering - */ - public void addOnDidFinishRenderingMapListener(@NonNull OnDidFinishRenderingMapListener listener) { - mapChangeReceiver.addOnDidFinishRenderingMapListener(listener); - } - - /** - * Remove a callback that's invoked when the map has finished rendering. - * - * @param listener The callback that's invoked when the map has has finished rendering. - */ - public void removeOnDidFinishRenderingMapListener(OnDidFinishRenderingMapListener listener) { - mapChangeReceiver.removeOnDidFinishRenderingMapListener(listener); - } - - /** - * Set a callback that's invoked when the map has entered the idle state. - * - * @param listener The callback that's invoked when the map has entered the idle state. - */ - public void addOnDidBecomeIdleListener(@NonNull OnDidBecomeIdleListener listener) { - mapChangeReceiver.addOnDidBecomeIdleListener(listener); - } - - /** - * Remove a callback that's invoked when the map has entered the idle state. - * - * @param listener The callback that's invoked when the map has entered the idle state. - */ - public void removeOnDidBecomeIdleListener(@NonNull OnDidBecomeIdleListener listener) { - mapChangeReceiver.removeOnDidBecomeIdleListener(listener); - } - - /** - * Set a callback that's invoked when the style has finished loading. - * - * @param listener The callback that's invoked when the style has finished loading - */ - public void addOnDidFinishLoadingStyleListener(@NonNull OnDidFinishLoadingStyleListener listener) { - mapChangeReceiver.addOnDidFinishLoadingStyleListener(listener); - } - - /** - * Set a callback that's invoked when the style has finished loading. - * - * @param listener The callback that's invoked when the style has finished loading - */ - public void removeOnDidFinishLoadingStyleListener(@NonNull OnDidFinishLoadingStyleListener listener) { - mapChangeReceiver.removeOnDidFinishLoadingStyleListener(listener); - } - - /** - * Set a callback that's invoked when a map source has changed. - * - * @param listener The callback that's invoked when the source has changed - */ - public void addOnSourceChangedListener(@NonNull OnSourceChangedListener listener) { - mapChangeReceiver.addOnSourceChangedListener(listener); - } - - /** - * Set a callback that's invoked when a map source has changed. - * - * @param listener The callback that's invoked when the source has changed - */ - public void removeOnSourceChangedListener(@NonNull OnSourceChangedListener listener) { - mapChangeReceiver.removeOnSourceChangedListener(listener); - } - - /** - * Set a callback that's invoked when the id of an icon is missing. - * - * @param listener The callback that's invoked when the id of an icon is missing - */ - public void addOnStyleImageMissingListener(@NonNull OnStyleImageMissingListener listener) { - mapChangeReceiver.addOnStyleImageMissingListener(listener); - } - - /** - * Set a callback that's invoked when a map source has changed. - * - * @param listener The callback that's invoked when the source has changed - */ - public void removeOnStyleImageMissingListener(@NonNull OnStyleImageMissingListener listener) { - mapChangeReceiver.removeOnStyleImageMissingListener(listener); - } - - /** - * Set a callback that's invoked when map needs to release unused image resources. - *

- * A callback will be called only for unused images that were provided by the client via - * {@link OnStyleImageMissingListener#onStyleImageMissing(String)} listener interface. - *

- *

- * By default, platform will remove unused images from the style. By adding listener, default - * behavior can be overridden and client can control whether to release unused resources. - *

- * - * @param listener The callback that's invoked when map needs to release unused image resources - */ - public void addOnCanRemoveUnusedStyleImageListener(@NonNull OnCanRemoveUnusedStyleImageListener listener) { - mapChangeReceiver.addOnCanRemoveUnusedStyleImageListener(listener); - } - - /** - * Removes a callback that's invoked when map needs to release unused image resources. - *

- * When all listeners are removed, platform will fallback to default behavior, which is to remove - * unused images from the style. - *

- * - * @param listener The callback that's invoked when map needs to release unused image resources - */ - public void removeOnCanRemoveUnusedStyleImageListener(@NonNull OnCanRemoveUnusedStyleImageListener listener) { - mapChangeReceiver.removeOnCanRemoveUnusedStyleImageListener(listener); - } - - /** - * Interface definition for a callback to be invoked when the camera will change. - *

- * {@link MapView#addOnCameraWillChangeListener(OnCameraWillChangeListener)} - *

- */ - public interface OnCameraWillChangeListener { - - /** - * Called when the camera region will change. - */ - void onCameraWillChange(boolean animated); - } - - /** - * Interface definition for a callback to be invoked when the camera is changing. - *

- * {@link MapView#addOnCameraIsChangingListener(OnCameraIsChangingListener)} - *

- */ - public interface OnCameraIsChangingListener { - /** - * Called when the camera is changing. - */ - void onCameraIsChanging(); - } - - /** - * Interface definition for a callback to be invoked when the map region did change. - *

- * {@link MapView#addOnCameraDidChangeListener(OnCameraDidChangeListener)} - *

- */ - public interface OnCameraDidChangeListener { - /** - * Called when the camera did change. - */ - void onCameraDidChange(boolean animated); - } - - /** - * Interface definition for a callback to be invoked when the map will start loading. - *

- * {@link MapView#addOnWillStartLoadingMapListener(OnWillStartLoadingMapListener)} - *

- */ - public interface OnWillStartLoadingMapListener { - /** - * Called when the map will start loading. - */ - void onWillStartLoadingMap(); - } - - /** - * Interface definition for a callback to be invoked when the map finished loading. - *

- * {@link MapView#addOnDidFinishLoadingMapListener(OnDidFinishLoadingMapListener)} - *

- */ - public interface OnDidFinishLoadingMapListener { - /** - * Called when the map has finished loading. - */ - void onDidFinishLoadingMap(); - } - - /** - * Interface definition for a callback to be invoked when the map is changing. - *

- * {@link MapView#addOnDidFailLoadingMapListener(OnDidFailLoadingMapListener)} - *

- */ - public interface OnDidFailLoadingMapListener { - /** - * Called when the map failed to load. - * - * @param errorMessage The reason why the map failed to load - */ - void onDidFailLoadingMap(String errorMessage); - } - - /** - * Interface definition for a callback to be invoked when the map will start rendering a frame. - *

- * {@link MapView#addOnWillStartRenderingFrameListener(OnWillStartRenderingFrameListener)} - *

- */ - public interface OnWillStartRenderingFrameListener { - /** - * Called when the map will start rendering a frame. - */ - void onWillStartRenderingFrame(); - } - - /** - * Interface definition for a callback to be invoked when the map finished rendering a frame. - *

- * {@link MapView#addOnDidFinishRenderingFrameListener(OnDidFinishRenderingFrameListener)} - *

- */ - public interface OnDidFinishRenderingFrameListener { - /** - * Called when the map has finished rendering a frame - * - * @param fully true if all frames have been rendered, false if partially rendered - */ - void onDidFinishRenderingFrame(boolean fully); - } - - /** - * Interface definition for a callback to be invoked when the map will start rendering the map. - *

- * {@link MapView#addOnDidFailLoadingMapListener(OnDidFailLoadingMapListener)} - *

- */ - public interface OnWillStartRenderingMapListener { - /** - * Called when the map will start rendering. - */ - void onWillStartRenderingMap(); - } - - /** - * Interface definition for a callback to be invoked when the map is changing. - *

- * {@link MapView#addOnDidFinishRenderingMapListener(OnDidFinishRenderingMapListener)} - *

- */ - public interface OnDidFinishRenderingMapListener { - /** - * Called when the map has finished rendering. - * - * @param fully true if map is fully rendered, false if not fully rendered - */ - void onDidFinishRenderingMap(boolean fully); - } - - /** - * Interface definition for a callback to be invoked when the map has entered the idle state. - *

- * Calling {@link MapboxMap#snapshot(MapboxMap.SnapshotReadyCallback)} from this callback - * will result in recursive execution. Use {@link OnDidFinishRenderingFrameListener} instead. - *

- *

- * {@link MapView#addOnDidBecomeIdleListener(OnDidBecomeIdleListener)} - *

- */ - public interface OnDidBecomeIdleListener { - /** - * Called when the map has entered the idle state. - */ - void onDidBecomeIdle(); - } - - /** - * Interface definition for a callback to be invoked when the map has loaded the style. - *

- * {@link MapView#addOnDidFailLoadingMapListener(OnDidFailLoadingMapListener)} - *

- */ - public interface OnDidFinishLoadingStyleListener { - /** - * Called when a style has finished loading. - */ - void onDidFinishLoadingStyle(); - } - - /** - * Interface definition for a callback to be invoked when a map source has changed. - *

- * {@link MapView#addOnDidFailLoadingMapListener(OnDidFailLoadingMapListener)} - *

- */ - public interface OnSourceChangedListener { - /** - * Called when a map source has changed. - * - * @param id the id of the source that has changed - */ - void onSourceChangedListener(String id); - } - - /** - * Interface definition for a callback to be invoked with the id of a missing icon. The icon should be added - * synchronously with {@link Style#addImage(String, Bitmap)} to be rendered on the current zoom level. When loading - * icons asynchronously, you can load a placeholder image and replace it when you icon has loaded. - *

- * {@link MapView#addOnStyleImageMissingListener(OnStyleImageMissingListener)} - *

- */ - public interface OnStyleImageMissingListener { - /** - * Called when the map is missing an icon.The icon should be added synchronously with - * {@link Style#addImage(String, Bitmap)} to be rendered on the current zoom level. When loading icons - * asynchronously, you can load a placeholder image and replace it when you icon has loaded. - * - * @param id the id of the icon that is missing - */ - void onStyleImageMissing(@NonNull String id); - } - - /** - * Interface definition for a callback to be invoked with an unused image identifier. - *

- * {@link MapView#addOnCanRemoveUnusedStyleImageListener(OnCanRemoveUnusedStyleImageListener)} - *

- */ - public interface OnCanRemoveUnusedStyleImageListener { - /** - * Called when the map needs to release unused image resources. - * - * @param id of an image that is not used by the map and can be removed from the style. - * @return true if image can be removed, false otherwise. - */ - boolean onCanRemoveUnusedStyleImage(@NonNull String id); - } - - /** - * Sets a callback object which will be triggered when the {@link MapboxMap} instance is ready to be used. - * - * @param callback The callback object that will be triggered when the map is ready to be used. - */ - @UiThread - public void getMapAsync(final @NonNull OnMapReadyCallback callback) { - if (mapboxMap == null) { - // Add callback to the list only if the style hasn't loaded, or the drawing surface isn't ready - mapCallback.addOnMapReadyCallback(callback); - } else { - callback.onMapReady(mapboxMap); - } - } - - private boolean isGestureDetectorInitialized() { - return mapGestureDetector != null; - } - - @Nullable - MapboxMap getMapboxMap() { - return mapboxMap; - } - - void setMapboxMap(MapboxMap mapboxMap) { - this.mapboxMap = mapboxMap; - } - - private class FocalPointInvalidator implements FocalPointChangeListener { - - private final List focalPointChangeListeners = new ArrayList<>(); - - void addListener(FocalPointChangeListener focalPointChangeListener) { - focalPointChangeListeners.add(focalPointChangeListener); - } - - @Override - public void onFocalPointChanged(PointF pointF) { - mapGestureDetector.setFocalPoint(pointF); - for (FocalPointChangeListener focalPointChangeListener : focalPointChangeListeners) { - focalPointChangeListener.onFocalPointChanged(pointF); - } - } - } - - /** - * The initial render callback waits for rendering to happen before making the map visible for end-users. - * We wait for the second DID_FINISH_RENDERING_FRAME map change event as the first will still show a black surface. - */ - private class InitialRenderCallback implements OnDidFinishRenderingFrameListener { - - private int renderCount; - - InitialRenderCallback() { - addOnDidFinishRenderingFrameListener(this); - } - - @Override - public void onDidFinishRenderingFrame(boolean fully) { - if (mapboxMap != null && mapboxMap.getStyle() != null && mapboxMap.getStyle().isFullyLoaded()) { - renderCount++; - if (renderCount == 3) { - MapView.this.setForeground(null); - removeOnDidFinishRenderingFrameListener(this); - } - } - } - - private void onDestroy() { - removeOnDidFinishRenderingFrameListener(this); - } - } - - private class GesturesManagerInteractionListener implements MapboxMap.OnGesturesManagerInteractionListener { - - @Override - public void onAddMapClickListener(MapboxMap.OnMapClickListener listener) { - mapGestureDetector.addOnMapClickListener(listener); - } - - @Override - public void onRemoveMapClickListener(MapboxMap.OnMapClickListener listener) { - mapGestureDetector.removeOnMapClickListener(listener); - } - - @Override - public void onAddMapLongClickListener(MapboxMap.OnMapLongClickListener listener) { - mapGestureDetector.addOnMapLongClickListener(listener); - } - - @Override - public void onRemoveMapLongClickListener(MapboxMap.OnMapLongClickListener listener) { - mapGestureDetector.removeOnMapLongClickListener(listener); - } - - @Override - public void onAddFlingListener(MapboxMap.OnFlingListener listener) { - mapGestureDetector.addOnFlingListener(listener); - } - - @Override - 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 class MapCallback implements OnDidFinishLoadingStyleListener, - OnDidFinishRenderingFrameListener, OnDidFinishLoadingMapListener, - OnCameraIsChangingListener, OnCameraDidChangeListener, OnDidFailLoadingMapListener { - - private final List onMapReadyCallbackList = new ArrayList<>(); - - MapCallback() { - addOnDidFinishLoadingStyleListener(this); - addOnDidFinishRenderingFrameListener(this); - addOnDidFinishLoadingMapListener(this); - addOnCameraIsChangingListener(this); - addOnCameraDidChangeListener(this); - addOnDidFailLoadingMapListener(this); - } - - void initialised() { - mapboxMap.onPreMapReady(); - onMapReady(); - mapboxMap.onPostMapReady(); - } - - /** - * Notify listeners, clear when done - */ - private void onMapReady() { - if (onMapReadyCallbackList.size() > 0) { - Iterator iterator = onMapReadyCallbackList.iterator(); - while (iterator.hasNext()) { - OnMapReadyCallback callback = iterator.next(); - if (callback != null) { - // null checking required for #13279 - callback.onMapReady(mapboxMap); - } - iterator.remove(); - } - } - } - - void addOnMapReadyCallback(OnMapReadyCallback callback) { - onMapReadyCallbackList.add(callback); - } - - void onDestroy() { - onMapReadyCallbackList.clear(); - removeOnDidFinishLoadingStyleListener(this); - removeOnDidFinishRenderingFrameListener(this); - removeOnDidFinishLoadingMapListener(this); - removeOnCameraIsChangingListener(this); - removeOnCameraDidChangeListener(this); - removeOnDidFailLoadingMapListener(this); - } - - @Override - public void onDidFinishLoadingStyle() { - if (mapboxMap != null) { - mapboxMap.onFinishLoadingStyle(); - } - } - - @Override - public void onDidFailLoadingMap(String errorMessage) { - if (mapboxMap != null) { - mapboxMap.onFailLoadingStyle(); - } - } - - @Override - public void onDidFinishRenderingFrame(boolean fully) { - if (mapboxMap != null) { - mapboxMap.onUpdateFullyRendered(); - } - } - - @Override - public void onDidFinishLoadingMap() { - if (mapboxMap != null) { - mapboxMap.onUpdateRegionChange(); - } - } - - @Override - public void onCameraIsChanging() { - if (mapboxMap != null) { - mapboxMap.onUpdateRegionChange(); - } - } - - @Override - public void onCameraDidChange(boolean animated) { - if (mapboxMap != null) { - mapboxMap.onUpdateRegionChange(); - } - } - } - - /** - * Click event hook for providing a custom attribution dialog manager. - */ - private static class AttributionClickListener implements OnClickListener { - - @NonNull - private final AttributionDialogManager defaultDialogManager; - private UiSettings uiSettings; - - private AttributionClickListener(@NonNull Context context, @NonNull MapboxMap mapboxMap) { - this.defaultDialogManager = new AttributionDialogManager(context, mapboxMap); - this.uiSettings = mapboxMap.getUiSettings(); - } - - @Override - public void onClick(View v) { - getDialogManager().onClick(v); - } - - public void onStop() { - getDialogManager().onStop(); - } - - private AttributionDialogManager getDialogManager() { - AttributionDialogManager customDialogManager = uiSettings.getAttributionDialogManager(); - if (customDialogManager != null) { - return uiSettings.getAttributionDialogManager(); - } else { - return defaultDialogManager; - } - } - } - - /** - * Sets the strict mode that will throw the {@link com.mapbox.mapboxsdk.MapStrictModeException} - * whenever the map would fail silently otherwise. - * - * @param strictModeEnabled true to enable the strict mode, false otherwise - */ - public static void setMapStrictModeEnabled(boolean strictModeEnabled) { - MapStrictMode.setStrictModeEnabled(strictModeEnabled); - } -} 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 deleted file mode 100644 index 8f4cb9438..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMap.java +++ /dev/null @@ -1,2425 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.graphics.RectF; -import android.os.Bundle; -import android.support.annotation.FloatRange; -import android.support.annotation.IntRange; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.Size; -import android.support.annotation.UiThread; -import android.text.TextUtils; -import android.view.View; - -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.MapStrictMode; -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.MarkerOptions; -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.PolygonOptions; -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.annotations.PolylineOptions; -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.geometry.LatLng; -import com.mapbox.mapboxsdk.geometry.LatLngBounds; -import com.mapbox.mapboxsdk.location.LocationComponent; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.offline.OfflineRegionDefinition; -import com.mapbox.mapboxsdk.style.expressions.Expression; - -import java.util.ArrayList; -import java.util.List; - -/** - * The general class to interact with in the Android Mapbox SDK. It exposes the entry point for all - * methods related to the MapView. You cannot instantiate {@link MapboxMap} object directly, rather, - * you must obtain one from the getMapAsync() method on a MapFragment or MapView that you have - * added to your application. - *

- * Note: Similar to a View object, a MapboxMap should only be read and modified from the main thread. - *

- */ -@UiThread -public final class MapboxMap { - - private static final String TAG = "Mbgl-MapboxMap"; - - private final NativeMap nativeMapView; - private final UiSettings uiSettings; - private final Projection projection; - private final Transform transform; - private final CameraChangeDispatcher cameraChangeDispatcher; - private final OnGesturesManagerInteractionListener onGesturesManagerInteractionListener; - private final List awaitingStyleGetters = new ArrayList<>(); - private final List developerAnimationStartedListeners; - - @Nullable - private Style.OnStyleLoaded styleLoadedCallback; - - private LocationComponent locationComponent; - private AnnotationManager annotationManager; - - @Nullable - private MapboxMap.OnFpsChangedListener onFpsChangedListener; - - @Nullable - private Style style; - - private boolean debugActive; - - MapboxMap(NativeMap map, Transform transform, UiSettings ui, Projection projection, - OnGesturesManagerInteractionListener listener, CameraChangeDispatcher cameraChangeDispatcher, - List developerAnimationStartedListeners) { - this.nativeMapView = map; - this.uiSettings = ui; - this.projection = projection; - this.transform = transform; - this.onGesturesManagerInteractionListener = listener; - this.cameraChangeDispatcher = cameraChangeDispatcher; - this.developerAnimationStartedListeners = developerAnimationStartedListeners; - } - - void initialise(@NonNull Context context, @NonNull MapboxMapOptions options) { - transform.initialise(this, options); - uiSettings.initialise(context, options); - - // Map configuration - setDebugActive(options.getDebugActive()); - setApiBaseUrl(options); - setPrefetchesTiles(options); - } - - /** - * Get the Style of the map asynchronously. - */ - public void getStyle(@NonNull Style.OnStyleLoaded onStyleLoaded) { - if (style != null && style.isFullyLoaded()) { - onStyleLoaded.onStyleLoaded(style); - } else { - awaitingStyleGetters.add(onStyleLoaded); - } - } - - /** - * Get the Style of the map. - *

- * Returns null when style is being loaded. - *

- * - * @return the style of the map - */ - @Nullable - public Style getStyle() { - if (style == null || !style.isFullyLoaded()) { - return null; - } else { - return style; - } - } - - /** - * Called when the hosting Activity/Fragment onStart() method is called. - */ - void onStart() { - locationComponent.onStart(); - } - - /** - * Called when the hosting Activity/Fragment onStop() method is called. - */ - void onStop() { - locationComponent.onStop(); - } - - /** - * Called when the hosting Activity/Fragment is going to be destroyed and map state needs to be saved. - * - * @param outState the bundle to save the state to. - */ - void onSaveInstanceState(@NonNull Bundle outState) { - outState.putParcelable(MapboxConstants.STATE_CAMERA_POSITION, transform.getCameraPosition()); - outState.putBoolean(MapboxConstants.STATE_DEBUG_ACTIVE, isDebugActive()); - uiSettings.onSaveInstanceState(outState); - } - - /** - * Called when the hosting Activity/Fragment is recreated and map state needs to be restored. - * - * @param savedInstanceState the bundle containing the saved state - */ - void onRestoreInstanceState(@NonNull Bundle savedInstanceState) { - final CameraPosition cameraPosition = savedInstanceState.getParcelable(MapboxConstants.STATE_CAMERA_POSITION); - - uiSettings.onRestoreInstanceState(savedInstanceState); - - if (cameraPosition != null) { - moveCamera(CameraUpdateFactory.newCameraPosition( - new CameraPosition.Builder(cameraPosition).build()) - ); - } - - nativeMapView.setDebug(savedInstanceState.getBoolean(MapboxConstants.STATE_DEBUG_ACTIVE)); - } - - /** - * Called when the hosting Activity/Fragment onDestroy()/onDestroyView() method is called. - */ - void onDestroy() { - locationComponent.onDestroy(); - if (style != null) { - style.clear(); - } - cameraChangeDispatcher.onDestroy(); - } - - /** - * Called before the OnMapReadyCallback is invoked. - */ - void onPreMapReady() { - transform.invalidateCameraPosition(); - annotationManager.reloadMarkers(); - annotationManager.adjustTopOffsetPixels(this); - } - - /** - * Called when the OnMapReadyCallback has finished executing. - *

- * Invalidation of the camera position is required to update the added components in - * OnMapReadyCallback with the correct transformation. - *

- */ - void onPostMapReady() { - transform.invalidateCameraPosition(); - } - - /** - * Called when the map finished loading a style. - */ - void onFinishLoadingStyle() { - notifyStyleLoaded(); - } - - /** - * Called when the map failed loading a style. - */ - void onFailLoadingStyle() { - styleLoadedCallback = null; - } - - /** - * Called when the region is changing or has changed. - */ - void onUpdateRegionChange() { - annotationManager.update(); - } - - /** - * Called when the map frame is fully rendered. - */ - void onUpdateFullyRendered() { - CameraPosition cameraPosition = transform.invalidateCameraPosition(); - if (cameraPosition != null) { - uiSettings.update(cameraPosition); - } - } - - /** - * Experimental feature. Do not use. - */ - long getNativeMapPtr() { - return nativeMapView.getNativePtr(); - } - - // Style - - /** - * Sets tile pre-fetching zoom delta from MapboxOptions. - * - * @param options the options object - */ - private void setPrefetchesTiles(@NonNull MapboxMapOptions options) { - if (!options.getPrefetchesTiles()) { - setPrefetchZoomDelta(0); - } else { - setPrefetchZoomDelta(options.getPrefetchZoomDelta()); - } - } - - /** - * Enable or disable tile pre-fetching. Pre-fetching makes sure that a low-resolution - * tile is rendered as soon as possible at the expense of a little bandwidth. - * - * @param enable true to enable - * @deprecated Use {@link #setPrefetchZoomDelta(int)} instead. - */ - @Deprecated - public void setPrefetchesTiles(boolean enable) { - nativeMapView.setPrefetchTiles(enable); - } - - /** - * Check whether tile pre-fetching is enabled or not. - * - * @return true if enabled - * @see MapboxMap#setPrefetchesTiles(boolean) - * @deprecated Use {@link #getPrefetchZoomDelta()} instead. - */ - @Deprecated - public boolean getPrefetchesTiles() { - return nativeMapView.getPrefetchTiles(); - } - - /** - * Set the tile pre-fetching zoom delta. Pre-fetching makes sure that a low-resolution - * tile at the (current_zoom_level - delta) is rendered as soon as possible at the - * expense of a little bandwidth. - * Note: This operation will override the MapboxMapOptions#setPrefetchesTiles(boolean) - * Setting zoom delta to 0 will disable pre-fetching. - * Default zoom delta is 4. - * - * @param delta zoom delta - */ - public void setPrefetchZoomDelta(@IntRange(from = 0) int delta) { - nativeMapView.setPrefetchZoomDelta(delta); - } - - /** - * Check current pre-fetching zoom delta. - * - * @return current zoom delta. - * @see MapboxMap#setPrefetchZoomDelta(int) - */ - @IntRange(from = 0) - public int getPrefetchZoomDelta() { - return nativeMapView.getPrefetchZoomDelta(); - } - - // - // MinZoom - // - - /** - *

- * Sets the minimum zoom level the map can be displayed at. - *

- * - * @param minZoom The new minimum zoom level. - */ - public void setMinZoomPreference( - @FloatRange(from = MapboxConstants.MINIMUM_ZOOM, to = MapboxConstants.MAXIMUM_ZOOM) double minZoom) { - transform.setMinZoom(minZoom); - } - - /** - *

- * Gets the minimum zoom level the map can be displayed at. - *

- * - * @return The minimum zoom level. - */ - public double getMinZoomLevel() { - return transform.getMinZoom(); - } - - // - // MaxZoom - // - - /** - *

- * Sets the maximum zoom level the map can be displayed at. - *

- *

- * The default maximum zoomn level is 22. The upper bound for this value is 25.5. - *

- * - * @param maxZoom The new maximum zoom level. - */ - public void setMaxZoomPreference(@FloatRange(from = MapboxConstants.MINIMUM_ZOOM, - to = MapboxConstants.MAXIMUM_ZOOM) double maxZoom) { - transform.setMaxZoom(maxZoom); - } - - /** - *

- * Gets the maximum zoom level the map can be displayed at. - *

- * - * @return The maximum zoom level. - */ - public double getMaxZoomLevel() { - return transform.getMaxZoom(); - } - - // - // UiSettings - // - - /** - * Gets the user interface settings for the map. - * - * @return the UiSettings associated with this map - */ - @NonNull - public UiSettings getUiSettings() { - return uiSettings; - } - - // - // Projection - // - - /** - * Get the Projection object that you can use to convert between screen coordinates and latitude/longitude - * coordinates. - * - * @return the Projection associated with this map - */ - @NonNull - public Projection getProjection() { - return projection; - } - - // - // Camera API - // - - /** - * Cancels ongoing animations. - *

- * This invokes the {@link CancelableCallback} for ongoing camera updates. - *

- */ - public void cancelTransitions() { - transform.cancelTransitions(); - } - - /** - * Gets the current position of the camera. - * The CameraPosition returned is a snapshot of the current position, and will not automatically update when the - * camera moves. - * - * @return The current position of the Camera. - */ - @NonNull - public final CameraPosition getCameraPosition() { - return transform.getCameraPosition(); - } - - /** - * Repositions the camera according to the cameraPosition. - * The move is instantaneous, and a subsequent getCameraPosition() will reflect the new position. - * See CameraUpdateFactory for a set of updates. - * - * @param cameraPosition the camera position to set - */ - public void setCameraPosition(@NonNull CameraPosition cameraPosition) { - moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), null); - } - - /** - * Repositions the camera according to the instructions defined in the update. - * The move is instantaneous, and a subsequent getCameraPosition() will reflect the new position. - * See CameraUpdateFactory for a set of updates. - * - * @param update The change that should be applied to the camera. - */ - public final void moveCamera(@NonNull CameraUpdate update) { - moveCamera(update, null); - } - - /** - * Repositions the camera according to the instructions defined in the update. - * The move is instantaneous, and a subsequent getCameraPosition() will reflect the new position. - * See CameraUpdateFactory for a set of updates. - * - * @param update The change that should be applied to the camera - * @param callback the callback to be invoked when an animation finishes or is canceled - */ - public final void moveCamera(@NonNull final CameraUpdate update, - @Nullable final MapboxMap.CancelableCallback callback) { - notifyDeveloperAnimationListeners(); - transform.moveCamera(MapboxMap.this, update, callback); - } - - /** - * Gradually move the camera by the default duration, zoom will not be affected unless specified - * within {@link CameraUpdate}. If {@link #getCameraPosition()} is called during the animation, - * it will return the current location of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void easeCamera(@NonNull CameraUpdate update) { - easeCamera(update, MapboxConstants.ANIMATION_DURATION); - } - - /** - * Gradually move the camera by the default duration, zoom will not be affected unless specified - * within {@link CameraUpdate}. If {@link #getCameraPosition()} is called during the animation, - * it will return the current location of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @param callback An optional callback to be notified from the main thread when the animation - * stops. If the animation stops due to its natural completion, the callback - * will be notified with onFinish(). If the animation stops due to interruption - * by a later camera movement or a user gesture, onCancel() will be called. - * Do not update or ease the camera from within onCancel(). - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void easeCamera(@NonNull CameraUpdate update, @Nullable final MapboxMap.CancelableCallback callback) { - easeCamera(update, MapboxConstants.ANIMATION_DURATION, callback); - } - - /** - * Gradually move the camera by a specified duration in milliseconds, zoom will not be affected - * unless specified within {@link CameraUpdate}. If {@link #getCameraPosition()} is called - * during the animation, it will return the current location of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void easeCamera(@NonNull CameraUpdate update, int durationMs) { - easeCamera(update, durationMs, null); - } - - /** - * Gradually move the camera by a specified duration in milliseconds, zoom will not be affected - * 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. - *

- * Note that this will cancel location tracking mode if enabled. - *

- * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @param callback An optional callback to be notified from the main thread when the animation - * stops. If the animation stops due to its natural completion, the callback - * will be notified with onFinish(). If the animation stops due to interruption - * by a later camera movement or a user gesture, onCancel() will be called. - * Do not update or ease the camera from within onCancel(). - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void easeCamera(@NonNull CameraUpdate update, int durationMs, - @Nullable final MapboxMap.CancelableCallback callback) { - easeCamera(update, durationMs, true, callback); - } - - /** - * Gradually move the camera by a specified duration in milliseconds, zoom will not be affected - * 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. - *

- * Note that this will cancel location tracking mode if enabled. - *

- * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @param easingInterpolator True for easing interpolator, false for linear. - */ - public final void easeCamera(@NonNull CameraUpdate update, int durationMs, boolean easingInterpolator) { - easeCamera(update, durationMs, easingInterpolator, null); - } - - /** - * Gradually move the camera by a specified duration in milliseconds, zoom will not be affected - * 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. - * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @param easingInterpolator True for easing interpolator, false for linear. - * @param callback An optional callback to be notified from the main thread when the animation - * stops. If the animation stops due to its natural completion, the callback - * will be notified with onFinish(). If the animation stops due to interruption - * by a later camera movement or a user gesture, onCancel() will be called. - * Do not update or ease the camera from within onCancel(). - */ - public final void easeCamera(@NonNull final CameraUpdate update, - final int durationMs, - final boolean easingInterpolator, - @Nullable final MapboxMap.CancelableCallback callback) { - if (durationMs <= 0) { - throw new IllegalArgumentException("Null duration passed into easeCamera"); - } - notifyDeveloperAnimationListeners(); - transform.easeCamera(MapboxMap.this, update, durationMs, easingInterpolator, callback); - } - - /** - * Animate the camera to a new location defined within {@link CameraUpdate} using a transition - * animation that evokes powered flight. The animation will last the default amount of time. - * During the animation, a call to {@link #getCameraPosition()} returns an intermediate location - * of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void animateCamera(@NonNull CameraUpdate update) { - animateCamera(update, MapboxConstants.ANIMATION_DURATION, null); - } - - /** - * Animate the camera to a new location defined within {@link CameraUpdate} using a transition - * animation that evokes powered flight. The animation will last the default amount of time. A - * callback can be used to be notified when animating the camera stops. During the animation, a - * call to {@link #getCameraPosition()} returns an intermediate location of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @param callback The callback to invoke from the main thread when the animation stops. If the - * animation completes normally, onFinish() is called; otherwise, onCancel() is - * called. Do not update or animate the camera from within onCancel(). - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void animateCamera(@NonNull CameraUpdate update, @Nullable MapboxMap.CancelableCallback callback) { - animateCamera(update, MapboxConstants.ANIMATION_DURATION, callback); - } - - /** - * Animate the camera to a new location defined within {@link CameraUpdate} using a transition - * animation that evokes powered flight. The animation will last a specified amount of time - * given in milliseconds. During the animation, a call to {@link #getCameraPosition()} returns - * an intermediate location of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void animateCamera(@NonNull CameraUpdate update, int durationMs) { - animateCamera(update, durationMs, null); - } - - /** - * Animate the camera to a new location defined within {@link CameraUpdate} using a transition - * animation that evokes powered flight. The animation will last a specified amount of time - * given in milliseconds. A callback can be used to be notified when animating the camera stops. - * During the animation, a call to {@link #getCameraPosition()} returns an intermediate location - * of the camera in flight. - * - * @param update The change that should be applied to the camera. - * @param durationMs The duration of the animation in milliseconds. This must be strictly - * positive, otherwise an IllegalArgumentException will be thrown. - * @param callback An optional callback to be notified from the main thread when the animation - * stops. If the animation stops due to its natural completion, the callback - * will be notified with onFinish(). If the animation stops due to interruption - * by a later camera movement or a user gesture, onCancel() will be called. - * Do not update or animate the camera from within onCancel(). If a callback - * isn't required, leave it as null. - * @see com.mapbox.mapboxsdk.camera.CameraUpdateFactory for a set of updates. - */ - public final void animateCamera(@NonNull final CameraUpdate update, final int durationMs, - @Nullable final MapboxMap.CancelableCallback callback) { - if (durationMs <= 0) { - throw new IllegalArgumentException("Null duration passed into animateCamera"); - } - notifyDeveloperAnimationListeners(); - transform.animateCamera(MapboxMap.this, update, durationMs, callback); - } - - /** - * Scrolls the camera over the map, shifting the center of view by the specified number of pixels in the x and y - * directions. - * - * @param x Amount of pixels to scroll to in x direction - * @param y Amount of pixels to scroll to in y direction - */ - public void scrollBy(float x, float y) { - scrollBy(x, y, 0); - } - - /** - * Scrolls the camera over the map, shifting the center of view by the specified number of pixels in the x and y - * directions. - * - * @param x Amount of pixels to scroll to in x direction - * @param y Amount of pixels to scroll to in y direction - * @param duration Amount of time the scrolling should take - */ - public void scrollBy(float x, float y, long duration) { - notifyDeveloperAnimationListeners(); - nativeMapView.moveBy(x, y, duration); - } - - // - // Reset North - // - - /** - * Resets the map view to face north. - */ - public void resetNorth() { - notifyDeveloperAnimationListeners(); - transform.resetNorth(); - } - - /** - * Transform the map bearing given a bearing, focal point coordinates, and a duration. - * - * @param bearing The bearing of the Map to be transformed to - * @param focalX The x coordinate of the focal point - * @param focalY The y coordinate of the focal point - * @param duration The duration of the transformation - */ - public void setFocalBearing(double bearing, float focalX, float focalY, long duration) { - notifyDeveloperAnimationListeners(); - transform.setBearing(bearing, focalX, focalY, duration); - } - - /** - * Returns the measured height of the Map. - * - * @return the height of the map - */ - public float getHeight() { - return projection.getHeight(); - } - - /** - * Returns the measured width of the Map. - * - * @return the width of the map - */ - public float getWidth() { - return projection.getWidth(); - } - - // - // Offline - // - - /** - * Loads a new style from the specified offline region definition and moves the map camera to that region. - * - * @param definition the offline region definition - * @see OfflineRegionDefinition - */ - public void setOfflineRegionDefinition(@NonNull OfflineRegionDefinition definition) { - setOfflineRegionDefinition(definition, null); - } - - /** - * Loads a new style from the specified offline region definition and moves the map camera to that region. - * - * @param definition the offline region definition - * @param callback the callback to be invoked when the style has loaded - * @see OfflineRegionDefinition - */ - public void setOfflineRegionDefinition(@NonNull OfflineRegionDefinition definition, - @Nullable Style.OnStyleLoaded callback) { - double minZoom = definition.getMinZoom(); - double maxZoom = definition.getMaxZoom(); - CameraPosition cameraPosition = new CameraPosition.Builder() - .target(definition.getBounds().getCenter()) - .zoom(minZoom) - .build(); - moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); - setMinZoomPreference(minZoom); - setMaxZoomPreference(maxZoom); - setStyle(new Style.Builder().fromUri(definition.getStyleURL()), callback); - } - - // - // Debug - // - - /** - * Returns whether the map debug information is currently shown. - * - * @return If true, map debug information is currently shown. - */ - public boolean isDebugActive() { - return debugActive; - } - - /** - *

- * Changes whether the map debug information is shown. - *

- * The default value is false. - * - * @param debugActive If true, map debug information is shown. - */ - public void setDebugActive(boolean debugActive) { - this.debugActive = debugActive; - nativeMapView.setDebug(debugActive); - } - - /** - *

- * Cycles through the map debug options. - *

- * The value of isDebugActive reflects whether there are - * any map debug options enabled or disabled. - * - * @see #isDebugActive() - */ - public void cycleDebugOptions() { - nativeMapView.cycleDebugOptions(); - this.debugActive = nativeMapView.getDebug(); - } - - // - // API endpoint config - // - - private void setApiBaseUrl(@NonNull MapboxMapOptions options) { - String apiBaseUrl = options.getApiBaseUrl(); - if (!TextUtils.isEmpty(apiBaseUrl)) { - nativeMapView.setApiBaseUrl(apiBaseUrl); - } - } - - // - // Styling - // - - /** - * Loads a new map style from the specified bundled style. - *

- * This method is asynchronous and will return before the style finishes loading. - * If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener} - * callback or use the {@link #setStyle(String, Style.OnStyleLoaded)} method instead. - *

- * If the style fails to load or an invalid style URL is set, the map view will become blank. - * An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback - * will be triggered. - * - * @param style The bundled style - * @see Style - */ - public void setStyle(@Style.StyleUrl String style) { - this.setStyle(style, null); - } - - /** - * Loads a new map style from the specified bundled style. - *

- * If the style fails to load or an invalid style URL is set, the map view will become blank. - * An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback - * will be triggered. - *

- * - * @param style The bundled style - * @param callback The callback to be invoked when the style has loaded - * @see Style - */ - public void setStyle(@Style.StyleUrl String style, final Style.OnStyleLoaded callback) { - this.setStyle(new Style.Builder().fromUri(style), callback); - } - - /** - * Loads a new map style from the specified builder. - *

- * If the builder fails to load, the map view will become blank. An error message will be logged in the Android logcat - * and {@link MapView.OnDidFailLoadingMapListener} callback will be triggered. If you wish to wait for the map to - * finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener} callback or use the - * {@link #setStyle(String, Style.OnStyleLoaded)} instead. - *

- * - * @param builder The style builder - * @see Style - */ - public void setStyle(Style.Builder builder) { - this.setStyle(builder, null); - } - - /** - * Loads a new map style from the specified builder. - *

- * If the builder fails to load, the map view will become blank. An error message will be logged in the Android logcat - * and {@link MapView.OnDidFailLoadingMapListener} callback will be triggered. - *

- * - * @param builder The style builder - * @param callback The callback to be invoked when the style has loaded - * @see Style - */ - public void setStyle(Style.Builder builder, final Style.OnStyleLoaded callback) { - styleLoadedCallback = callback; - locationComponent.onStartLoadingMap(); - if (style != null) { - style.clear(); - } - - style = builder.build(nativeMapView); - if (!TextUtils.isEmpty(builder.getUri())) { - nativeMapView.setStyleUri(builder.getUri()); - } else if (!TextUtils.isEmpty(builder.getJson())) { - nativeMapView.setStyleJson(builder.getJson()); - } else { - // user didn't provide a `from` component, load a blank style instead - nativeMapView.setStyleJson(Style.EMPTY_JSON); - } - } - - void notifyStyleLoaded() { - if (nativeMapView.isDestroyed()) { - return; - } - - if (style != null) { - style.onDidFinishLoadingStyle(); - locationComponent.onFinishLoadingStyle(); - - // notify the listener provided with the style setter - if (styleLoadedCallback != null) { - styleLoadedCallback.onStyleLoaded(style); - } - - // notify style getters - for (Style.OnStyleLoaded styleGetter : awaitingStyleGetters) { - styleGetter.onStyleLoaded(style); - } - } else { - MapStrictMode.strictModeViolation("No style to provide."); - } - styleLoadedCallback = null; - awaitingStyleGetters.clear(); - } - - // - // Annotations - // - - /** - *

- * Adds a marker to this map. - *

- * The marker's icon is rendered on the map at the location {@code Marker.position}. - * If {@code Marker.title} is defined, the map shows an info box with the marker's title and snippet. - * - * @param markerOptions A marker options object that defines how to render the marker - * @return The {@code Marker} that was added to the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public Marker addMarker(@NonNull MarkerOptions markerOptions) { - return annotationManager.addMarker(markerOptions, this); - } - - /** - *

- * Adds a marker to this map. - *

- * The marker's icon is rendered on the map at the location {@code Marker.position}. - * If {@code Marker.title} is defined, the map shows an info box with the marker's title and snippet. - * - * @param markerOptions A marker options object that defines how to render the marker - * @return The {@code Marker} that was added to the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public Marker addMarker(@NonNull BaseMarkerOptions markerOptions) { - return annotationManager.addMarker(markerOptions, this); - } - - /** - *

- * Adds multiple markers to this map. - *

- * The marker's icon is rendered on the map at the location {@code Marker.position}. - * If {@code Marker.title} is defined, the map shows an info box with the marker's title and snippet. - * - * @param markerOptionsList A list of marker options objects that defines how to render the markers - * @return A list of the {@code Marker}s that were added to the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List addMarkers(@NonNull List markerOptionsList) { - return annotationManager.addMarkers(markerOptionsList, this); - } - - /** - *

- * Updates a marker on this map. Does nothing if the marker isn't already added. - *

- * - * @param updatedMarker An updated marker object - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void updateMarker(@NonNull Marker updatedMarker) { - annotationManager.updateMarker(updatedMarker, this); - } - - /** - * Adds a polyline to this map. - * - * @param polylineOptions A polyline options object that defines how to render the polyline - * @return The {@code Polyine} that was added to the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public Polyline addPolyline(@NonNull PolylineOptions polylineOptions) { - return annotationManager.addPolyline(polylineOptions, this); - } - - /** - * Adds multiple polylines to this map. - * - * @param polylineOptionsList A list of polyline options objects that defines how to render the polylines. - * @return A list of the {@code Polyline}s that were added to the map. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List addPolylines(@NonNull List polylineOptionsList) { - return annotationManager.addPolylines(polylineOptionsList, this); - } - - /** - * Update a polyline on this map. - * - * @param polyline An updated polyline object. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void updatePolyline(@NonNull Polyline polyline) { - annotationManager.updatePolyline(polyline); - } - - /** - * Adds a polygon to this map. - * - * @param polygonOptions A polygon options object that defines how to render the polygon. - * @return The {@code Polygon} that was added to the map. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public Polygon addPolygon(@NonNull PolygonOptions polygonOptions) { - return annotationManager.addPolygon(polygonOptions, this); - } - - /** - * Adds multiple polygons to this map. - * - * @param polygonOptionsList A list of polygon options objects that defines how to render the polygons - * @return A list of the {@code Polygon}s that were added to the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List addPolygons(@NonNull List polygonOptionsList) { - return annotationManager.addPolygons(polygonOptionsList, this); - } - - /** - * Update a polygon on this map. - * - * @param polygon An updated polygon object - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void updatePolygon(@NonNull Polygon polygon) { - annotationManager.updatePolygon(polygon); - } - - /** - *

- * Convenience method for removing a Marker from the map. - *

- * Calls removeAnnotation() internally. - * - * @param marker Marker to remove - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removeMarker(@NonNull Marker marker) { - annotationManager.removeAnnotation(marker); - } - - /** - *

- * Convenience method for removing a Polyline from the map. - *

- * Calls removeAnnotation() internally. - * - * @param polyline Polyline to remove - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removePolyline(@NonNull Polyline polyline) { - annotationManager.removeAnnotation(polyline); - } - - /** - *

- * Convenience method for removing a Polygon from the map. - *

- * Calls removeAnnotation() internally. - * - * @param polygon Polygon to remove - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removePolygon(@NonNull Polygon polygon) { - annotationManager.removeAnnotation(polygon); - } - - /** - * Removes an annotation from the map. - * - * @param annotation The annotation object to remove. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removeAnnotation(@NonNull Annotation annotation) { - annotationManager.removeAnnotation(annotation); - } - - /** - * Removes an annotation from the map - * - * @param id The identifier associated to the annotation to be removed - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removeAnnotation(long id) { - annotationManager.removeAnnotation(id); - } - - /** - * Removes multiple annotations from the map. - * - * @param annotationList A list of annotation objects to remove. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removeAnnotations(@NonNull List annotationList) { - annotationManager.removeAnnotations(annotationList); - } - - /** - * Removes all annotations from the map. - * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void removeAnnotations() { - annotationManager.removeAnnotations(); - } - - /** - * Removes all markers, polylines, polygons, overlays, etc from the map. - * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void clear() { - annotationManager.removeAnnotations(); - } - - /** - * Return a annotation based on its id. - * - * @param id the id used to look up an annotation - * @return An annotation with a matched id, null is returned if no match was found - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @Nullable - public Annotation getAnnotation(long id) { - return annotationManager.getAnnotation(id); - } - - /** - * Returns a list of all the annotations on the map. - * - * @return A list of all the annotation objects. The returned object is a copy so modifying this - * list will not update the map - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List getAnnotations() { - return annotationManager.getAnnotations(); - } - - /** - * Returns a list of all the markers on the map. - * - * @return A list of all the markers objects. The returned object is a copy so modifying this - * list will not update the map. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List getMarkers() { - return annotationManager.getMarkers(); - } - - /** - * Returns a list of all the polygons on the map. - * - * @return A list of all the polygon objects. The returned object is a copy so modifying this - * list will not update the map. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List getPolygons() { - return annotationManager.getPolygons(); - } - - /** - * Returns a list of all the polylines on the map. - * - * @return A list of all the polylines objects. The returned object is a copy so modifying this - * list will not update the map. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List getPolylines() { - return annotationManager.getPolylines(); - } - - /** - * Sets a callback that's invoked when the user clicks on a marker. - * - * @param listener The callback that's invoked when the user clicks on a marker. - * To unset the callback, use null. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void setOnMarkerClickListener(@Nullable OnMarkerClickListener listener) { - annotationManager.setOnMarkerClickListener(listener); - } - - /** - * Sets a callback that's invoked when the user clicks on a polygon. - * - * @param listener The callback that's invoked when the user clicks on a polygon. - * To unset the callback, use null. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void setOnPolygonClickListener(@Nullable OnPolygonClickListener listener) { - annotationManager.setOnPolygonClickListener(listener); - } - - /** - * Sets a callback that's invoked when the user clicks on a polyline. - * - * @param listener The callback that's invoked when the user clicks on a polyline. - * To unset the callback, use null. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void setOnPolylineClickListener(@Nullable OnPolylineClickListener listener) { - annotationManager.setOnPolylineClickListener(listener); - } - - /** - *

- * Selects a marker. The selected marker will have it's info window opened. - * Any other open info windows will be closed unless isAllowConcurrentMultipleOpenInfoWindows() - * is true. - *

- * Selecting an already selected marker will have no effect. - * - * @param marker The marker to select. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void selectMarker(@NonNull Marker marker) { - if (marker == null) { - Logger.w(TAG, "marker was null, so just returning"); - return; - } - annotationManager.selectMarker(marker); - } - - /** - * Deselects any currently selected marker. All markers will have it's info window closed. - * - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void deselectMarkers() { - annotationManager.deselectMarkers(); - } - - /** - * Deselects a currently selected marker. The selected marker will have it's info window closed. - * - * @param marker the marker to deselect - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void deselectMarker(@NonNull Marker marker) { - annotationManager.deselectMarker(marker); - } - - /** - * Gets the currently selected marker. - * - * @return The currently selected marker. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @NonNull - public List getSelectedMarkers() { - return annotationManager.getSelectedMarkers(); - } - - // - // InfoWindow - // - - /** - *

- * Sets a custom renderer for the contents of info window. - *

- * When set your callback is invoked when an info window is about to be shown. By returning - * a custom {@link View}, the default info window will be replaced. - * - * @param infoWindowAdapter The callback to be invoked when an info window will be shown. - * To unset the callback, use null. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void setInfoWindowAdapter(@Nullable InfoWindowAdapter infoWindowAdapter) { - annotationManager.getInfoWindowManager().setInfoWindowAdapter(infoWindowAdapter); - } - - /** - * Gets the callback to be invoked when an info window will be shown. - * - * @return The callback to be invoked when an info window will be shown. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - @Nullable - public InfoWindowAdapter getInfoWindowAdapter() { - return annotationManager.getInfoWindowManager().getInfoWindowAdapter(); - } - - /** - * Changes whether the map allows concurrent multiple infowindows to be shown. - * - * @param allow If true, map allows concurrent multiple infowindows to be shown. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public void setAllowConcurrentMultipleOpenInfoWindows(boolean allow) { - annotationManager.getInfoWindowManager().setAllowConcurrentMultipleOpenInfoWindows(allow); - } - - /** - * Returns whether the map allows concurrent multiple infowindows to be shown. - * - * @return If true, map allows concurrent multiple infowindows to be shown. - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public boolean isAllowConcurrentMultipleOpenInfoWindows() { - return annotationManager.getInfoWindowManager().isAllowConcurrentMultipleOpenInfoWindows(); - } - - // - // LatLngBounds - // - - /** - * Sets a LatLngBounds that constraints map transformations to this bounds. - *

- * Set to null to clear current bounds, newly set bounds will override previously set bounds. - *

- * - * @param latLngBounds the bounds to constrain the map with - */ - public void setLatLngBoundsForCameraTarget(@Nullable LatLngBounds latLngBounds) { - nativeMapView.setLatLngBounds(latLngBounds); - } - - - /** - * Get a camera position that fits a provided bounds and the current camera tilt and bearing. - * - * @param latLngBounds the bounds to set the map with - * @return the camera position that fits the bounds - */ - @Nullable - public CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds latLngBounds) { - // we use current camera tilt value to provide expected transformations as #11993 - return getCameraForLatLngBounds(latLngBounds, new int[] {0, 0, 0, 0}); - } - - - /** - * Get a camera position that fits a provided bounds and padding and the current camera tilt and bearing. - * - * @param latLngBounds the bounds to set the map with - * @param padding the padding to apply to the bounds - * @return the camera position that fits the bounds and padding - */ - @Nullable - public CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds latLngBounds, - @NonNull @Size(value = 4) int[] padding) { - // we use current camera tilt/bearing value to provide expected transformations as #11993 - return getCameraForLatLngBounds(latLngBounds, padding, transform.getRawBearing(), transform.getTilt()); - } - - - /** - * Get a camera position that fits a provided bounds, bearing and tilt. - * - * @param latLngBounds the bounds to set the map with - * @param bearing the bearing to transform the camera position with - * @param tilt to transform the camera position with - * @return the camera position that fits the bounds and given bearing and tilt - */ - @Nullable - public CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds latLngBounds, - @FloatRange(from = MapboxConstants.MINIMUM_DIRECTION, - to = MapboxConstants.MAXIMUM_DIRECTION) double bearing, - @FloatRange(from = MapboxConstants.MINIMUM_TILT, - to = MapboxConstants.MAXIMUM_TILT) double tilt) { - return getCameraForLatLngBounds(latLngBounds, new int[] {0, 0, 0, 0}, bearing, tilt); - } - - - /** - * Get a camera position that fits a provided bounds, padding, bearing and tilt. - * - * @param latLngBounds the bounds to set the map with - * @param padding the padding to apply to the bounds - * @param bearing the bearing to transform the camera position with - * @param tilt to transform the camera position with - * @return the camera position that fits the bounds, bearing and tilt - */ - @Nullable - public CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds latLngBounds, - @NonNull @Size(value = 4) int[] padding, - @FloatRange(from = MapboxConstants.MINIMUM_DIRECTION, - to = MapboxConstants.MAXIMUM_DIRECTION) double bearing, - @FloatRange(from = MapboxConstants.MINIMUM_TILT, - to = MapboxConstants.MAXIMUM_TILT) double tilt) { - return nativeMapView.getCameraForLatLngBounds(latLngBounds, padding, bearing, tilt); - } - - /** - * Get a camera position that fits a provided shape. - * - * @param geometry the geometry to wraps the map with - * @return the camera position that fits the geometry inside - */ - @Nullable - public CameraPosition getCameraForGeometry(@NonNull Geometry geometry) { - // we use current camera tilt value to provide expected transformations as #11993 - return getCameraForGeometry(geometry, new int[] {0, 0, 0, 0}); - } - - /** - * Get a camera position that fits a provided shape and padding. - * - * @param geometry the geometry to wraps the map with - * @param padding the padding to apply to the bounds - * @return the camera position that fits the geometry inside and padding - */ - @Nullable - public CameraPosition getCameraForGeometry(@NonNull Geometry geometry, - @NonNull @Size(value = 4) int[] padding) { - // we use current camera tilt/bearing value to provide expected transformations as #11993 - return getCameraForGeometry(geometry, padding, transform.getBearing(), transform.getTilt()); - } - - /** - * Get a camera position that fits a provided shape with a given bearing and tilt. - * - * @param geometry the geometry to wraps the map with - * @param bearing the bearing at which to compute the geometry's bounds - * @param tilt the tilt at which to compute the geometry's bounds - * @return the camera position that the geometry inside with bearing and tilt - */ - @Nullable - public CameraPosition getCameraForGeometry(@NonNull Geometry geometry, - @FloatRange(from = MapboxConstants.MINIMUM_DIRECTION, - to = MapboxConstants.MAXIMUM_DIRECTION) double bearing, - @FloatRange(from = MapboxConstants.MINIMUM_TILT, - to = MapboxConstants.MAXIMUM_TILT) double tilt) { - return getCameraForGeometry(geometry, new int[] {0, 0, 0, 0}, bearing, tilt); - } - - /** - * Get a camera position that fits a provided shape with a given padding, bearing and tilt. - * - * @param geometry the geometry to wraps the map with - * @param padding the padding to apply to the bounds - * @param bearing the bearing at which to compute the geometry's bounds - * @param tilt the tilt at which to compute the geometry's bounds - * @return the camera position that fits the geometry inside with padding, bearing and tilt - */ - @Nullable - public CameraPosition getCameraForGeometry(@NonNull Geometry geometry, - @NonNull @Size(value = 4) int[] padding, - @FloatRange(from = MapboxConstants.MINIMUM_DIRECTION, - to = MapboxConstants.MAXIMUM_DIRECTION) double bearing, - @FloatRange(from = MapboxConstants.MINIMUM_TILT, - to = MapboxConstants.MAXIMUM_TILT) double tilt) { - return nativeMapView.getCameraForGeometry(geometry, padding, bearing, tilt); - } - - // - // Padding - // - - /** - *

- * Sets the distance from the edges of the map view's frame to the edges of the map - * view's logical viewport. - *

- *

- * 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 - * frame from the viewport. For instance, if the only the top edge is inset, the - * map center is effectively shifted downward. - *

- *

- * This method sets the padding "lazily". - * This means that the padding is going to be applied with the next camera transformation. - * To apply the padding immediately use {@link CameraPosition.Builder#padding(double, double, double, double)} - * or {@link CameraUpdateFactory#paddingTo(double, double, double, double)}. - *

- * - * @param left The left margin in pixels. - * @param top The top margin in pixels. - * @param right The right margin in pixels. - * @param bottom The bottom margin in pixels. - * @deprecated Use {@link CameraPosition.Builder#padding(double, double, double, double)} - * or {@link CameraUpdateFactory#paddingTo(double, double, double, double)} instead. - */ - @Deprecated - public void setPadding(int left, int top, int right, int bottom) { - // TODO padding should be passed as doubles - projection.setContentPadding(new int[] {left, top, right, bottom}); - uiSettings.invalidate(); - } - - /** - * Returns the current configured content padding on map view. This might return the currently visible padding - * or the padding cached but not yet applied by {@link #setPadding(int, int, int, int)}. - * - * @return An array with length 4 in the LTRB order. - * @deprecated Use {@link CameraPosition#padding} instead. - */ - @Deprecated - @NonNull - public int[] getPadding() { - // TODO this should return double[] (semver major change) - return projection.getContentPadding(); - } - - // - // Map events - // - - /** - * Adds a callback that is invoked when camera movement has ended. - * - * @param listener the listener to notify - */ - public void addOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { - cameraChangeDispatcher.addOnCameraIdleListener(listener); - } - - /** - * Removes a callback that is invoked when camera movement has ended. - * - * @param listener the listener to remove - */ - public void removeOnCameraIdleListener(@NonNull OnCameraIdleListener listener) { - cameraChangeDispatcher.removeOnCameraIdleListener(listener); - } - - /** - * Adds a callback that is invoked when camera movement was cancelled. - * - * @param listener the listener to notify - */ - public void addOnCameraMoveCancelListener(@NonNull OnCameraMoveCanceledListener listener) { - cameraChangeDispatcher.addOnCameraMoveCancelListener(listener); - } - - /** - * Removes a callback that is invoked when camera movement was cancelled. - * - * @param listener the listener to remove - */ - public void removeOnCameraMoveCancelListener(@NonNull OnCameraMoveCanceledListener listener) { - cameraChangeDispatcher.removeOnCameraMoveCancelListener(listener); - } - - /** - * Adds a callback that is invoked when camera movement has started. - * - * @param listener the listener to notify - */ - public void addOnCameraMoveStartedListener(@NonNull OnCameraMoveStartedListener listener) { - cameraChangeDispatcher.addOnCameraMoveStartedListener(listener); - } - - /** - * Removes a callback that is invoked when camera movement has started. - * - * @param listener the listener to remove - */ - public void removeOnCameraMoveStartedListener(@NonNull OnCameraMoveStartedListener listener) { - cameraChangeDispatcher.removeOnCameraMoveStartedListener(listener); - } - - /** - * Adds a callback that is invoked when camera position changes. - * - * @param listener the listener to notify - */ - public void addOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { - cameraChangeDispatcher.addOnCameraMoveListener(listener); - } - - /** - * Removes a callback that is invoked when camera position changes. - * - * @param listener the listener to remove - */ - public void removeOnCameraMoveListener(@NonNull OnCameraMoveListener listener) { - cameraChangeDispatcher.removeOnCameraMoveListener(listener); - } - - /** - * Sets a callback that's invoked on every frame rendered to the map view. - * - * @param listener The callback that's invoked on every frame rendered to the map view. - * To unset the callback, use null. - */ - public void setOnFpsChangedListener(@Nullable OnFpsChangedListener listener) { - onFpsChangedListener = listener; - nativeMapView.setOnFpsChangedListener(listener); - } - - // used by MapView - @Nullable - OnFpsChangedListener getOnFpsChangedListener() { - return onFpsChangedListener; - } - - /** - * Adds a callback that's invoked when the map is flinged. - * - * @param listener The callback that's invoked when the map is flinged. - */ - 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. - */ - 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 mapbox-gestures-android library - */ - public void setGesturesManager(@NonNull 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. - */ - @NonNull - public AndroidGesturesManager getGesturesManager() { - return onGesturesManagerInteractionListener.getGesturesManager(); - } - - /** - * Interrupts any ongoing gesture velocity animations. - */ - public void cancelAllVelocityAnimations() { - onGesturesManagerInteractionListener.cancelAllVelocityAnimations(); - } - - /** - * 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. - */ - 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. - */ - public void removeOnMapClickListener(@NonNull OnMapClickListener listener) { - onGesturesManagerInteractionListener.onRemoveMapClickListener(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. - */ - 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. - */ - public void removeOnMapLongClickListener(@NonNull OnMapLongClickListener listener) { - onGesturesManagerInteractionListener.onRemoveMapLongClickListener(listener); - } - - /** - * Sets a callback that's invoked when the user clicks on an info window. - * - * @param listener The callback that's invoked when the user clicks on an info window. - * To unset the callback, use null. - */ - public void setOnInfoWindowClickListener(@Nullable OnInfoWindowClickListener listener) { - annotationManager.getInfoWindowManager().setOnInfoWindowClickListener(listener); - } - - /** - * Return the InfoWindow click listener - * - * @return Current active InfoWindow Click Listener - */ - @Nullable - public OnInfoWindowClickListener getOnInfoWindowClickListener() { - return annotationManager.getInfoWindowManager().getOnInfoWindowClickListener(); - } - - /** - * Sets a callback that's invoked when a marker's info window is long pressed. - * - * @param listener The callback that's invoked when a marker's info window is long pressed. To unset the callback, - * use null. - */ - public void setOnInfoWindowLongClickListener(@Nullable OnInfoWindowLongClickListener - listener) { - annotationManager.getInfoWindowManager().setOnInfoWindowLongClickListener(listener); - } - - /** - * Return the InfoWindow long click listener - * - * @return Current active InfoWindow long Click Listener - */ - @Nullable - public OnInfoWindowLongClickListener getOnInfoWindowLongClickListener() { - return annotationManager.getInfoWindowManager().getOnInfoWindowLongClickListener(); - } - - /** - * Set an callback to be invoked when an InfoWindow closes. - * - * @param listener callback invoked when an InfoWindow closes - */ - public void setOnInfoWindowCloseListener(@Nullable OnInfoWindowCloseListener listener) { - annotationManager.getInfoWindowManager().setOnInfoWindowCloseListener(listener); - } - - /** - * Return the InfoWindow close listener - * - * @return Current active InfoWindow Close Listener - */ - @Nullable - public OnInfoWindowCloseListener getOnInfoWindowCloseListener() { - return annotationManager.getInfoWindowManager().getOnInfoWindowCloseListener(); - } - - // - // Invalidate - // - - /** - * Takes a snapshot of the map. - * - * @param callback Callback method invoked when the snapshot is taken. - */ - public void snapshot(@NonNull SnapshotReadyCallback callback) { - nativeMapView.addSnapshotCallback(callback); - } - - /** - * Queries the map for rendered features. - *

- * Returns an empty list if either the map or underlying render surface has been destroyed. - *

- * - * @param coordinates the point to query - * @param layerIds optionally - only query these layers - * @return the list of feature - */ - @NonNull - public List queryRenderedFeatures(@NonNull PointF coordinates, @Nullable String... layerIds) { - return nativeMapView.queryRenderedFeatures(coordinates, layerIds, null); - } - - /** - * Queries the map for rendered features - *

- * Returns an empty list if either the map or underlying render surface has been destroyed. - *

- * - * @param coordinates the point to query - * @param filter filters the returned features with an expression - * @param layerIds optionally - only query these layers - * @return the list of feature - */ - @NonNull - public List queryRenderedFeatures(@NonNull PointF coordinates, - @Nullable Expression filter, - @Nullable String... layerIds) { - return nativeMapView.queryRenderedFeatures(coordinates, layerIds, filter); - } - - /** - * Queries the map for rendered features - *

- * Returns an empty list if either the map or underlying render surface has been destroyed. - *

- * - * @param coordinates the box to query - * @param layerIds optionally - only query these layers - * @return the list of feature - */ - @NonNull - public List queryRenderedFeatures(@NonNull RectF coordinates, @Nullable String... layerIds) { - return nativeMapView.queryRenderedFeatures(coordinates, layerIds, null); - } - - /** - * Queries the map for rendered features - *

- * Returns an empty list if either the map or underlying render surface has been destroyed. - *

- * - * @param coordinates the box to query - * @param filter filters the returned features with an expression - * @param layerIds optionally - only query these layers - * @return the list of feature - */ - @NonNull - public List queryRenderedFeatures(@NonNull RectF coordinates, - @Nullable Expression filter, - @Nullable String... layerIds) { - return nativeMapView.queryRenderedFeatures(coordinates, layerIds, filter); - } - - // - // LocationComponent - // - - void injectLocationComponent(LocationComponent locationComponent) { - this.locationComponent = locationComponent; - } - - void injectAnnotationManager(AnnotationManager annotationManager) { - this.annotationManager = annotationManager.bind(this); - } - - /** - * Returns the {@link LocationComponent} that can be used to display user's location on the map. - *

- * Use {@link LocationComponent#activateLocationComponent(Context, Style)} or any overload to activate the component, - * then, enable it with {@link LocationComponent#setLocationComponentEnabled(boolean)}. - *

- * You can customize the location icon and more with {@link com.mapbox.mapboxsdk.location.LocationComponentOptions}. - * - * @return the Location Component - */ - @NonNull - public LocationComponent getLocationComponent() { - return locationComponent; - } - - // - // Interfaces - // - - /** - * Interface definition for a callback to be invoked when the map is flinged. - * - * @see MapboxMap#addOnFlingListener(OnFlingListener) - */ - public interface OnFlingListener { - /** - * Called when the map is flinged. - */ - void onFling(); - } - - /** - * Interface definition for a callback to be invoked when the map is moved. - * - * @see MapboxMap#addOnMoveListener(OnMoveListener) - */ - public interface OnMoveListener { - void onMoveBegin(@NonNull MoveGestureDetector detector); - - void onMove(@NonNull MoveGestureDetector detector); - - void onMoveEnd(@NonNull MoveGestureDetector detector); - } - - /** - * Interface definition for a callback to be invoked when the map is rotated. - * - * @see MapboxMap#addOnRotateListener(OnRotateListener) - */ - public interface OnRotateListener { - void onRotateBegin(@NonNull RotateGestureDetector detector); - - void onRotate(@NonNull RotateGestureDetector detector); - - void onRotateEnd(@NonNull RotateGestureDetector detector); - } - - /** - * Interface definition for a callback to be invoked when the map is scaled. - * - * @see MapboxMap#addOnScaleListener(OnScaleListener) - */ - public interface OnScaleListener { - void onScaleBegin(@NonNull StandardScaleGestureDetector detector); - - void onScale(@NonNull StandardScaleGestureDetector detector); - - void onScaleEnd(@NonNull StandardScaleGestureDetector detector); - } - - /** - * Interface definition for a callback to be invoked when the map is tilted. - * - * @see MapboxMap#addOnShoveListener(OnShoveListener) - */ - public interface OnShoveListener { - void onShoveBegin(@NonNull ShoveGestureDetector detector); - - void onShove(@NonNull ShoveGestureDetector detector); - - void onShoveEnd(@NonNull ShoveGestureDetector detector); - } - - /** - * Interface definition for a callback to be invoked for when the camera motion starts. - */ - public interface OnCameraMoveStartedListener { - int REASON_API_GESTURE = 1; - int REASON_DEVELOPER_ANIMATION = 2; - int REASON_API_ANIMATION = 3; - - /** - * Called when the camera starts moving after it has been idle or when the reason for camera motion has changed. - * - * @param reason the reason for the camera change - */ - void onCameraMoveStarted(int reason); - } - - /** - * Interface definition for a callback to be invoked for when the camera changes position. - */ - public interface OnCameraMoveListener { - /** - * Called repeatedly as the camera continues to move after an onCameraMoveStarted call. - * This may be called as often as once every frame and should not perform expensive operations. - */ - void onCameraMove(); - } - - /** - * Interface definition for a callback to be invoked for when the camera's motion has been stopped or when the camera - * starts moving for a new reason. - */ - public interface OnCameraMoveCanceledListener { - /** - * Called when the developer explicitly calls the cancelTransitions() method or if the reason for camera motion has - * changed before the onCameraIdle had a chance to fire after the previous animation. - * Do not update or animate the camera from within this method. - */ - void onCameraMoveCanceled(); - } - - /** - * Interface definition for a callback to be invoked for when camera movement has ended. - */ - public interface OnCameraIdleListener { - /** - * Called when camera movement has ended. - */ - void onCameraIdle(); - } - - /** - * Interface definition for a callback to be invoked for when the compass is animating. - */ - public interface OnCompassAnimationListener { - /** - * Called repeatedly as the compass continues to move after clicking on it. - */ - void onCompassAnimation(); - - /** - * Called when compass animation has ended. - */ - void onCompassAnimationFinished(); - } - - /** - * Interface definition for a callback to be invoked when a frame is rendered to the map view. - * - * @see MapboxMap#setOnFpsChangedListener(OnFpsChangedListener) - */ - public interface OnFpsChangedListener { - /** - * Called for every frame rendered to the map view. - * - * @param fps The average number of frames rendered over the last second. - */ - void onFpsChanged(double fps); - } - - /** - * Interface definition for a callback to be invoked when a user registers an listener that is - * related to touch and click events. - */ - interface OnGesturesManagerInteractionListener { - - void onAddMapClickListener(OnMapClickListener listener); - - void onRemoveMapClickListener(OnMapClickListener listener); - - void onAddMapLongClickListener(OnMapLongClickListener listener); - - void onRemoveMapLongClickListener(OnMapLongClickListener listener); - - 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(); - } - - /** - * Interface definition for a callback to be invoked when the user clicks on the map view. - * - * @see MapboxMap#addOnMapClickListener(OnMapClickListener) - */ - public interface OnMapClickListener { - /** - * Called when the user clicks on the map view. - * - * @param point The projected map coordinate the user clicked on. - * @return True if this click should be consumed and not passed further to other listeners registered afterwards, - * false otherwise. - */ - boolean onMapClick(@NonNull LatLng point); - } - - /** - * Interface definition for a callback to be invoked when the user long clicks on the map view. - * - * @see MapboxMap#addOnMapLongClickListener(OnMapLongClickListener) - */ - public interface OnMapLongClickListener { - /** - * Called when the user long clicks on the map view. - * - * @param point The projected map coordinate the user long clicked on. - * @return True if this click should be consumed and not passed further to other listeners registered afterwards, - * false otherwise. - */ - boolean onMapLongClick(@NonNull LatLng point); - } - - /** - * Interface definition for a callback to be invoked when the user clicks on a marker. - * - * @see MapboxMap#setOnMarkerClickListener(OnMarkerClickListener) - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public interface OnMarkerClickListener { - /** - * Called when the user clicks on a marker. - * - * @param marker The marker the user clicked on. - * @return If true the listener has consumed the event and the info window will not be shown. - */ - boolean onMarkerClick(@NonNull Marker marker); - } - - /** - * Interface definition for a callback to be invoked when the user clicks on a polygon. - * - * @see MapboxMap#setOnPolygonClickListener(OnPolygonClickListener) - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public interface OnPolygonClickListener { - /** - * Called when the user clicks on a polygon. - * - * @param polygon The polygon the user clicked on. - */ - void onPolygonClick(@NonNull Polygon polygon); - } - - /** - * Interface definition for a callback to be invoked when the user clicks on a polyline. - * - * @see MapboxMap#setOnPolylineClickListener(OnPolylineClickListener) - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public interface OnPolylineClickListener { - /** - * Called when the user clicks on a polyline. - * - * @param polyline The polyline the user clicked on. - */ - void onPolylineClick(@NonNull Polyline polyline); - } - - /** - * Interface definition for a callback to be invoked when the user clicks on an info window. - * - * @see MapboxMap#setOnInfoWindowClickListener(OnInfoWindowClickListener) - */ - public interface OnInfoWindowClickListener { - /** - * Called when the user clicks on an info window. - * - * @param marker The marker of the info window the user clicked on. - * @return If true the listener has consumed the event and the info window will not be closed. - */ - boolean onInfoWindowClick(@NonNull Marker marker); - } - - /** - * Interface definition for a callback to be invoked when the user long presses on a marker's info window. - * - * @see MapboxMap#setOnInfoWindowClickListener(OnInfoWindowClickListener) - */ - public interface OnInfoWindowLongClickListener { - - /** - * Called when the user makes a long-press gesture on the marker's info window. - * - * @param marker The marker were the info window is attached to - */ - void onInfoWindowLongClick(@NonNull Marker marker); - } - - /** - * Interface definition for a callback to be invoked when a marker's info window is closed. - * - * @see MapboxMap#setOnInfoWindowCloseListener(OnInfoWindowCloseListener) - */ - public interface OnInfoWindowCloseListener { - - /** - * Called when the marker's info window is closed. - * - * @param marker The marker of the info window that was closed. - */ - void onInfoWindowClose(@NonNull Marker marker); - } - - /** - * Interface definition for a callback to be invoked when an info window will be shown. - * - * @see MapboxMap#setInfoWindowAdapter(InfoWindowAdapter) - * @deprecated As of 7.0.0, - * use - * Mapbox Annotation Plugin instead - */ - @Deprecated - public interface InfoWindowAdapter { - /** - * Called when an info window will be shown as a result of a marker click. - * - * @param marker The marker the user clicked on. - * @return View to be shown as a info window. If null is returned the default - * info window will be shown. - */ - @Nullable - View getInfoWindow(@NonNull Marker marker); - } - - /** - * Interface definition for a callback to be invoked when a task is complete or cancelled. - */ - public interface CancelableCallback { - /** - * Invoked when a task is cancelled. - */ - void onCancel(); - - /** - * Invoked when a task is complete. - */ - void onFinish(); - } - - /** - * Interface definition for a callback to be invoked when the snapshot has been taken. - */ - public interface SnapshotReadyCallback { - /** - * Invoked when the snapshot has been taken. - * - * @param snapshot the snapshot bitmap - */ - void onSnapshotReady(@NonNull Bitmap snapshot); - } - - /** - * Internal use. - */ - public interface OnDeveloperAnimationListener { - - /** - * Notifies listener when a developer invoked animation is about to start. - */ - void onDeveloperAnimationStarted(); - } - - // - // Used for instrumentation testing - // - @NonNull - Transform getTransform() { - return transform; - } - - private void notifyDeveloperAnimationListeners() { - for (OnDeveloperAnimationListener listener : developerAnimationStartedListeners) { - listener.onDeveloperAnimationStarted(); - } - } -} 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 deleted file mode 100644 index 827756870..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MapboxMapOptions.java +++ /dev/null @@ -1,1283 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.drawable.BitmapDrawable; -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.annotation.VisibleForTesting; -import android.support.v4.content.res.ResourcesCompat; -import android.text.TextUtils; -import android.util.AttributeSet; -import android.view.Gravity; - -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.FontUtils; - -import java.util.Arrays; - -/** - * Defines configuration MapboxMapMapOptions for a MapboxMap. These options can be used when adding a - * map to your application programmatically (as opposed to via XML). If you are using a MapFragment, - * you can pass these options in using the static factory method newInstance(MapboxMapOptions). - * If you are using a MapView, you can pass these options in using the constructor - * MapView(Context, MapboxMapOptions). If you add a map using XML, then you can apply these options - * using custom XML tags. - */ -public class MapboxMapOptions implements Parcelable { - - private static final int LIGHT_GRAY = 0xFFF0E9E1; // RGB(240, 233, 225)) - private static final float FOUR_DP = 4f; - private static final float NINETY_TWO_DP = 92f; - private static final int UNDEFINED_COLOR = -1; - - private CameraPosition cameraPosition; - - private boolean debugActive; - - private boolean compassEnabled = true; - private boolean fadeCompassFacingNorth = true; - private int compassGravity = Gravity.TOP | Gravity.END; - private int[] compassMargins; - private Drawable compassImage; - - private boolean logoEnabled = true; - private int logoGravity = Gravity.BOTTOM | Gravity.START; - private int[] logoMargins; - - @ColorInt - private int attributionTintColor = UNDEFINED_COLOR; - private boolean attributionEnabled = true; - private int attributionGravity = Gravity.BOTTOM | Gravity.START; - private int[] attributionMargins; - - private double minZoom = MapboxConstants.MINIMUM_ZOOM; - private double maxZoom = MapboxConstants.MAXIMUM_ZOOM; - - private boolean rotateGesturesEnabled = true; - private boolean scrollGesturesEnabled = true; - private boolean tiltGesturesEnabled = true; - private boolean zoomGesturesEnabled = true; - private boolean doubleTapGesturesEnabled = true; - private boolean quickZoomGesturesEnabled = true; - - private boolean prefetchesTiles = true; - private int prefetchZoomDelta = 4; - private boolean zMediaOverlay = false; - - private boolean localIdeographFontFamilyEnabled = true; - private String localIdeographFontFamily; - private String[] localIdeographFontFamilies; - - private String apiBaseUri; - - private boolean textureMode; - private boolean translucentTextureSurface; - - @ColorInt - private int foregroundLoadColor; - - private float pixelRatio; - - private boolean crossSourceCollisions = true; - - /** - * Creates a new MapboxMapOptions object. - * - * @deprecated Use {@link #createFromAttributes(Context, AttributeSet)} instead. - */ - @Deprecated - public MapboxMapOptions() { - } - - private MapboxMapOptions(Parcel in) { - cameraPosition = in.readParcelable(CameraPosition.class.getClassLoader()); - debugActive = in.readByte() != 0; - - compassEnabled = in.readByte() != 0; - compassGravity = in.readInt(); - compassMargins = in.createIntArray(); - fadeCompassFacingNorth = in.readByte() != 0; - - Bitmap compassBitmap = in.readParcelable(getClass().getClassLoader()); - if (compassBitmap != null) { - compassImage = new BitmapDrawable(compassBitmap); - } - - logoEnabled = in.readByte() != 0; - logoGravity = in.readInt(); - logoMargins = in.createIntArray(); - - attributionEnabled = in.readByte() != 0; - attributionGravity = in.readInt(); - attributionMargins = in.createIntArray(); - attributionTintColor = in.readInt(); - - minZoom = in.readDouble(); - maxZoom = in.readDouble(); - - rotateGesturesEnabled = in.readByte() != 0; - scrollGesturesEnabled = in.readByte() != 0; - tiltGesturesEnabled = in.readByte() != 0; - zoomGesturesEnabled = in.readByte() != 0; - doubleTapGesturesEnabled = in.readByte() != 0; - quickZoomGesturesEnabled = in.readByte() != 0; - - apiBaseUri = in.readString(); - textureMode = in.readByte() != 0; - translucentTextureSurface = in.readByte() != 0; - prefetchesTiles = in.readByte() != 0; - prefetchZoomDelta = in.readInt(); - zMediaOverlay = in.readByte() != 0; - localIdeographFontFamilyEnabled = in.readByte() != 0; - localIdeographFontFamily = in.readString(); - localIdeographFontFamilies = in.createStringArray(); - pixelRatio = in.readFloat(); - foregroundLoadColor = in.readInt(); - crossSourceCollisions = in.readByte() != 0; - } - - /** - * Creates a default MapboxMapsOptions from a given context. - * - * @param context Context related to a map view. - * @return the MapboxMapOptions created from attributes - */ - @NonNull - public static MapboxMapOptions createFromAttributes(@NonNull Context context) { - return createFromAttributes(context, null); - } - - /** - * Creates a MapboxMapsOptions from the attribute set. - * - * @param context Context related to a map view. - * @param attrs Attributeset containing configuration - * @return the MapboxMapOptions created from attributes - */ - @NonNull - public static MapboxMapOptions createFromAttributes(@NonNull Context context, @Nullable AttributeSet attrs) { - TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.mapbox_MapView, 0, 0); - return createFromAttributes(new MapboxMapOptions(), context, typedArray); - } - - @VisibleForTesting - static MapboxMapOptions createFromAttributes(@NonNull MapboxMapOptions mapboxMapOptions, - @NonNull Context context, - @Nullable TypedArray typedArray) { - float pxlRatio = context.getResources().getDisplayMetrics().density; - try { - mapboxMapOptions.camera(new CameraPosition.Builder(typedArray).build()); - - // deprecated - mapboxMapOptions.apiBaseUrl(typedArray.getString(R.styleable.mapbox_MapView_mapbox_apiBaseUrl)); - - String baseUri = typedArray.getString(R.styleable.mapbox_MapView_mapbox_apiBaseUri); - if (!TextUtils.isEmpty(baseUri)) { - // override deprecated property if a value of the new type was provided - mapboxMapOptions.apiBaseUri(baseUri); - } - - mapboxMapOptions.zoomGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiZoomGestures, true)); - mapboxMapOptions.scrollGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiScrollGestures, true)); - mapboxMapOptions.rotateGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiRotateGestures, true)); - mapboxMapOptions.tiltGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiTiltGestures, true)); - mapboxMapOptions.doubleTapGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiDoubleTapGestures, true)); - mapboxMapOptions.quickZoomGesturesEnabled( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiQuickZoomGestures, true)); - - mapboxMapOptions.maxZoomPreference(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraZoomMax, - MapboxConstants.MAXIMUM_ZOOM)); - mapboxMapOptions.minZoomPreference(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraZoomMin, - MapboxConstants.MINIMUM_ZOOM)); - - mapboxMapOptions.compassEnabled(typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiCompass, true)); - mapboxMapOptions.compassGravity(typedArray.getInt(R.styleable.mapbox_MapView_mapbox_uiCompassGravity, - Gravity.TOP | Gravity.END)); - mapboxMapOptions.compassMargins(new int[] { - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiCompassMarginLeft, - FOUR_DP * pxlRatio)), - ((int) typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiCompassMarginTop, - FOUR_DP * pxlRatio)), - ((int) typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiCompassMarginRight, - FOUR_DP * pxlRatio)), - ((int) typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiCompassMarginBottom, - FOUR_DP * pxlRatio))}); - mapboxMapOptions.compassFadesWhenFacingNorth(typedArray.getBoolean( - R.styleable.mapbox_MapView_mapbox_uiCompassFadeFacingNorth, true)); - Drawable compassDrawable = typedArray.getDrawable( - R.styleable.mapbox_MapView_mapbox_uiCompassDrawable); - if (compassDrawable == null) { - compassDrawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.mapbox_compass_icon, null); - } - mapboxMapOptions.compassImage(compassDrawable); - - mapboxMapOptions.logoEnabled(typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_uiLogo, true)); - mapboxMapOptions.logoGravity(typedArray.getInt(R.styleable.mapbox_MapView_mapbox_uiLogoGravity, - Gravity.BOTTOM | Gravity.START)); - mapboxMapOptions.logoMargins(new int[] { - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiLogoMarginLeft, - FOUR_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiLogoMarginTop, - FOUR_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiLogoMarginRight, - FOUR_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiLogoMarginBottom, - FOUR_DP * pxlRatio))}); - - mapboxMapOptions.attributionTintColor(typedArray.getColor( - R.styleable.mapbox_MapView_mapbox_uiAttributionTintColor, UNDEFINED_COLOR)); - mapboxMapOptions.attributionEnabled(typedArray.getBoolean( - R.styleable.mapbox_MapView_mapbox_uiAttribution, true)); - mapboxMapOptions.attributionGravity(typedArray.getInt( - R.styleable.mapbox_MapView_mapbox_uiAttributionGravity, Gravity.BOTTOM | Gravity.START)); - mapboxMapOptions.attributionMargins(new int[] { - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiAttributionMarginLeft, - NINETY_TWO_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiAttributionMarginTop, - FOUR_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiAttributionMarginRight, - FOUR_DP * pxlRatio)), - (int) (typedArray.getDimension(R.styleable.mapbox_MapView_mapbox_uiAttributionMarginBottom, - FOUR_DP * pxlRatio))}); - 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.setPrefetchZoomDelta( - typedArray.getInt(R.styleable.mapbox_MapView_mapbox_prefetchZoomDelta, 4)); - mapboxMapOptions.renderSurfaceOnTop( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_enableZMediaOverlay, false)); - - mapboxMapOptions.localIdeographFontFamilyEnabled = - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_localIdeographEnabled, true); - - int localIdeographFontFamiliesResId = - typedArray.getResourceId(R.styleable.mapbox_MapView_mapbox_localIdeographFontFamilies, 0); - if (localIdeographFontFamiliesResId != 0) { - String[] localIdeographFontFamilies = - context.getResources().getStringArray(localIdeographFontFamiliesResId); - mapboxMapOptions.localIdeographFontFamily(localIdeographFontFamilies); - } else { - // did user provide xml font string? - String localIdeographFontFamily = - typedArray.getString(R.styleable.mapbox_MapView_mapbox_localIdeographFontFamily); - if (localIdeographFontFamily == null) { - localIdeographFontFamily = MapboxConstants.DEFAULT_FONT; - } - mapboxMapOptions.localIdeographFontFamily(localIdeographFontFamily); - } - - mapboxMapOptions.pixelRatio( - typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_pixelRatio, 0)); - mapboxMapOptions.foregroundLoadColor( - typedArray.getInt(R.styleable.mapbox_MapView_mapbox_foregroundLoadColor, LIGHT_GRAY) - ); - mapboxMapOptions.crossSourceCollisions( - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_cross_source_collisions, true) - ); - } finally { - typedArray.recycle(); - } - return mapboxMapOptions; - } - - /** - * Specifies the URL used for API endpoint. - * - * @param apiBaseUrl The base of our API endpoint - * @return This - * @deprecated use {@link #apiBaseUri} instead - */ - @Deprecated - @NonNull - public MapboxMapOptions apiBaseUrl(String apiBaseUrl) { - this.apiBaseUri = apiBaseUrl; - return this; - } - - /** - * Specifies the URI used for API endpoint. - * - * @param apiBaseUri The base of our API endpoint - * @return This - */ - @NonNull - public MapboxMapOptions apiBaseUri(String apiBaseUri) { - this.apiBaseUri = apiBaseUri; - return this; - } - - /** - * Specifies a the initial camera position for the map view. - * - * @param cameraPosition Inital camera position - * @return This - */ - @NonNull - public MapboxMapOptions camera(CameraPosition cameraPosition) { - this.cameraPosition = cameraPosition; - return this; - } - - /** - * Specifies the used debug type for a map view. - * - * @param enabled True is debug is enabled - * @return This - */ - @NonNull - public MapboxMapOptions debugActive(boolean enabled) { - debugActive = enabled; - return this; - } - - /** - * Specifies the used minimum zoom level for a map view. - * - * @param minZoom Zoom level to be used - * @return This - */ - @NonNull - public MapboxMapOptions minZoomPreference(double minZoom) { - this.minZoom = minZoom; - return this; - } - - /** - * Specifies the used maximum zoom level for a map view. - * - * @param maxZoom Zoom level to be used - * @return This - */ - @NonNull - public MapboxMapOptions maxZoomPreference(double maxZoom) { - this.maxZoom = maxZoom; - return this; - } - - /** - * Specifies the visibility state of a mapbox_compass_icon for a map view. - * - * @param enabled True and mapbox_compass_icon is shown - * @return This - */ - @NonNull - public MapboxMapOptions compassEnabled(boolean enabled) { - compassEnabled = enabled; - return this; - } - - /** - * Specifies the gravity state of mapbox_compass_icon for a map view. - * - * @param gravity Android SDK Gravity. - * @return This - */ - @NonNull - public MapboxMapOptions compassGravity(int gravity) { - compassGravity = gravity; - return this; - } - - /** - * Specifies the margin state of mapbox_compass_icon for a map view - * - * @param margins 4 long array for LTRB margins - * @return This - */ - @NonNull - public MapboxMapOptions compassMargins(int[] margins) { - compassMargins = margins; - return this; - } - - /** - * Specifies if the mapbox_compass_icon fades to invisible when facing north. - *

- * By default this value is true. - *

- * - * @param compassFadeWhenFacingNorth true is mapbox_compass_icon fades to invisble - * @return This - */ - @NonNull - public MapboxMapOptions compassFadesWhenFacingNorth(boolean compassFadeWhenFacingNorth) { - this.fadeCompassFacingNorth = compassFadeWhenFacingNorth; - return this; - } - - /** - * Specifies the image of the CompassView. - *

- * By default this value is R.drawable.mapbox_compass_icon. - *

- * - * @param compass the drawable to show as image compass - * @return This - */ - @NonNull - public MapboxMapOptions compassImage(Drawable compass) { - this.compassImage = compass; - return this; - } - - /** - * Specifies the visibility state of a logo for a map view. - * - * @param enabled True and logo is shown - * @return This - */ - @NonNull - public MapboxMapOptions logoEnabled(boolean enabled) { - logoEnabled = enabled; - return this; - } - - /** - * Specifies the gravity state of logo for a map view. - * - * @param gravity Android SDK Gravity. - * @return This - */ - @NonNull - public MapboxMapOptions logoGravity(int gravity) { - logoGravity = gravity; - return this; - } - - /** - * Specifies the margin state of logo for a map view - * - * @param margins 4 long array for LTRB margins - * @return This - */ - @NonNull - public MapboxMapOptions logoMargins(int[] margins) { - logoMargins = margins; - return this; - } - - /** - * Specifies the visibility state of a attribution for a map view. - * - * @param enabled True and attribution is shown - * @return This - */ - @NonNull - public MapboxMapOptions attributionEnabled(boolean enabled) { - attributionEnabled = enabled; - return this; - } - - /** - * Specifies the gravity state of attribution for a map view. - * - * @param gravity Android SDK Gravity. - * @return This - */ - @NonNull - public MapboxMapOptions attributionGravity(int gravity) { - attributionGravity = gravity; - return this; - } - - /** - * Specifies the margin state of attribution for a map view - * - * @param margins 4 long array for LTRB margins - * @return This - */ - @NonNull - public MapboxMapOptions attributionMargins(int[] margins) { - attributionMargins = margins; - return this; - } - - /** - * Specifies the tint color of the attribution for a map view - * - * @param color integer resembling a color - * @return This - */ - @NonNull - public MapboxMapOptions attributionTintColor(@ColorInt int color) { - attributionTintColor = color; - return this; - } - - /** - * Specifies if the rotate gesture is enabled for a map view. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions rotateGesturesEnabled(boolean enabled) { - rotateGesturesEnabled = enabled; - return this; - } - - /** - * Specifies if the scroll gesture is enabled for a map view. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions scrollGesturesEnabled(boolean enabled) { - scrollGesturesEnabled = enabled; - return this; - } - - /** - * Specifies if the tilt gesture is enabled for a map view. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions tiltGesturesEnabled(boolean enabled) { - tiltGesturesEnabled = enabled; - return this; - } - - /** - * Specifies if the zoom gesture is enabled for a map view. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions zoomGesturesEnabled(boolean enabled) { - zoomGesturesEnabled = enabled; - return this; - } - - /** - * Specifies if the double tap gesture is enabled for a map view. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions doubleTapGesturesEnabled(boolean enabled) { - doubleTapGesturesEnabled = enabled; - return this; - } - - /** - * Specifies whether the user may zoom the map by tapping twice, holding and moving the pointer up and down. - * - * @param enabled True and gesture will be enabled - * @return This - */ - @NonNull - public MapboxMapOptions quickZoomGesturesEnabled(boolean enabled) { - quickZoomGesturesEnabled = enabled; - return this; - } - - /** - * Enable {@link android.view.TextureView} as rendered surface. - *

- * Since the 5.2.0 release we replaced our TextureView with an {@link android.opengl.GLSurfaceView} - * implementation. Enabling this option will use the {@link android.view.TextureView} instead. - * {@link android.view.TextureView} can be useful in situations where you need to animate, scale - * or transform the view. This comes at a siginficant performance penalty and should not be considered - * unless absolutely needed. - *

- * - * @param textureMode True to enable texture mode - * @return This - */ - @NonNull - public MapboxMapOptions textureMode(boolean textureMode) { - this.textureMode = textureMode; - return this; - } - - @NonNull - public MapboxMapOptions translucentTextureSurface(boolean translucentTextureSurface) { - this.translucentTextureSurface = translucentTextureSurface; - return this; - } - - /** - * Set the MapView foreground color that is used when the map surface is being created. - * - * @param loadColor the color to show during map creation - * @return This - */ - @NonNull - public MapboxMapOptions foregroundLoadColor(@ColorInt int loadColor) { - this.foregroundLoadColor = loadColor; - 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. - * Enabled by default - * - * @param enable true to enable - * @return This - * @deprecated Use {@link #setPrefetchZoomDelta(int)} instead. - */ - @Deprecated - @NonNull - public MapboxMapOptions setPrefetchesTiles(boolean enable) { - this.prefetchesTiles = enable; - return this; - } - - /** - * Set the tile pre-fetching zoom delta. Pre-fetching makes sure that a low-resolution - * tile at the (current_zoom_level - delta) is rendered as soon as possible at the - * expense of a little bandwidth. - * Note: This operation will override the MapboxMapOptions#setPrefetchesTiles(boolean) - * Setting zoom delta to 0 will disable pre-fetching. - * Default zoom delta is 4. - * - * @param delta zoom delta - * @return This - */ - @NonNull - public MapboxMapOptions setPrefetchZoomDelta(@IntRange(from = 0) int delta) { - this.prefetchZoomDelta = delta; - return this; - } - - /** - * Enable cross-source symbol collision detection, defaults to true. - *

- * If set to false, symbol layers will only run collision detection against - * other symbol layers that are part of the same source. - *

- * - * @param crossSourceCollisions true to enable, false to disable - * @return This - */ - @NonNull - public MapboxMapOptions crossSourceCollisions(boolean crossSourceCollisions) { - this.crossSourceCollisions = crossSourceCollisions; - return this; - } - - /** - * Enable local ideograph font family, defaults to true. - * - * @param enabled true to enable, false to disable - * @return This - */ - @NonNull - public MapboxMapOptions localIdeographFontFamilyEnabled(boolean enabled) { - this.localIdeographFontFamilyEnabled = enabled; - return this; - } - - /** - * Set the font family for generating glyphs locally for ideographs in the 'CJK Unified Ideographs' - * and 'Hangul Syllables' ranges. - *

- * The font family argument is passed to {@link android.graphics.Typeface#create(String, int)}. - * Default system fonts are defined in '/system/etc/fonts.xml' - * Default font for local ideograph font family is {@link MapboxConstants#DEFAULT_FONT}. - * - * @param fontFamily font family for local ideograph generation. - * @return This - */ - @NonNull - public MapboxMapOptions localIdeographFontFamily(String fontFamily) { - this.localIdeographFontFamily = FontUtils.extractValidFont(fontFamily); - return this; - } - - /** - * Set a font family from range of font families for generating glyphs locally for ideographs in the - * 'CJK Unified Ideographs' and 'Hangul Syllables' ranges. The first matching font - * will be selected. If no valid font found, it defaults to {@link MapboxConstants#DEFAULT_FONT}. - *

- * The font families are checked against the default system fonts defined in - * '/system/etc/fonts.xml' Default font for local ideograph font family is - * {@link MapboxConstants#DEFAULT_FONT}. - *

- * - * @param fontFamilies an array of font families for local ideograph generation. - * @return This - */ - @NonNull - public MapboxMapOptions localIdeographFontFamily(String... fontFamilies) { - this.localIdeographFontFamily = FontUtils.extractValidFont(fontFamilies); - return this; - } - - /** - * Set the custom pixel ratio configuration to override the default value from resources. - * This ratio will be used to initialise the map with. - * - * @param pixelRatio the custom pixel ratio of the map under construction - * @return This - */ - @NonNull - public MapboxMapOptions pixelRatio(float pixelRatio) { - this.pixelRatio = pixelRatio; - return this; - } - - /** - * Check whether tile pre-fetching is enabled. - * - * @return true if enabled - * @deprecated Use {@link #getPrefetchZoomDelta()} instead. - */ - @Deprecated - public boolean getPrefetchesTiles() { - return prefetchesTiles; - } - - /** - * Check current pre-fetching zoom delta. - * - * @return current zoom delta. - */ - @IntRange(from = 0) - public int getPrefetchZoomDelta() { - return prefetchZoomDelta; - } - - /** - * Check whether cross-source symbol collision detection is enabled. - * - * @return true if enabled - */ - public boolean getCrossSourceCollisions() { - return crossSourceCollisions; - } - - /** - * Set the flag to render the map surface on top of another surface. - * - * @param renderOnTop true if this map is shown on top of another one, false if bottom. - */ - public void renderSurfaceOnTop(boolean renderOnTop) { - this.zMediaOverlay = renderOnTop; - } - - /** - * Get the flag to render the map surface on top of another surface. - * - * @return true if this map is - */ - public boolean getRenderSurfaceOnTop() { - return zMediaOverlay; - } - - /** - * Get the current configured API endpoint base URL. - * - * @return Base URL to be used API endpoint. - * @deprecated use {@link #getApiBaseUri()} instead - */ - @Deprecated - public String getApiBaseUrl() { - return apiBaseUri; - } - - /** - * Get the current configured API endpoint base URI. - * - * @return Base URI to be used API endpoint. - */ - public String getApiBaseUri() { - return apiBaseUri; - } - - /** - * Get the current configured initial camera position for a map view. - * - * @return CameraPosition to be initially used. - */ - public CameraPosition getCamera() { - return cameraPosition; - } - - /** - * Get the current configured min zoom for a map view. - * - * @return Mininum zoom level to be used. - */ - public double getMinZoomPreference() { - return minZoom; - } - - /** - * Get the current configured maximum zoom for a map view. - * - * @return Maximum zoom to be used. - */ - public double getMaxZoomPreference() { - return maxZoom; - } - - /** - * Get the current configured visibility state for mapbox_compass_icon for a map view. - * - * @return Visibility state of the mapbox_compass_icon - */ - public boolean getCompassEnabled() { - return compassEnabled; - } - - /** - * Get the current configured gravity state for mapbox_compass_icon for a map view. - * - * @return Gravity state of the mapbox_compass_icon - */ - public int getCompassGravity() { - return compassGravity; - } - - /** - * Get the current configured margins for mapbox_compass_icon for a map view. - * - * @return Margins state of the mapbox_compass_icon - */ - public int[] getCompassMargins() { - return compassMargins; - } - - /** - * Get the current configured state for fading the mapbox_compass_icon when facing north. - * - * @return True if mapbox_compass_icon fades to invisible when facing north - */ - public boolean getCompassFadeFacingNorth() { - return fadeCompassFacingNorth; - } - - /** - * Get the current configured CompassView image. - * - * @return the drawable used as compass image - */ - public Drawable getCompassImage() { - return compassImage; - } - - /** - * Get the current configured visibility state for mapbox_compass_icon for a map view. - * - * @return Visibility state of the mapbox_compass_icon - */ - public boolean getLogoEnabled() { - return logoEnabled; - } - - /** - * Get the current configured gravity state for logo for a map view. - * - * @return Gravity state of the logo - */ - public int getLogoGravity() { - return logoGravity; - } - - /** - * Get the current configured margins for logo for a map view. - * - * @return Margins state of the logo - */ - public int[] getLogoMargins() { - return logoMargins; - } - - /** - * Get the current configured rotate gesture state for a map view. - * - * @return True indicates gesture is enabled - */ - public boolean getRotateGesturesEnabled() { - return rotateGesturesEnabled; - } - - /** - * Get the current configured scroll gesture state for a map view. - * - * @return True indicates gesture is enabled - */ - public boolean getScrollGesturesEnabled() { - return scrollGesturesEnabled; - } - - /** - * Get the current configured tilt gesture state for a map view. - * - * @return True indicates gesture is enabled - */ - public boolean getTiltGesturesEnabled() { - return tiltGesturesEnabled; - } - - /** - * Get the current configured zoom gesture state for a map view. - * - * @return True indicates gesture is enabled - */ - public boolean getZoomGesturesEnabled() { - return zoomGesturesEnabled; - } - - /** - * Get the current configured double tap gesture state for a map view. - * - * @return True indicates gesture is enabled - */ - public boolean getDoubleTapGesturesEnabled() { - return doubleTapGesturesEnabled; - } - - /** - * Get whether the user may zoom the map by tapping twice, holding and moving the pointer up and down. - * - * @return True indicates gesture is enabled - */ - public boolean getQuickZoomGesturesEnabled() { - return quickZoomGesturesEnabled; - } - - /** - * Get the current configured visibility state for attribution for a map view. - * - * @return Visibility state of the attribution - */ - public boolean getAttributionEnabled() { - return attributionEnabled; - } - - /** - * Get the current configured gravity state for attribution for a map view. - * - * @return Gravity state of the logo - */ - public int getAttributionGravity() { - return attributionGravity; - } - - /** - * Get the current configured margins for attribution for a map view. - * - * @return Margins state of the logo - */ - public int[] getAttributionMargins() { - return attributionMargins; - } - - /** - * Get the current configured tint color for attribution for a map view. - * - * @return the tint color - */ - @ColorInt - public int getAttributionTintColor() { - return attributionTintColor; - } - - /** - * Get the current configured debug state for a map view. - * - * @return True indicates debug is enabled. - */ - public boolean getDebugActive() { - return debugActive; - } - - /** - * Returns true if TextureView is being used the render view. - * - * @return True if TextureView is used. - */ - public boolean getTextureMode() { - return textureMode; - } - - /** - * Returns true if TextureView supports a translucent surface - * - * @return True if translucent surface is active - */ - public boolean getTranslucentTextureSurface() { - return translucentTextureSurface; - } - - /** - * Returns the current configured foreground color that is used during map creation. - * - * @return the load color - */ - @ColorInt - public int getForegroundLoadColor() { - return foregroundLoadColor; - } - - /** - * Returns the font-family for locally overriding generation of glyphs in the - * 'CJK Unified Ideographs' and 'Hangul Syllables' ranges. - * Default font for local ideograph font family is {@link MapboxConstants#DEFAULT_FONT}. - * Returns null if local ideograph font families are disabled. - * - * @return Local ideograph font family name. - */ - @Nullable - public String getLocalIdeographFontFamily() { - return localIdeographFontFamilyEnabled ? localIdeographFontFamily : null; - } - - /** - * Returns true if local ideograph font family is enabled, defaults to true. - * - * @return True if local ideograph font family is enabled - */ - public boolean isLocalIdeographFontFamilyEnabled() { - return localIdeographFontFamilyEnabled; - } - - /** - * Return the custom configured pixel ratio, returns 0 if not configured. - * - * @return the pixel ratio used by the map under construction - */ - public float getPixelRatio() { - return pixelRatio; - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - public MapboxMapOptions createFromParcel(@NonNull Parcel in) { - return new MapboxMapOptions(in); - } - - public MapboxMapOptions[] newArray(int size) { - return new MapboxMapOptions[size]; - } - }; - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(@NonNull Parcel dest, int flags) { - dest.writeParcelable(cameraPosition, flags); - dest.writeByte((byte) (debugActive ? 1 : 0)); - - dest.writeByte((byte) (compassEnabled ? 1 : 0)); - dest.writeInt(compassGravity); - dest.writeIntArray(compassMargins); - dest.writeByte((byte) (fadeCompassFacingNorth ? 1 : 0)); - dest.writeParcelable(compassImage != null - ? BitmapUtils.getBitmapFromDrawable(compassImage) : null, flags); - - dest.writeByte((byte) (logoEnabled ? 1 : 0)); - dest.writeInt(logoGravity); - dest.writeIntArray(logoMargins); - - dest.writeByte((byte) (attributionEnabled ? 1 : 0)); - dest.writeInt(attributionGravity); - dest.writeIntArray(attributionMargins); - dest.writeInt(attributionTintColor); - - dest.writeDouble(minZoom); - dest.writeDouble(maxZoom); - - dest.writeByte((byte) (rotateGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (scrollGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (tiltGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (zoomGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (doubleTapGesturesEnabled ? 1 : 0)); - dest.writeByte((byte) (quickZoomGesturesEnabled ? 1 : 0)); - - dest.writeString(apiBaseUri); - dest.writeByte((byte) (textureMode ? 1 : 0)); - dest.writeByte((byte) (translucentTextureSurface ? 1 : 0)); - dest.writeByte((byte) (prefetchesTiles ? 1 : 0)); - dest.writeInt(prefetchZoomDelta); - dest.writeByte((byte) (zMediaOverlay ? 1 : 0)); - dest.writeByte((byte) (localIdeographFontFamilyEnabled ? 1 : 0)); - dest.writeString(localIdeographFontFamily); - dest.writeStringArray(localIdeographFontFamilies); - dest.writeFloat(pixelRatio); - dest.writeInt(foregroundLoadColor); - dest.writeByte((byte) (crossSourceCollisions ? 1 : 0)); - } - - @Override - public boolean equals(@Nullable Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - MapboxMapOptions options = (MapboxMapOptions) o; - - if (debugActive != options.debugActive) { - return false; - } - if (compassEnabled != options.compassEnabled) { - return false; - } - if (fadeCompassFacingNorth != options.fadeCompassFacingNorth) { - return false; - } - if (compassImage != null - ? !compassImage.equals(options.compassImage) - : options.compassImage != null) { - return false; - } - if (compassGravity != options.compassGravity) { - return false; - } - if (logoEnabled != options.logoEnabled) { - return false; - } - if (logoGravity != options.logoGravity) { - return false; - } - if (attributionTintColor != options.attributionTintColor) { - return false; - } - if (attributionEnabled != options.attributionEnabled) { - return false; - } - if (attributionGravity != options.attributionGravity) { - return false; - } - if (Double.compare(options.minZoom, minZoom) != 0) { - return false; - } - if (Double.compare(options.maxZoom, maxZoom) != 0) { - return false; - } - if (rotateGesturesEnabled != options.rotateGesturesEnabled) { - return false; - } - if (scrollGesturesEnabled != options.scrollGesturesEnabled) { - return false; - } - if (tiltGesturesEnabled != options.tiltGesturesEnabled) { - return false; - } - if (zoomGesturesEnabled != options.zoomGesturesEnabled) { - return false; - } - if (doubleTapGesturesEnabled != options.doubleTapGesturesEnabled) { - return false; - } - if (quickZoomGesturesEnabled != options.quickZoomGesturesEnabled) { - return false; - } - if (cameraPosition != null ? !cameraPosition.equals(options.cameraPosition) : options.cameraPosition != null) { - return false; - } - if (!Arrays.equals(compassMargins, options.compassMargins)) { - return false; - } - if (!Arrays.equals(logoMargins, options.logoMargins)) { - return false; - } - if (!Arrays.equals(attributionMargins, options.attributionMargins)) { - return false; - } - if (apiBaseUri != null ? !apiBaseUri.equals(options.apiBaseUri) : options.apiBaseUri != null) { - return false; - } - if (prefetchesTiles != options.prefetchesTiles) { - return false; - } - if (prefetchZoomDelta != options.prefetchZoomDelta) { - return false; - } - if (zMediaOverlay != options.zMediaOverlay) { - return false; - } - if (localIdeographFontFamilyEnabled != options.localIdeographFontFamilyEnabled) { - return false; - } - if (!localIdeographFontFamily.equals(options.localIdeographFontFamily)) { - return false; - } - if (!Arrays.equals(localIdeographFontFamilies, options.localIdeographFontFamilies)) { - return false; - } - - if (pixelRatio != options.pixelRatio) { - return false; - } - - if (crossSourceCollisions != options.crossSourceCollisions) { - return false; - } - - return false; - } - - @Override - public int hashCode() { - int result; - long temp; - result = cameraPosition != null ? cameraPosition.hashCode() : 0; - result = 31 * result + (debugActive ? 1 : 0); - result = 31 * result + (compassEnabled ? 1 : 0); - result = 31 * result + (fadeCompassFacingNorth ? 1 : 0); - result = 31 * result + compassGravity; - result = 31 * result + (compassImage != null ? compassImage.hashCode() : 0); - result = 31 * result + Arrays.hashCode(compassMargins); - result = 31 * result + (logoEnabled ? 1 : 0); - result = 31 * result + logoGravity; - result = 31 * result + Arrays.hashCode(logoMargins); - result = 31 * result + attributionTintColor; - result = 31 * result + (attributionEnabled ? 1 : 0); - result = 31 * result + attributionGravity; - result = 31 * result + Arrays.hashCode(attributionMargins); - temp = Double.doubleToLongBits(minZoom); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(maxZoom); - result = 31 * result + (int) (temp ^ (temp >>> 32)); - result = 31 * result + (rotateGesturesEnabled ? 1 : 0); - result = 31 * result + (scrollGesturesEnabled ? 1 : 0); - result = 31 * result + (tiltGesturesEnabled ? 1 : 0); - result = 31 * result + (zoomGesturesEnabled ? 1 : 0); - result = 31 * result + (doubleTapGesturesEnabled ? 1 : 0); - result = 31 * result + (quickZoomGesturesEnabled ? 1 : 0); - result = 31 * result + (apiBaseUri != null ? apiBaseUri.hashCode() : 0); - result = 31 * result + (textureMode ? 1 : 0); - result = 31 * result + (translucentTextureSurface ? 1 : 0); - result = 31 * result + (prefetchesTiles ? 1 : 0); - result = 31 * result + prefetchZoomDelta; - result = 31 * result + (zMediaOverlay ? 1 : 0); - result = 31 * result + (localIdeographFontFamilyEnabled ? 1 : 0); - result = 31 * result + (localIdeographFontFamily != null ? localIdeographFontFamily.hashCode() : 0); - result = 31 * result + Arrays.hashCode(localIdeographFontFamilies); - result = 31 * result + (int) pixelRatio; - result = 31 * result + (crossSourceCollisions ? 1 : 0); - return result; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MarkerContainer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MarkerContainer.java deleted file mode 100644 index b408d9f5c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/MarkerContainer.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.RectF; -import android.support.annotation.NonNull; -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Icon; -import com.mapbox.mapboxsdk.annotations.Marker; - -import java.util.ArrayList; -import java.util.List; - -/** - * Encapsulates {@link Marker}'s functionality. - */ -class MarkerContainer implements Markers { - - private final NativeMap nativeMapView; - private final LongSparseArray annotations; - private final IconManager iconManager; - - MarkerContainer(NativeMap nativeMapView, LongSparseArray annotations, IconManager iconManager) { - this.nativeMapView = nativeMapView; - this.annotations = annotations; - this.iconManager = iconManager; - } - - @Override - public Marker addBy(@NonNull BaseMarkerOptions markerOptions, @NonNull MapboxMap mapboxMap) { - Marker marker = prepareMarker(markerOptions); - long id = nativeMapView != null ? nativeMapView.addMarker(marker) : 0; - marker.setMapboxMap(mapboxMap); - marker.setId(id); - annotations.put(id, marker); - return marker; - } - - @NonNull - @Override - public List addBy(@NonNull List markerOptionsList, @NonNull MapboxMap - mapboxMap) { - int count = markerOptionsList.size(); - List markers = new ArrayList<>(count); - if (nativeMapView != null && count > 0) { - BaseMarkerOptions markerOptions; - Marker marker; - for (int i = 0; i < count; i++) { - markerOptions = markerOptionsList.get(i); - marker = prepareMarker(markerOptions); - markers.add(marker); - } - - if (markers.size() > 0) { - long[] ids = nativeMapView.addMarkers(markers); - for (int i = 0; i < ids.length; i++) { - Marker createdMarker = markers.get(i); - createdMarker.setMapboxMap(mapboxMap); - createdMarker.setId(ids[i]); - annotations.put(ids[i], createdMarker); - } - } - } - return markers; - } - - @Override - public void update(@NonNull Marker updatedMarker, @NonNull MapboxMap mapboxMap) { - ensureIconLoaded(updatedMarker, mapboxMap); - nativeMapView.updateMarker(updatedMarker); - annotations.setValueAt(annotations.indexOfKey(updatedMarker.getId()), updatedMarker); - } - - @NonNull - @Override - public List obtainAll() { - List markers = new ArrayList<>(); - Annotation annotation; - for (int i = 0; i < annotations.size(); i++) { - annotation = annotations.get(annotations.keyAt(i)); - if (annotation instanceof Marker) { - markers.add((Marker) annotation); - } - } - return markers; - } - - @NonNull - @Override - public List obtainAllIn(@NonNull RectF rectangle) { - RectF rect = nativeMapView.getDensityDependantRectangle(rectangle); - long[] ids = nativeMapView.queryPointAnnotations(rect); - List idsList = new ArrayList<>(ids.length); - for (long id : ids) { - idsList.add(id); - } - - List annotations = new ArrayList<>(ids.length); - List annotationList = obtainAnnotations(); - int count = annotationList.size(); - for (int i = 0; i < count; i++) { - Annotation annotation = annotationList.get(i); - if (annotation instanceof com.mapbox.mapboxsdk.annotations.Marker && idsList.contains(annotation.getId())) { - annotations.add((com.mapbox.mapboxsdk.annotations.Marker) annotation); - } - } - - return new ArrayList<>(annotations); - } - - @Override - public void reload() { - iconManager.reloadIcons(); - int count = annotations.size(); - for (int i = 0; i < count; i++) { - Annotation annotation = annotations.get(i); - if (annotation instanceof Marker) { - Marker marker = (Marker) annotation; - nativeMapView.removeAnnotation(annotation.getId()); - long newId = nativeMapView.addMarker(marker); - marker.setId(newId); - } - } - } - - private Marker prepareMarker(BaseMarkerOptions markerOptions) { - Marker marker = markerOptions.getMarker(); - Icon icon = iconManager.loadIconForMarker(marker); - marker.setTopOffsetPixels(iconManager.getTopOffsetPixelsForIcon(icon)); - return marker; - } - - private void ensureIconLoaded(Marker marker, @NonNull MapboxMap mapboxMap) { - iconManager.ensureIconLoaded(marker, mapboxMap); - } - - @NonNull - private List obtainAnnotations() { - List annotations = new ArrayList<>(); - for (int i = 0; i < this.annotations.size(); i++) { - annotations.add(this.annotations.get(this.annotations.keyAt(i))); - } - return annotations; - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Markers.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Markers.java deleted file mode 100644 index 62859d58a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Markers.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.RectF; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Marker; - -import java.util.List; - -/** - * Interface that defines convenient methods for working with a {@link Marker}'s collection. - */ -interface Markers { - Marker addBy(@NonNull BaseMarkerOptions markerOptions, @NonNull MapboxMap mapboxMap); - - List addBy(@NonNull List markerOptionsList, @NonNull MapboxMap mapboxMap); - - void update(@NonNull Marker updatedMarker, @NonNull MapboxMap mapboxMap); - - List obtainAll(); - - @NonNull - List obtainAllIn(@NonNull RectF rectangle); - - void reload(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMap.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMap.java deleted file mode 100644 index c805dcddb..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMap.java +++ /dev/null @@ -1,274 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.graphics.RectF; -import android.support.annotation.IntRange; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import com.mapbox.geojson.Feature; -import com.mapbox.geojson.Geometry; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.geometry.LatLngBounds; -import com.mapbox.mapboxsdk.geometry.ProjectedMeters; -import com.mapbox.mapboxsdk.style.expressions.Expression; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.layers.TransitionOptions; -import com.mapbox.mapboxsdk.style.light.Light; -import com.mapbox.mapboxsdk.style.sources.Source; - -import java.util.List; - -interface NativeMap { - - // - // Lifecycle API - // - - void resizeView(int width, int height); - - void onLowMemory(); - - void destroy(); - - boolean isDestroyed(); - - // - // Camera API - // - - void jumpTo(@NonNull LatLng center, double zoom, double pitch, double bearing, double[] padding); - - void easeTo(@NonNull LatLng center, double zoom, double bearing, double pitch, double[] padding, long duration, - boolean easingInterpolator); - - void flyTo(@NonNull LatLng center, double zoom, double bearing, double pitch, double[] padding, long duration); - - void moveBy(double deltaX, double deltaY, long duration); - - @NonNull - CameraPosition getCameraPosition(); - - CameraPosition getCameraForLatLngBounds(@NonNull LatLngBounds bounds, int[] padding, double bearing, double pitch); - - CameraPosition getCameraForGeometry(@NonNull Geometry geometry, int[] padding, double bearing, double pitch); - - void resetPosition(); - - void setLatLng(@NonNull LatLng latLng, long duration); - - LatLng getLatLng(); - - void setLatLngBounds(@Nullable LatLngBounds latLngBounds); - - void setVisibleCoordinateBounds(@NonNull LatLng[] coordinates, @NonNull RectF padding, - double direction, long duration); - - void setPitch(double pitch, long duration); - - double getPitch(); - - void setZoom(double zoom, @NonNull PointF focalPoint, long duration); - - double getZoom(); - - void setMinZoom(double zoom); - - double getMinZoom(); - - void setMaxZoom(double zoom); - - double getMaxZoom(); - - void resetZoom(); - - void rotateBy(double sx, double sy, double ex, double ey, long duration); - - void setBearing(double degrees, long duration); - - void setBearing(double degrees, double fx, double fy, long duration); - - double getBearing(); - - void resetNorth(); - - void cancelTransitions(); - - // - // Style API - // - - void setStyleUri(String url); - - @NonNull - String getStyleUri(); - - void setStyleJson(String newStyleJson); - - @NonNull - String getStyleJson(); - - boolean isFullyLoaded(); - - void addLayer(@NonNull Layer layer); - - void addLayerBelow(@NonNull Layer layer, @NonNull String below); - - void addLayerAbove(@NonNull Layer layer, @NonNull String above); - - void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index); - - @NonNull - List getLayers(); - - Layer getLayer(String layerId); - - boolean removeLayer(@NonNull String layerId); - - boolean removeLayer(@NonNull Layer layer); - - boolean removeLayerAt(@IntRange(from = 0) int index); - - void addSource(@NonNull Source source); - - @NonNull - List getSources(); - - Source getSource(@NonNull String sourceId); - - boolean removeSource(@NonNull String sourceId); - - boolean removeSource(@NonNull Source source); - - void setTransitionOptions(@NonNull TransitionOptions transitionOptions); - - @NonNull - TransitionOptions getTransitionOptions(); - - void addImages(Image[] images); - - Bitmap getImage(String name); - - void removeImage(String name); - - Light getLight(); - - // - // Content padding API - // - - void setContentPadding(double[] padding); - - double[] getContentPadding(); - - // - // Query API - // - - @NonNull - List queryRenderedFeatures(@NonNull PointF coordinates, - @Nullable String[] layerIds, - @Nullable Expression filter); - - @NonNull - List queryRenderedFeatures(@NonNull RectF coordinates, - @Nullable String[] layerIds, - @Nullable Expression filter); - - // - // Projection API - // - - double getMetersPerPixelAtLatitude(double lat); - - ProjectedMeters projectedMetersForLatLng(@NonNull LatLng latLng); - - LatLng latLngForProjectedMeters(@NonNull ProjectedMeters projectedMeters); - - @NonNull - PointF pixelForLatLng(@NonNull LatLng latLng); - - LatLng latLngForPixel(@NonNull PointF pixel); - - // - // Utils API - // - - void setOnFpsChangedListener(@NonNull MapboxMap.OnFpsChangedListener listener); - - void setDebug(boolean debug); - - boolean getDebug(); - - void cycleDebugOptions(); - - void setReachability(boolean status); - - void setApiBaseUrl(String baseUrl); - - void setPrefetchTiles(boolean enable); - - boolean getPrefetchTiles(); - - void setPrefetchZoomDelta(@IntRange(from = 0) int delta); - - @IntRange(from = 0) - int getPrefetchZoomDelta(); - - void setGestureInProgress(boolean inProgress); - - float getPixelRatio(); - - // - // Deprecated Annotations API - // - - long addMarker(Marker marker); - - @NonNull - long[] addMarkers(@NonNull List markers); - - long addPolyline(Polyline polyline); - - @NonNull - long[] addPolylines(@NonNull List polylines); - - long addPolygon(Polygon polygon); - - @NonNull - long[] addPolygons(@NonNull List polygons); - - void updateMarker(@NonNull Marker marker); - - void updatePolygon(@NonNull Polygon polygon); - - void updatePolyline(@NonNull Polyline polyline); - - void removeAnnotation(long id); - - void removeAnnotations(long[] ids); - - double getTopOffsetPixelsForAnnotationSymbol(String symbolName); - - void addAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels); - - void removeAnnotationIcon(String symbol); - - @NonNull - long[] queryPointAnnotations(RectF rectF); - - @NonNull - long[] queryShapeAnnotations(RectF rectF); - - @NonNull - RectF getDensityDependantRectangle(RectF rectangle); - - long getNativePtr(); - - void addSnapshotCallback(@NonNull MapboxMap.SnapshotReadyCallback callback); -} \ No newline at end of file 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 deleted file mode 100755 index 75ca5edfc..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/NativeMapView.java +++ /dev/null @@ -1,1512 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.PointF; -import android.graphics.RectF; -import android.os.Handler; -import android.support.annotation.IntRange; -import android.support.annotation.Keep; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.text.TextUtils; - -import com.mapbox.geojson.Feature; -import com.mapbox.geojson.Geometry; -import com.mapbox.mapboxsdk.LibraryLoader; -import com.mapbox.mapboxsdk.MapStrictMode; -import com.mapbox.mapboxsdk.annotations.Icon; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.exceptions.CalledFromWorkerThreadException; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.geometry.LatLngBounds; -import com.mapbox.mapboxsdk.geometry.ProjectedMeters; -import com.mapbox.mapboxsdk.log.Logger; -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.Layer; -import com.mapbox.mapboxsdk.style.layers.TransitionOptions; -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 java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -// Class that wraps the native methods for convenience -final class NativeMapView implements NativeMap { - - private static final String TAG = "Mbgl-NativeMapView"; - - // Hold a reference to prevent it from being GC'd as long as it's used on the native side - private final FileSource fileSource; - - // Used to schedule work on the MapRenderer Thread - private final MapRenderer mapRenderer; - - // Used to validate if methods are called from the correct thread - @NonNull - private final Thread thread; - - // Used for view callbacks - @Nullable - private ViewCallback viewCallback; - - // Used for map change callbacks - @Nullable - private StateCallback stateCallback; - - // Device density - private final float pixelRatio; - - // Flag to indicate destroy was called - private boolean destroyed = false; - - // Cached to enable lazily set padding. - // Whenever an animation is schedule, this value is cleared and the source of truth becomes the core transform state. - private double[] edgeInsets; - - // Holds the pointer to JNI NativeMapView - @Keep - private long nativePtr = 0; - - // Listener invoked to return a bitmap of the map - private MapboxMap.SnapshotReadyCallback snapshotReadyCallback; - - static { - LibraryLoader.load(); - } - - // - // Constructors - // - - public NativeMapView(@NonNull final Context context, final boolean crossSourceCollisions, - final ViewCallback viewCallback, final StateCallback stateCallback, - final MapRenderer mapRenderer) { - this(context, context.getResources().getDisplayMetrics().density, crossSourceCollisions, viewCallback, - stateCallback, mapRenderer); - } - - public NativeMapView(final Context context, final float pixelRatio, final boolean crossSourceCollisions, - final ViewCallback viewCallback, final StateCallback stateCallback, - final MapRenderer mapRenderer) { - this.mapRenderer = mapRenderer; - this.viewCallback = viewCallback; - this.fileSource = FileSource.getInstance(context); - this.pixelRatio = pixelRatio; - this.thread = Thread.currentThread(); - this.stateCallback = stateCallback; - nativeInitialize(this, fileSource, mapRenderer, pixelRatio, crossSourceCollisions); - } - - // - // Methods - // - - private boolean checkState(String callingMethod) { - // validate if invocation has occurred on the main thread - if (thread != Thread.currentThread()) { - throw new CalledFromWorkerThreadException( - String.format( - "Map interactions should happen on the UI thread. Method invoked from wrong thread is %s.", - callingMethod) - ); - } - - // validate if map has already been destroyed - if (destroyed && !TextUtils.isEmpty(callingMethod)) { - String message = String.format( - "You're calling `%s` after the `MapView` was destroyed, were you invoking it after `onDestroy()`?", - callingMethod); - Logger.e(TAG, message); - - MapStrictMode.strictModeViolation(message); - } - return destroyed; - } - - @Override - public void destroy() { - destroyed = true; - viewCallback = null; - nativeDestroy(); - } - - @Override - public void resizeView(int width, int height) { - if (checkState("resizeView")) { - return; - } - width = (int) Math.ceil(width / pixelRatio); - height = (int) Math.ceil(height / pixelRatio); - - if (width < 0) { - throw new IllegalArgumentException("width cannot be negative."); - } - - if (height < 0) { - throw new IllegalArgumentException("height cannot be negative."); - } - - if (width > 65535) { - // we have seen edge cases where devices return incorrect values #6111 - Logger.e(TAG, String.format("Device returned an out of range width size, " - + "capping value at 65535 instead of %s", width) - ); - width = 65535; - } - - if (height > 65535) { - // we have seen edge cases where devices return incorrect values #6111 - Logger.e(TAG, String.format("Device returned an out of range height size, " - + "capping value at 65535 instead of %s", height) - ); - height = 65535; - } - - nativeResizeView(width, height); - } - - @Override - public void setStyleUri(String url) { - if (checkState("setStyleUri")) { - return; - } - nativeSetStyleUrl(url); - } - - @Override - @NonNull - public String getStyleUri() { - if (checkState("getStyleUri")) { - return ""; - } - return nativeGetStyleUrl(); - } - - @Override - public void setStyleJson(String newStyleJson) { - if (checkState("setStyleJson")) { - return; - } - nativeSetStyleJson(newStyleJson); - } - - @Override - @NonNull - public String getStyleJson() { - if (checkState("getStyleJson")) { - return ""; - } - return nativeGetStyleJson(); - } - - @Override - public void setLatLngBounds(LatLngBounds latLngBounds) { - if (checkState("setLatLngBounds")) { - return; - } - nativeSetLatLngBounds(latLngBounds); - } - - @Override - public void cancelTransitions() { - if (checkState("cancelTransitions")) { - return; - } - nativeCancelTransitions(); - } - - @Override - public void setGestureInProgress(boolean inProgress) { - if (checkState("setGestureInProgress")) { - return; - } - nativeSetGestureInProgress(inProgress); - } - - @Override - public void moveBy(double dx, double dy, long duration) { - if (checkState("moveBy")) { - return; - } - nativeMoveBy(dx / pixelRatio, dy / pixelRatio, duration); - } - - @Override - public void setLatLng(@NonNull LatLng latLng, long duration) { - if (checkState("setLatLng")) { - return; - } - nativeSetLatLng(latLng.getLatitude(), latLng.getLongitude(), - getAnimationPaddingAndClearCachedInsets(null), duration); - } - - @Override - public LatLng getLatLng() { - if (checkState("")) { - return new LatLng(); - } - return nativeGetLatLng(); - } - - @Override - public CameraPosition getCameraForLatLngBounds(LatLngBounds bounds, int[] padding, double bearing, double tilt) { - if (checkState("getCameraForLatLngBounds")) { - return null; - } - return nativeGetCameraForLatLngBounds( - bounds, - padding[1] / pixelRatio, - padding[0] / pixelRatio, - padding[3] / pixelRatio, - padding[2] / pixelRatio, - bearing, - tilt - ); - } - - @Override - public CameraPosition getCameraForGeometry(Geometry geometry, int[] padding, double bearing, double tilt) { - if (checkState("getCameraForGeometry")) { - return null; - } - return nativeGetCameraForGeometry( - geometry, - padding[1] / pixelRatio, - padding[0] / pixelRatio, - padding[3] / pixelRatio, - padding[2] / pixelRatio, - bearing, - tilt - ); - } - - @Override - public void resetPosition() { - if (checkState("resetPosition")) { - return; - } - nativeResetPosition(); - } - - @Override - public double getPitch() { - if (checkState("getPitch")) { - return 0; - } - return nativeGetPitch(); - } - - @Override - public void setPitch(double pitch, long duration) { - if (checkState("setPitch")) { - return; - } - nativeSetPitch(pitch, duration); - } - - @Override - public void setZoom(double zoom, @NonNull PointF focalPoint, long duration) { - if (checkState("setZoom")) { - return; - } - nativeSetZoom(zoom, focalPoint.x / pixelRatio, focalPoint.y / pixelRatio, duration); - } - - @Override - public double getZoom() { - if (checkState("getZoom")) { - return 0; - } - return nativeGetZoom(); - } - - @Override - public void resetZoom() { - if (checkState("resetZoom")) { - return; - } - nativeResetZoom(); - } - - @Override - public void setMinZoom(double zoom) { - if (checkState("setMinZoom")) { - return; - } - nativeSetMinZoom(zoom); - } - - @Override - public double getMinZoom() { - if (checkState("getMinZoom")) { - return 0; - } - return nativeGetMinZoom(); - } - - @Override - public void setMaxZoom(double zoom) { - if (checkState("setMaxZoom")) { - return; - } - nativeSetMaxZoom(zoom); - } - - @Override - public double getMaxZoom() { - if (checkState("getMaxZoom")) { - return 0; - } - return nativeGetMaxZoom(); - } - - @Override - public void rotateBy(double sx, double sy, double ex, double ey, - long duration) { - if (checkState("rotateBy")) { - return; - } - nativeRotateBy(sx / pixelRatio, sy / pixelRatio, ex, ey, duration); - } - - @Override - public void setContentPadding(double[] padding) { - if (checkState("setContentPadding")) { - return; - } - this.edgeInsets = padding; - } - - @Override - public double[] getContentPadding() { - if (checkState("getContentPadding")) { - return new double[] {0, 0, 0, 0}; - } - // if cached insets are not applied yet, return them, otherwise, get the padding from the camera - return edgeInsets != null ? edgeInsets : getCameraPosition().padding; - } - - @Override - public void setBearing(double degrees, long duration) { - if (checkState("setBearing")) { - return; - } - nativeSetBearing(degrees, duration); - } - - @Override - public void setBearing(double degrees, double fx, double fy, long duration) { - if (checkState("setBearing")) { - return; - } - nativeSetBearingXY(degrees, fx / pixelRatio, fy / pixelRatio, duration); - } - - @Override - public double getBearing() { - if (checkState("getBearing")) { - return 0; - } - return nativeGetBearing(); - } - - @Override - public void resetNorth() { - if (checkState("resetNorth")) { - return; - } - nativeResetNorth(); - } - - @Override - public long addMarker(Marker marker) { - if (checkState("addMarker")) { - return 0; - } - Marker[] markers = {marker}; - return nativeAddMarkers(markers)[0]; - } - - @Override - @NonNull - public long[] addMarkers(@NonNull List markers) { - if (checkState("addMarkers")) { - return new long[] {}; - } - return nativeAddMarkers(markers.toArray(new Marker[markers.size()])); - } - - @Override - public long addPolyline(Polyline polyline) { - if (checkState("addPolyline")) { - return 0; - } - Polyline[] polylines = {polyline}; - return nativeAddPolylines(polylines)[0]; - } - - @Override - @NonNull - public long[] addPolylines(@NonNull List polylines) { - if (checkState("addPolylines")) { - return new long[] {}; - } - return nativeAddPolylines(polylines.toArray(new Polyline[polylines.size()])); - } - - @Override - public long addPolygon(Polygon polygon) { - if (checkState("addPolygon")) { - return 0; - } - Polygon[] polygons = {polygon}; - return nativeAddPolygons(polygons)[0]; - } - - @Override - @NonNull - public long[] addPolygons(@NonNull List polygons) { - if (checkState("addPolygons")) { - return new long[] {}; - } - return nativeAddPolygons(polygons.toArray(new Polygon[polygons.size()])); - } - - @Override - public void updateMarker(@NonNull Marker marker) { - if (checkState("updateMarker")) { - return; - } - LatLng position = marker.getPosition(); - Icon icon = marker.getIcon(); - nativeUpdateMarker(marker.getId(), position.getLatitude(), position.getLongitude(), icon.getId()); - } - - @Override - public void updatePolygon(@NonNull Polygon polygon) { - if (checkState("updatePolygon")) { - return; - } - nativeUpdatePolygon(polygon.getId(), polygon); - } - - @Override - public void updatePolyline(@NonNull Polyline polyline) { - if (checkState("updatePolyline")) { - return; - } - nativeUpdatePolyline(polyline.getId(), polyline); - } - - @Override - public void removeAnnotation(long id) { - if (checkState("removeAnnotation")) { - return; - } - long[] ids = {id}; - removeAnnotations(ids); - } - - @Override - public void removeAnnotations(long[] ids) { - if (checkState("removeAnnotations")) { - return; - } - nativeRemoveAnnotations(ids); - } - - @Override - @NonNull - public long[] queryPointAnnotations(RectF rect) { - if (checkState("queryPointAnnotations")) { - return new long[] {}; - } - return nativeQueryPointAnnotations(rect); - } - - @Override - @NonNull - public long[] queryShapeAnnotations(RectF rectF) { - if (checkState("queryShapeAnnotations")) { - return new long[] {}; - } - return nativeQueryShapeAnnotations(rectF); - } - - @Override - public void addAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels) { - if (checkState("addAnnotationIcon")) { - return; - } - nativeAddAnnotationIcon(symbol, width, height, scale, pixels); - } - - @Override - public void removeAnnotationIcon(String symbol) { - if (checkState("removeAnnotationIcon")) { - return; - } - nativeRemoveAnnotationIcon(symbol); - } - - @Override - public void setVisibleCoordinateBounds(LatLng[] coordinates, RectF padding, double direction, long duration) { - if (checkState("setVisibleCoordinateBounds")) { - return; - } - nativeSetVisibleCoordinateBounds(coordinates, padding, direction, duration); - } - - @Override - public void onLowMemory() { - if (checkState("onLowMemory")) { - return; - } - nativeOnLowMemory(); - } - - @Override - public void setDebug(boolean debug) { - if (checkState("setDebug")) { - return; - } - nativeSetDebug(debug); - } - - @Override - public void cycleDebugOptions() { - if (checkState("cycleDebugOptions")) { - return; - } - nativeCycleDebugOptions(); - } - - @Override - public boolean getDebug() { - if (checkState("getDebug")) { - return false; - } - return nativeGetDebug(); - } - - @Override - public boolean isFullyLoaded() { - if (checkState("isFullyLoaded")) { - return false; - } - return nativeIsFullyLoaded(); - } - - @Override - public void setReachability(boolean status) { - if (checkState("setReachability")) { - return; - } - nativeSetReachability(status); - } - - @Override - public double getMetersPerPixelAtLatitude(double lat) { - if (checkState("getMetersPerPixelAtLatitude")) { - return 0; - } - return nativeGetMetersPerPixelAtLatitude(lat, getZoom()); - } - - @Override - public ProjectedMeters projectedMetersForLatLng(@NonNull LatLng latLng) { - if (checkState("projectedMetersForLatLng")) { - return null; - } - return nativeProjectedMetersForLatLng(latLng.getLatitude(), latLng.getLongitude()); - } - - @Override - public LatLng latLngForProjectedMeters(@NonNull ProjectedMeters projectedMeters) { - if (checkState("latLngForProjectedMeters")) { - return new LatLng(); - } - return nativeLatLngForProjectedMeters(projectedMeters.getNorthing(), - projectedMeters.getEasting()); - } - - @Override - @NonNull - public PointF pixelForLatLng(@NonNull LatLng latLng) { - if (checkState("pixelForLatLng")) { - return new PointF(); - } - PointF pointF = nativePixelForLatLng(latLng.getLatitude(), latLng.getLongitude()); - pointF.set(pointF.x * pixelRatio, pointF.y * pixelRatio); - return pointF; - } - - @Override - public LatLng latLngForPixel(@NonNull PointF pixel) { - if (checkState("latLngForPixel")) { - return new LatLng(); - } - return nativeLatLngForPixel(pixel.x / pixelRatio, pixel.y / pixelRatio); - } - - @Override - public double getTopOffsetPixelsForAnnotationSymbol(String symbolName) { - if (checkState("getTopOffsetPixelsForAnnotationSymbol")) { - return 0; - } - return nativeGetTopOffsetPixelsForAnnotationSymbol(symbolName); - } - - @Override - public void jumpTo(@NonNull LatLng center, double zoom, double pitch, double angle, double[] padding) { - if (checkState("jumpTo")) { - return; - } - nativeJumpTo(angle, center.getLatitude(), center.getLongitude(), pitch, zoom, - getAnimationPaddingAndClearCachedInsets(padding)); - } - - @Override - public void easeTo(@NonNull LatLng center, double zoom, double angle, double pitch, double[] padding, long duration, - boolean easingInterpolator) { - if (checkState("easeTo")) { - return; - } - nativeEaseTo(angle, center.getLatitude(), center.getLongitude(), duration, pitch, zoom, - getAnimationPaddingAndClearCachedInsets(padding), easingInterpolator); - } - - @Override - public void flyTo(@NonNull LatLng center, double zoom, double angle, double pitch, double[] padding, long duration) { - if (checkState("flyTo")) { - return; - } - nativeFlyTo(angle, center.getLatitude(), center.getLongitude(), duration, pitch, zoom, - getAnimationPaddingAndClearCachedInsets(padding)); - } - - @Override - @NonNull - public CameraPosition getCameraPosition() { - if (checkState("getCameraValues")) { - return new CameraPosition.Builder().build(); - } - if (edgeInsets != null) { - return new CameraPosition.Builder(nativeGetCameraPosition()).padding(edgeInsets).build(); - } else { - return nativeGetCameraPosition(); - } - } - - @Override - public void setPrefetchTiles(boolean enable) { - if (checkState("setPrefetchTiles")) { - return; - } - nativeSetPrefetchTiles(enable); - } - - @Override - public boolean getPrefetchTiles() { - if (checkState("getPrefetchTiles")) { - return false; - } - return nativeGetPrefetchTiles(); - } - - @Override - public void setPrefetchZoomDelta(@IntRange(from = 0) int delta) { - if (checkState("nativeSetPrefetchZoomDelta")) { - return; - } - nativeSetPrefetchZoomDelta(delta); - } - - @Override - @IntRange(from = 0) - public int getPrefetchZoomDelta() { - if (checkState("nativeGetPrefetchZoomDelta")) { - return 0; - } - return nativeGetPrefetchZoomDelta(); - } - - // Runtime style Api - - @Override - public void setTransitionOptions(@NonNull TransitionOptions transitionOptions) { - nativeSetTransitionOptions(transitionOptions); - } - - @NonNull - @Override - public TransitionOptions getTransitionOptions() { - return nativeGetTransitionOptions(); - } - - @Override - @NonNull - public List getLayers() { - if (checkState("getLayers")) { - return new ArrayList<>(); - } - return Arrays.asList(nativeGetLayers()); - } - - @Override - public Layer getLayer(String layerId) { - if (checkState("getLayer")) { - return null; - } - return nativeGetLayer(layerId); - } - - @Override - public void addLayer(@NonNull Layer layer) { - if (checkState("addLayer")) { - return; - } - nativeAddLayer(layer.getNativePtr(), null); - } - - @Override - public void addLayerBelow(@NonNull Layer layer, @NonNull String below) { - if (checkState("addLayerBelow")) { - return; - } - nativeAddLayer(layer.getNativePtr(), below); - } - - @Override - public void addLayerAbove(@NonNull Layer layer, @NonNull String above) { - if (checkState("addLayerAbove")) { - return; - } - nativeAddLayerAbove(layer.getNativePtr(), above); - } - - @Override - public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) { - if (checkState("addLayerAt")) { - return; - } - nativeAddLayerAt(layer.getNativePtr(), index); - } - - @Override - public boolean removeLayer(@NonNull String layerId) { - if (checkState("removeLayer")) { - return false; - } - - Layer layer = getLayer(layerId); - if (layer != null) { - return removeLayer(layer); - } - return false; - } - - - @Override - public boolean removeLayer(@NonNull Layer layer) { - if (checkState("removeLayer")) { - return false; - } - return nativeRemoveLayer(layer.getNativePtr()); - } - - @Override - public boolean removeLayerAt(@IntRange(from = 0) int index) { - if (checkState("removeLayerAt")) { - return false; - } - return nativeRemoveLayerAt(index); - } - - @Override - @NonNull - public List getSources() { - if (checkState("getSources")) { - return new ArrayList<>(); - } - return Arrays.asList(nativeGetSources()); - } - - @Override - public Source getSource(@NonNull String sourceId) { - if (checkState("getSource")) { - return null; - } - return nativeGetSource(sourceId); - } - - @Override - public void addSource(@NonNull Source source) { - if (checkState("addSource")) { - return; - } - nativeAddSource(source, source.getNativePtr()); - } - - @Override - public boolean removeSource(@NonNull String sourceId) { - if (checkState("removeSource")) { - return false; - } - Source source = getSource(sourceId); - if (source != null) { - return removeSource(source); - } - return false; - } - - @Override - public boolean removeSource(@NonNull Source source) { - if (checkState("removeSource")) { - return false; - } - return nativeRemoveSource(source, source.getNativePtr()); - } - - @Override - public void addImages(@NonNull Image[] images) { - if (checkState("addImages")) { - return; - } - nativeAddImages(images); - } - - @Override - public void removeImage(String name) { - if (checkState("removeImage")) { - return; - } - nativeRemoveImage(name); - } - - @Override - public Bitmap getImage(String name) { - if (checkState("getImage")) { - return null; - } - return nativeGetImage(name); - } - - // Feature querying - - @Override - @NonNull - public List queryRenderedFeatures(@NonNull PointF coordinates, - @Nullable String[] layerIds, - @Nullable Expression filter) { - if (checkState("queryRenderedFeatures")) { - return new ArrayList<>(); - } - Feature[] features = nativeQueryRenderedFeaturesForPoint(coordinates.x / pixelRatio, - coordinates.y / pixelRatio, layerIds, filter != null ? filter.toArray() : null); - return features != null ? Arrays.asList(features) : new ArrayList(); - } - - @Override - @NonNull - public List queryRenderedFeatures(@NonNull RectF coordinates, - @Nullable String[] layerIds, - @Nullable Expression filter) { - if (checkState("queryRenderedFeatures")) { - return new ArrayList<>(); - } - Feature[] features = nativeQueryRenderedFeaturesForBox( - coordinates.left / pixelRatio, - coordinates.top / pixelRatio, - coordinates.right / pixelRatio, - coordinates.bottom / pixelRatio, - layerIds, - filter != null ? filter.toArray() : null); - return features != null ? Arrays.asList(features) : new ArrayList(); - } - - @Override - public void setApiBaseUrl(String baseUrl) { - if (checkState("setApiBaseUrl")) { - return; - } - fileSource.setApiBaseUrl(baseUrl); - } - - @Override - public Light getLight() { - if (checkState("getLight")) { - return null; - } - return nativeGetLight(); - } - - @Override - public float getPixelRatio() { - return pixelRatio; - } - - @NonNull - @Override - public RectF getDensityDependantRectangle(final RectF rectangle) { - return new RectF( - rectangle.left / pixelRatio, - rectangle.top / pixelRatio, - rectangle.right / pixelRatio, - rectangle.bottom / pixelRatio - ); - } - - // - // Callbacks - // - - @Keep - private void onCameraWillChange(boolean animated) { - if (stateCallback != null) { - stateCallback.onCameraWillChange(animated); - } - } - - @Keep - private void onCameraIsChanging() { - if (stateCallback != null) { - stateCallback.onCameraIsChanging(); - } - } - - @Keep - private void onCameraDidChange(boolean animated) { - if (stateCallback != null) { - stateCallback.onCameraDidChange(animated); - } - } - - @Keep - private void onWillStartLoadingMap() { - if (stateCallback != null) { - stateCallback.onWillStartLoadingMap(); - } - } - - @Keep - private void onDidFinishLoadingMap() { - if (stateCallback != null) { - stateCallback.onDidFinishLoadingMap(); - } - } - - @Keep - private void onDidFailLoadingMap(String error) { - if (stateCallback != null) { - stateCallback.onDidFailLoadingMap(error); - } - } - - @Keep - private void onWillStartRenderingFrame() { - if (stateCallback != null) { - stateCallback.onWillStartRenderingFrame(); - } - } - - @Keep - private void onDidFinishRenderingFrame(boolean fully) { - if (stateCallback != null) { - stateCallback.onDidFinishRenderingFrame(fully); - } - } - - @Keep - private void onWillStartRenderingMap() { - if (stateCallback != null) { - stateCallback.onWillStartRenderingMap(); - } - } - - @Keep - private void onDidFinishRenderingMap(boolean fully) { - if (stateCallback != null) { - stateCallback.onDidFinishRenderingMap(fully); - } - } - - @Keep - private void onDidBecomeIdle() { - if (stateCallback != null) { - stateCallback.onDidBecomeIdle(); - } - } - - @Keep - private void onDidFinishLoadingStyle() { - if (stateCallback != null) { - stateCallback.onDidFinishLoadingStyle(); - } - } - - @Keep - private void onSourceChanged(String sourceId) { - if (stateCallback != null) { - stateCallback.onSourceChanged(sourceId); - } - } - - @Keep - private void onStyleImageMissing(String imageId) { - if (stateCallback != null) { - stateCallback.onStyleImageMissing(imageId); - } - } - - @Keep - private boolean onCanRemoveUnusedStyleImage(String imageId) { - if (stateCallback != null) { - return stateCallback.onCanRemoveUnusedStyleImage(imageId); - } - - return true; - } - - @Keep - protected void onSnapshotReady(@Nullable Bitmap mapContent) { - if (checkState("OnSnapshotReady")) { - return; - } - - try { - if (snapshotReadyCallback != null && mapContent != null) { - if (viewCallback == null) { - snapshotReadyCallback.onSnapshotReady(mapContent); - } else { - Bitmap viewContent = viewCallback.getViewContent(); - if (viewContent != null) { - snapshotReadyCallback.onSnapshotReady(BitmapUtils.mergeBitmap(mapContent, viewContent)); - } - } - } - } catch (Throwable err) { - Logger.e(TAG, "Exception in onSnapshotReady", err); - throw err; - } - } - - // - // JNI methods - // - - @Keep - private native void nativeInitialize(NativeMapView nativeMap, - FileSource fileSource, - MapRenderer mapRenderer, - float pixelRatio, - boolean crossSourceCollisions); - - @Keep - private native void nativeDestroy(); - - @Keep - private native void nativeResizeView(int width, int height); - - @Keep - private native void nativeSetStyleUrl(String url); - - @NonNull - @Keep - private native String nativeGetStyleUrl(); - - @Keep - private native void nativeSetStyleJson(String newStyleJson); - - @NonNull - @Keep - private native String nativeGetStyleJson(); - - @Keep - private native void nativeSetLatLngBounds(LatLngBounds latLngBounds); - - @Keep - private native void nativeCancelTransitions(); - - @Keep - private native void nativeSetGestureInProgress(boolean inProgress); - - @Keep - private native void nativeMoveBy(double dx, double dy, long duration); - - @Keep - private native void nativeSetLatLng(double latitude, double longitude, double[] padding, long duration); - - @NonNull - @Keep - private native LatLng nativeGetLatLng(); - - @NonNull - @Keep - private native CameraPosition nativeGetCameraForLatLngBounds( - LatLngBounds latLngBounds, double top, double left, double bottom, double right, double bearing, double tilt); - - @NonNull - @Keep - private native CameraPosition nativeGetCameraForGeometry( - Geometry geometry, double top, double left, double bottom, double right, double bearing, double tilt); - - @Keep - private native void nativeResetPosition(); - - @Keep - private native double nativeGetPitch(); - - @Keep - private native void nativeSetPitch(double pitch, long duration); - - @Keep - private native void nativeSetZoom(double zoom, double cx, double cy, long duration); - - @Keep - private native double nativeGetZoom(); - - @Keep - private native void nativeResetZoom(); - - @Keep - private native void nativeSetMinZoom(double zoom); - - @Keep - private native double nativeGetMinZoom(); - - @Keep - private native void nativeSetMaxZoom(double zoom); - - @Keep - private native double nativeGetMaxZoom(); - - @Keep - private native void nativeRotateBy(double sx, double sy, double ex, double ey, long duration); - - @Keep - private native void nativeSetBearing(double degrees, long duration); - - @Keep - private native void nativeSetBearingXY(double degrees, double fx, double fy, long duration); - - @Keep - private native double nativeGetBearing(); - - @Keep - private native void nativeResetNorth(); - - @Keep - private native void nativeUpdateMarker(long markerId, double lat, double lon, String iconId); - - @NonNull - @Keep - private native long[] nativeAddMarkers(Marker[] markers); - - @NonNull - @Keep - private native long[] nativeAddPolylines(Polyline[] polylines); - - @NonNull - @Keep - private native long[] nativeAddPolygons(Polygon[] polygons); - - @Keep - private native void nativeRemoveAnnotations(long[] id); - - @NonNull - @Keep - private native long[] nativeQueryPointAnnotations(RectF rect); - - @NonNull - @Keep - private native long[] nativeQueryShapeAnnotations(RectF rect); - - @Keep - private native void nativeAddAnnotationIcon(String symbol, int width, int height, float scale, byte[] pixels); - - @Keep - private native void nativeRemoveAnnotationIcon(String symbol); - - @Keep - private native void nativeSetVisibleCoordinateBounds(LatLng[] coordinates, RectF padding, - double direction, long duration); - - @Keep - private native void nativeOnLowMemory(); - - @Keep - private native void nativeSetDebug(boolean debug); - - @Keep - private native void nativeCycleDebugOptions(); - - @Keep - private native boolean nativeGetDebug(); - - @Keep - private native boolean nativeIsFullyLoaded(); - - @Keep - private native void nativeSetReachability(boolean status); - - @Keep - private native double nativeGetMetersPerPixelAtLatitude(double lat, double zoom); - - @NonNull - @Keep - private native ProjectedMeters nativeProjectedMetersForLatLng(double latitude, double longitude); - - @NonNull - @Keep - private native LatLng nativeLatLngForProjectedMeters(double northing, double easting); - - @NonNull - @Keep - private native PointF nativePixelForLatLng(double lat, double lon); - - @NonNull - @Keep - private native LatLng nativeLatLngForPixel(float x, float y); - - @Keep - private native double nativeGetTopOffsetPixelsForAnnotationSymbol(String symbolName); - - @Keep - private native void nativeJumpTo(double angle, double latitude, double longitude, double pitch, double zoom, - double[] padding); - - @Keep - private native void nativeEaseTo(double angle, double latitude, double longitude, - long duration, double pitch, double zoom, double[] padding, - boolean easingInterpolator); - - @Keep - private native void nativeFlyTo(double angle, double latitude, double longitude, - long duration, double pitch, double zoom, double[] padding); - - @NonNull - @Keep - private native CameraPosition nativeGetCameraPosition(); - - @Keep - private native void nativeSetTransitionOptions(TransitionOptions transitionOptions); - - @NonNull - @Keep - private native TransitionOptions nativeGetTransitionOptions(); - - @Keep - private native long nativeGetTransitionDuration(); - - @Keep - private native void nativeSetTransitionDuration(long duration); - - @Keep - private native long nativeGetTransitionDelay(); - - @Keep - private native void nativeSetTransitionDelay(long delay); - - @NonNull - @Keep - private native Layer[] nativeGetLayers(); - - @NonNull - @Keep - private native Layer nativeGetLayer(String layerId); - - @Keep - private native void nativeAddLayer(long layerPtr, String before) throws CannotAddLayerException; - - @Keep - private native void nativeAddLayerAbove(long layerPtr, String above) throws CannotAddLayerException; - - @Keep - private native void nativeAddLayerAt(long layerPtr, int index) throws CannotAddLayerException; - - @Keep - private native boolean nativeRemoveLayer(long layerId); - - @Keep - private native boolean nativeRemoveLayerAt(int index); - - @NonNull - @Keep - private native Source[] nativeGetSources(); - - @NonNull - @Keep - private native Source nativeGetSource(String sourceId); - - @Keep - private native void nativeAddSource(Source source, long sourcePtr) throws CannotAddSourceException; - - @Keep - private native boolean nativeRemoveSource(Source source, long sourcePtr); - - @Keep - private native void nativeAddImage(String name, Bitmap bitmap, float pixelRatio, boolean sdf); - - @Keep - private native void nativeAddImages(Image[] images); - - @Keep - private native void nativeRemoveImage(String name); - - @NonNull - @Keep - private native Bitmap nativeGetImage(String name); - - @Keep - private native void nativeUpdatePolygon(long polygonId, Polygon polygon); - - @Keep - private native void nativeUpdatePolyline(long polylineId, Polyline polyline); - - @Keep - private native void nativeTakeSnapshot(); - - @NonNull - @Keep - private native Feature[] nativeQueryRenderedFeaturesForPoint(float x, float y, - String[] layerIds, - Object[] filter); - - @NonNull - @Keep - private native Feature[] nativeQueryRenderedFeaturesForBox(float left, float top, - float right, float bottom, - String[] layerIds, - Object[] filter); - - @NonNull - @Keep - private native Light nativeGetLight(); - - @Keep - private native void nativeSetPrefetchTiles(boolean enable); - - @Keep - private native boolean nativeGetPrefetchTiles(); - - @Keep - private native void nativeSetPrefetchZoomDelta(int delta); - - @Keep - private native int nativeGetPrefetchZoomDelta(); - - @Override - public long getNativePtr() { - return nativePtr; - } - - // - // Snapshot - // - - @Override - public void addSnapshotCallback(@NonNull MapboxMap.SnapshotReadyCallback callback) { - if (checkState("addSnapshotCallback")) { - return; - } - snapshotReadyCallback = callback; - nativeTakeSnapshot(); - } - - @Override - public void setOnFpsChangedListener(@Nullable final MapboxMap.OnFpsChangedListener listener) { - final Handler handler = new Handler(); - mapRenderer.queueEvent(new Runnable() { - - @Override - public void run() { - if (listener != null) { - mapRenderer.setOnFpsChangedListener(new MapboxMap.OnFpsChangedListener() { - @Override - public void onFpsChanged(final double fps) { - handler.post(new Runnable() { - - @Override - public void run() { - listener.onFpsChanged(fps); - } - - }); - } - }); - } else { - mapRenderer.setOnFpsChangedListener(null); - } - } - }); - } - - @Override - public boolean isDestroyed() { - return destroyed; - } - - private double[] getAnimationPaddingAndClearCachedInsets(double[] providedPadding) { - if (providedPadding == null) { - providedPadding = this.edgeInsets; - } - this.edgeInsets = null; - return providedPadding == null ? null : - new double[] { - providedPadding[1] / pixelRatio, - providedPadding[0] / pixelRatio, - providedPadding[3] / pixelRatio, - providedPadding[2] / pixelRatio - }; - } - - public interface ViewCallback { - @Nullable - Bitmap getViewContent(); - } - - interface StyleCallback { - void onWillStartLoadingMap(); - - void onDidFinishLoadingStyle(); - } - - interface StateCallback extends StyleCallback { - void onCameraWillChange(boolean animated); - - void onCameraIsChanging(); - - void onCameraDidChange(boolean animated); - - void onDidFinishLoadingMap(); - - void onDidFailLoadingMap(String error); - - void onWillStartRenderingFrame(); - - void onDidFinishRenderingFrame(boolean fully); - - void onWillStartRenderingMap(); - - void onDidFinishRenderingMap(boolean fully); - - void onDidBecomeIdle(); - - void onSourceChanged(String sourceId); - - void onStyleImageMissing(String imageId); - - boolean onCanRemoveUnusedStyleImage(String imageId); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/OnMapReadyCallback.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/OnMapReadyCallback.java deleted file mode 100644 index 31b459abb..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/OnMapReadyCallback.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.support.annotation.NonNull; - -/** - * Interface definition for a callback to be invoked when the map is ready to be used. - *

- * Once an instance of this interface is set on a {@link MapFragment} or {@link MapView} object, - * the onMapReady(MapboxMap) method is triggered when the map is ready to be used and provides an instance of - * {@link MapboxMap}. - *

- */ -public interface OnMapReadyCallback { - - /** - * Called when the map is ready to be used. - * - * @param mapboxMap An instance of MapboxMap associated with the {@link MapFragment} or - * {@link MapView} that defines the callback. - */ - void onMapReady(@NonNull MapboxMap mapboxMap); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolygonContainer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolygonContainer.java deleted file mode 100644 index a7e2ace06..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolygonContainer.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.PolygonOptions; - -import java.util.ArrayList; -import java.util.List; - -/** - * Encapsulates {@link Polygon}'s functionality. - */ -class PolygonContainer implements Polygons { - - private final NativeMap nativeMap; - private final LongSparseArray annotations; - - PolygonContainer(NativeMap nativeMap, LongSparseArray annotations) { - this.nativeMap = nativeMap; - this.annotations = annotations; - } - - @Override - public Polygon addBy(@NonNull PolygonOptions polygonOptions, @NonNull MapboxMap mapboxMap) { - Polygon polygon = polygonOptions.getPolygon(); - if (!polygon.getPoints().isEmpty()) { - long id = nativeMap != null ? nativeMap.addPolygon(polygon) : 0; - polygon.setId(id); - polygon.setMapboxMap(mapboxMap); - annotations.put(id, polygon); - } - return polygon; - } - - @NonNull - @Override - public List addBy(@NonNull List polygonOptionsList, @NonNull MapboxMap mapboxMap) { - int count = polygonOptionsList.size(); - - Polygon polygon; - List polygons = new ArrayList<>(count); - if (nativeMap != null && count > 0) { - for (PolygonOptions polygonOptions : polygonOptionsList) { - polygon = polygonOptions.getPolygon(); - if (!polygon.getPoints().isEmpty()) { - polygons.add(polygon); - } - } - - long[] ids = nativeMap.addPolygons(polygons); - for (int i = 0; i < ids.length; i++) { - polygon = polygons.get(i); - polygon.setMapboxMap(mapboxMap); - polygon.setId(ids[i]); - annotations.put(ids[i], polygon); - } - } - return polygons; - } - - @Override - public void update(@NonNull Polygon polygon) { - nativeMap.updatePolygon(polygon); - annotations.setValueAt(annotations.indexOfKey(polygon.getId()), polygon); - } - - @NonNull - @Override - public List obtainAll() { - List polygons = new ArrayList<>(); - Annotation annotation; - for (int i = 0; i < annotations.size(); i++) { - annotation = annotations.get(annotations.keyAt(i)); - if (annotation instanceof Polygon) { - polygons.add((Polygon) annotation); - } - } - return polygons; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polygons.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polygons.java deleted file mode 100644 index 2a0190b5b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polygons.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.annotations.Polygon; -import com.mapbox.mapboxsdk.annotations.PolygonOptions; - -import java.util.List; - -/** - * Interface that defines convenient methods for working with a {@link Polygon}'s collection. - */ -interface Polygons { - Polygon addBy(@NonNull PolygonOptions polygonOptions, @NonNull MapboxMap mapboxMap); - - List addBy(@NonNull List polygonOptionsList, @NonNull MapboxMap mapboxMap); - - void update(Polygon polygon); - - List obtainAll(); -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolylineContainer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolylineContainer.java deleted file mode 100644 index e11da26e0..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/PolylineContainer.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.annotations.PolylineOptions; - -import java.util.ArrayList; -import java.util.List; - -/** - * Encapsulates {@link Polyline}'s functionality. - */ -class PolylineContainer implements Polylines { - - private final NativeMap nativeMap; - private final LongSparseArray annotations; - - PolylineContainer(NativeMap nativeMap, LongSparseArray annotations) { - this.nativeMap = nativeMap; - this.annotations = annotations; - } - - @Override - public Polyline addBy(@NonNull PolylineOptions polylineOptions, @NonNull MapboxMap mapboxMap) { - Polyline polyline = polylineOptions.getPolyline(); - if (!polyline.getPoints().isEmpty()) { - long id = nativeMap != null ? nativeMap.addPolyline(polyline) : 0; - polyline.setMapboxMap(mapboxMap); - polyline.setId(id); - annotations.put(id, polyline); - } - return polyline; - } - - @NonNull - @Override - public List addBy(@NonNull List polylineOptionsList, @NonNull MapboxMap mapboxMap) { - int count = polylineOptionsList.size(); - Polyline polyline; - List polylines = new ArrayList<>(count); - if (nativeMap != null && count > 0) { - for (PolylineOptions options : polylineOptionsList) { - polyline = options.getPolyline(); - if (!polyline.getPoints().isEmpty()) { - polylines.add(polyline); - } - } - - long[] ids = nativeMap.addPolylines(polylines); - for (int i = 0; i < ids.length; i++) { - Polyline polylineCreated = polylines.get(i); - polylineCreated.setMapboxMap(mapboxMap); - polylineCreated.setId(ids[i]); - annotations.put(ids[i], polylineCreated); - } - } - return polylines; - } - - @Override - public void update(@NonNull Polyline polyline) { - nativeMap.updatePolyline(polyline); - annotations.setValueAt(annotations.indexOfKey(polyline.getId()), polyline); - } - - @NonNull - @Override - public List obtainAll() { - List polylines = new ArrayList<>(); - Annotation annotation; - for (int i = 0; i < annotations.size(); i++) { - annotation = annotations.get(annotations.keyAt(i)); - if (annotation instanceof Polyline) { - polylines.add((Polyline) annotation); - } - } - return polylines; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polylines.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polylines.java deleted file mode 100644 index c9a865cdd..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Polylines.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - - -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.annotations.Polyline; -import com.mapbox.mapboxsdk.annotations.PolylineOptions; - -import java.util.List; - -/** - * Interface that defines convenient methods for working with a {@link Polyline}'s collection. - */ -interface Polylines { - Polyline addBy(@NonNull PolylineOptions polylineOptions, @NonNull MapboxMap mapboxMap); - - List addBy(@NonNull List polylineOptionsList, @NonNull MapboxMap mapboxMap); - - void update(Polyline polyline); - - List obtainAll(); -} 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 deleted file mode 100644 index 76395f956..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Projection.java +++ /dev/null @@ -1,283 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.PointF; -import android.support.annotation.FloatRange; -import android.support.annotation.NonNull; - -import com.mapbox.geojson.Point; -import com.mapbox.mapboxsdk.constants.GeometryConstants; -import com.mapbox.mapboxsdk.geometry.LatLng; -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) - * with respect to the top left corner of the map (and not necessarily of the whole screen). - */ -public class Projection { - - @NonNull - private final NativeMap nativeMapView; - @NonNull - private final MapView mapView; - - Projection(@NonNull NativeMap nativeMapView, @NonNull MapView mapView) { - this.nativeMapView = nativeMapView; - this.mapView = mapView; - } - - void setContentPadding(int[] contentPadding) { - double[] output = new double[contentPadding.length]; - for (int i = 0; i < contentPadding.length; i++) { - output[i] = contentPadding[i]; - } - nativeMapView.setContentPadding(output); - } - - int[] getContentPadding() { - double[] padding = nativeMapView.getCameraPosition().padding; - return new int[] {(int) padding[0], (int) padding[1], (int) padding[2], (int) padding[3]}; - } - - /** - * @deprecated unused - */ - @Deprecated - public void invalidateContentPadding() { - } - - /** - * Returns the spherical Mercator projected meters for a LatLng. - */ - @NonNull - public ProjectedMeters getProjectedMetersForLatLng(@NonNull LatLng latLng) { - return nativeMapView.projectedMetersForLatLng(latLng); - } - - /** - * Returns the LatLng for a spherical Mercator projected meters. - */ - @NonNull - public LatLng getLatLngForProjectedMeters(@NonNull ProjectedMeters projectedMeters) { - return nativeMapView.latLngForProjectedMeters(projectedMeters); - } - - /** - *

- * Returns the distance spanned by one pixel at the specified latitude and current zoom level. - *

- * The distance between pixels decreases as the latitude approaches the poles. - * This relationship parallels the relationship between longitudinal coordinates at different latitudes. - * - * @param latitude The latitude for which to return the value. - * @return The distance measured in meters. - */ - public double getMetersPerPixelAtLatitude(@FloatRange(from = -90, to = 90) double latitude) { - return nativeMapView.getMetersPerPixelAtLatitude(latitude); - } - - /** - * Returns the geographic location that corresponds to a screen location. - * The screen location is specified in screen pixels (not display pixels) relative to the - * top left of the map (not the top left of the whole screen). - * - * @param point A Point on the screen in screen pixels. - * @return The LatLng corresponding to the point on the screen, or null if the ray through - * the given screen point does not intersect the ground plane. - */ - @NonNull - public LatLng fromScreenLocation(@NonNull PointF point) { - return nativeMapView.latLngForPixel(point); - } - - /** - * Gets a projection of the viewing frustum for converting between screen coordinates and - * geo-latitude/longitude coordinates. - *

- * This method ignores the content padding. - * - * @return The projection of the viewing frustum in its current state. - */ - @NonNull - public VisibleRegion getVisibleRegion() { - return getVisibleRegion(true); - } - - /** - * Gets a projection of the viewing frustum for converting between screen coordinates and - * geo-latitude/longitude coordinates. - * - * @param ignorePadding True if the padding should be ignored, - * false if the returned region should be reduced by the padding. - * @return The projection of the viewing frustum in its current state. - */ - @NonNull - public VisibleRegion getVisibleRegion(boolean ignorePadding) { - float left; - float right; - float top; - float bottom; - - if (ignorePadding) { - left = 0; - right = mapView.getWidth(); - top = 0; - bottom = mapView.getHeight(); - } else { - int[] contentPadding = getContentPadding(); - left = contentPadding[0]; - right = mapView.getWidth() - contentPadding[2]; - top = contentPadding[1]; - bottom = mapView.getHeight() - contentPadding[3]; - } - - LatLng center = fromScreenLocation(new PointF(left + (right - left) / 2, top + (bottom - top) / 2)); - - LatLng topLeft = fromScreenLocation(new PointF(left, top)); - LatLng topRight = fromScreenLocation(new PointF(right, top)); - LatLng bottomRight = fromScreenLocation(new PointF(right, bottom)); - LatLng bottomLeft = fromScreenLocation(new PointF(left, bottom)); - - List latLngs = new ArrayList<>(); - latLngs.add(topRight); - latLngs.add(bottomRight); - latLngs.add(bottomLeft); - latLngs.add(topLeft); - - double maxEastLonSpan = 0; - double maxWestLonSpan = 0; - - double east = 0; - double west = 0; - double north = GeometryConstants.MIN_LATITUDE; - double south = GeometryConstants.MAX_LATITUDE; - - for (LatLng latLng : latLngs) { - double bearing = bearing(center, latLng); - - if (bearing >= 0) { - double span = getLongitudeSpan(latLng.getLongitude(), center.getLongitude()); - if (span > maxEastLonSpan) { - maxEastLonSpan = span; - east = latLng.getLongitude(); - } - } else { - double span = getLongitudeSpan(center.getLongitude(), latLng.getLongitude()); - if (span > maxWestLonSpan) { - maxWestLonSpan = span; - west = latLng.getLongitude(); - } - } - - if (north < latLng.getLatitude()) { - north = latLng.getLatitude(); - } - if (south > latLng.getLatitude()) { - south = latLng.getLatitude(); - } - } - - if (east < west) { - return new VisibleRegion(topLeft, topRight, bottomLeft, bottomRight, - LatLngBounds.from(north, east + GeometryConstants.LONGITUDE_SPAN, south, west)); - } - return new VisibleRegion(topLeft, topRight, bottomLeft, bottomRight, - LatLngBounds.from(north, east, south, west)); - } - - /** - * Takes two {@link Point}s and finds the geographic bearing between them. - * - * @param latLng1 the first point used for calculating the bearing - * @param latLng2 the second point used for calculating the bearing - * @return bearing in decimal degrees - * @see Turf Bearing documentation - */ - static double bearing(@NonNull LatLng latLng1, @NonNull LatLng latLng2) { - - double lon1 = degreesToRadians(latLng1.getLongitude()); - double lon2 = degreesToRadians(latLng2.getLongitude()); - double lat1 = degreesToRadians(latLng1.getLatitude()); - double lat2 = degreesToRadians(latLng2.getLatitude()); - - double value1 = Math.sin(lon2 - lon1) * Math.cos(lat2); - double value2 = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) - * Math.cos(lat2) * Math.cos(lon2 - lon1); - - return radiansToDegrees(Math.atan2(value1, value2)); - } - - /** - * Converts an angle in degrees to radians. - * - * @param degrees angle between 0 and 360 degrees - * @return angle in radians - */ - static double degreesToRadians(double degrees) { - double radians = degrees % 360; - return radians * Math.PI / 180; - } - - /** - * Converts an angle in radians to degrees. - * - * @param radians angle in radians - * @return degrees between 0 and 360 degrees - */ - static double radiansToDegrees(double radians) { - double degrees = radians % (2 * Math.PI); - return degrees * 180 / Math.PI; - } - - /** - * 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; - } - - /** - * Returns a screen location that corresponds to a geographical coordinate (LatLng). - * The screen location is in screen pixels (not display pixels) relative to the top left - * of the map (not of the whole screen). - * - * @param location A LatLng on the map to convert to a screen location. - * @return A Point representing the screen location in screen pixels. - */ - @NonNull - public PointF toScreenLocation(@NonNull LatLng location) { - return nativeMapView.pixelForLatLng(location); - } - - float getHeight() { - return mapView.getHeight(); - } - - float getWidth() { - return mapView.getWidth(); - } - - /** - * Calculates a zoom level based on minimum scale and current scale from MapView - * - * @param minScale The minimum scale to calculate the zoom level. - * @return zoom level that fits the MapView. - */ - public double calculateZoom(float minScale) { - return nativeMapView.getZoom() + Math.log(minScale) / Math.log(2); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotationContainer.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotationContainer.java deleted file mode 100644 index 9c2b97b6a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotationContainer.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.RectF; -import android.support.annotation.NonNull; -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; - -import java.util.ArrayList; -import java.util.List; - -class ShapeAnnotationContainer implements ShapeAnnotations { - - private final NativeMap nativeMapView; - private final LongSparseArray annotations; - - ShapeAnnotationContainer(NativeMap nativeMapView, LongSparseArray annotations) { - this.nativeMapView = nativeMapView; - this.annotations = annotations; - } - - @NonNull - @Override - public List obtainAllIn(@NonNull RectF rectangle) { - RectF rect = nativeMapView.getDensityDependantRectangle(rectangle); - long[] annotationIds = nativeMapView.queryShapeAnnotations(rect); - return getAnnotationsFromIds(annotationIds); - } - - @NonNull - private List getAnnotationsFromIds(long[] annotationIds) { - List shapeAnnotations = new ArrayList<>(); - for (long annotationId : annotationIds) { - Annotation annotation = annotations.get(annotationId); - if (annotation != null) { - shapeAnnotations.add(annotation); - } - } - return shapeAnnotations; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotations.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotations.java deleted file mode 100644 index f9b2ca10d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/ShapeAnnotations.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.RectF; - -import com.mapbox.mapboxsdk.annotations.Annotation; - -import java.util.List; - -interface ShapeAnnotations { - - List obtainAllIn(RectF rectF); - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Style.java b/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Style.java deleted file mode 100644 index b21186050..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Style.java +++ /dev/null @@ -1,1150 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.os.AsyncTask; -import android.support.annotation.IntRange; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.annotation.StringDef; -import android.util.DisplayMetrics; -import android.util.Pair; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.layers.TransitionOptions; -import com.mapbox.mapboxsdk.style.light.Light; -import com.mapbox.mapboxsdk.style.sources.Source; -import com.mapbox.mapboxsdk.utils.BitmapUtils; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.ref.WeakReference; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * The proxy object for current map style. - *

- * To create new instances of this object, create a new instance using a {@link Builder} and load the style with - * MapboxMap. This object is returned from {@link MapboxMap#getStyle()} once the style - * has been loaded by underlying map. - *

- */ -@SuppressWarnings("unchecked") -public class Style { - - static final String EMPTY_JSON = "{\"version\": 8,\"sources\": {},\"layers\": []}"; - - private final NativeMap nativeMap; - private final HashMap sources = new HashMap<>(); - private final HashMap layers = new HashMap<>(); - private final HashMap images = new HashMap<>(); - private final Builder builder; - private boolean fullyLoaded; - - /** - * Private constructor to build a style object. - * - * @param builder the builder used for creating this style - * @param nativeMap the map object used to load this style - */ - private Style(@NonNull Builder builder, @NonNull NativeMap nativeMap) { - this.builder = builder; - this.nativeMap = nativeMap; - } - - /** - * Returns the current style url. - * - * @return the style url - * @deprecated use {@link #getUri()} instead - */ - @NonNull - @Deprecated - public String getUrl() { - validateState("getUrl"); - return nativeMap.getStyleUri(); - } - - /** - * Returns the current style uri. - * - * @return the style uri - */ - @NonNull - public String getUri() { - validateState("getUri"); - return nativeMap.getStyleUri(); - } - - /** - * Returns the current style json. - * - * @return the style json - */ - @NonNull - public String getJson() { - validateState("getJson"); - return nativeMap.getStyleJson(); - } - - // - // Source - // - - /** - * Retrieve all the sources in the style - * - * @return all the sources in the current style - */ - @NonNull - public List getSources() { - validateState("getSources"); - return nativeMap.getSources(); - } - - /** - * Adds the source to the map. The source must be newly created and not added to the map before - * - * @param source the source to add - */ - public void addSource(@NonNull Source source) { - validateState("addSource"); - nativeMap.addSource(source); - sources.put(source.getId(), source); - } - - /** - * Retrieve a source by id - * - * @param id the source's id - * @return the source if present in the current style - */ - @Nullable - public Source getSource(String id) { - validateState("getSource"); - Source source = sources.get(id); - if (source == null) { - source = nativeMap.getSource(id); - } - return source; - } - - /** - * Tries to cast the Source to T, throws ClassCastException if it's another type. - * - * @param sourceId the id used to look up a layer - * @param the generic type of a Source - * @return the casted Source, null if another type - */ - @Nullable - public T getSourceAs(@NonNull String sourceId) { - validateState("getSourceAs"); - // noinspection unchecked - if (sources.containsKey(sourceId)) { - return (T) sources.get(sourceId); - } - return (T) nativeMap.getSource(sourceId); - } - - /** - * Removes the source from the style. - * - * @param sourceId the source to remove - * @return the source handle or null if the source was not present - */ - public boolean removeSource(@NonNull String sourceId) { - validateState("removeSource"); - sources.remove(sourceId); - return nativeMap.removeSource(sourceId); - } - - /** - * Removes the source, preserving the reference for re-use - * - * @param source the source to remove - * @return the source - */ - public boolean removeSource(@NonNull Source source) { - validateState("removeSource"); - sources.remove(source.getId()); - return nativeMap.removeSource(source); - } - - // - // Layer - // - - /** - * Adds the layer to the map. The layer must be newly created and not added to the map before - * - * @param layer the layer to add - */ - public void addLayer(@NonNull Layer layer) { - validateState("addLayer"); - nativeMap.addLayer(layer); - layers.put(layer.getId(), layer); - } - - /** - * Adds the layer to the map. The layer must be newly created and not added to the map before - * - * @param layer the layer to add - * @param below the layer id to add this layer before - */ - public void addLayerBelow(@NonNull Layer layer, @NonNull String below) { - validateState("addLayerBelow"); - nativeMap.addLayerBelow(layer, below); - layers.put(layer.getId(), layer); - } - - /** - * Adds the layer to the map. The layer must be newly created and not added to the map before - * - * @param layer the layer to add - * @param above the layer id to add this layer above - */ - public void addLayerAbove(@NonNull Layer layer, @NonNull String above) { - validateState("addLayerAbove"); - nativeMap.addLayerAbove(layer, above); - layers.put(layer.getId(), layer); - } - - /** - * Adds the layer to the map at the specified index. The layer must be newly - * created and not added to the map before - * - * @param layer the layer to add - * @param index the index to insert the layer at - */ - public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) { - validateState("addLayerAbove"); - nativeMap.addLayerAt(layer, index); - layers.put(layer.getId(), layer); - } - - /** - * Get the layer by id - * - * @param id the layer's id - * @return the layer, if present in the style - */ - @Nullable - public Layer getLayer(@NonNull String id) { - validateState("getLayer"); - Layer layer = layers.get(id); - if (layer == null) { - layer = nativeMap.getLayer(id); - } - return layer; - } - - /** - * Tries to cast the Layer to T, throws ClassCastException if it's another type. - * - * @param layerId the layer id used to look up a layer - * @param the generic attribute of a Layer - * @return the casted Layer, null if another type - */ - @Nullable - public T getLayerAs(@NonNull String layerId) { - validateState("getLayerAs"); - // noinspection unchecked - return (T) nativeMap.getLayer(layerId); - } - - /** - * Retrieve all the layers in the style - * - * @return all the layers in the current style - */ - @NonNull - public List getLayers() { - validateState("getLayers"); - return nativeMap.getLayers(); - } - - /** - * Removes the layer. Any references to the layer become invalid and should not be used anymore - * - * @param layerId the layer to remove - * @return the removed layer or null if not found - */ - public boolean removeLayer(@NonNull String layerId) { - validateState("removeLayer"); - layers.remove(layerId); - return nativeMap.removeLayer(layerId); - } - - /** - * Removes the layer. The reference is re-usable after this and can be re-added - * - * @param layer the layer to remove - * @return the layer - */ - public boolean removeLayer(@NonNull Layer layer) { - validateState("removeLayer"); - layers.remove(layer.getId()); - return nativeMap.removeLayer(layer); - } - - /** - * Removes the layer. Any other references to the layer become invalid and should not be used anymore - * - * @param index the layer index - * @return the removed layer or null if not found - */ - public boolean removeLayerAt(@IntRange(from = 0) int index) { - validateState("removeLayerAt"); - return nativeMap.removeLayerAt(index); - } - - // - // Image - // - - /** - * Adds an image to be used in the map's style - * - * @param name the name of the image - * @param image the pre-multiplied Bitmap - */ - public void addImage(@NonNull String name, @NonNull Bitmap image) { - addImage(name, image, false); - } - - /** - * Adds an drawable to be converted into a bitmap to be used in the map's style - * - * @param name the name of the image - * @param drawable the drawable instance to convert - */ - public void addImage(@NonNull String name, @NonNull Drawable drawable) { - Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable); - if (bitmap == null) { - throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap."); - } - addImage(name, bitmap, false); - } - - /** - * Adds an image to be used in the map's style - * - * @param name the name of the image - * @param bitmap the pre-multiplied Bitmap - * @param sdf the flag indicating image is an SDF or template image - */ - public void addImage(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) { - validateState("addImage"); - nativeMap.addImages(new Image[]{toImage(new Builder.ImageWrapper(name, bitmap, sdf))}); - } - - /** - * Adds an image asynchronously, to be used in the map's style. - * - * @param name the name of the image - * @param image the pre-multiplied Bitmap - */ - public void addImageAsync(@NonNull String name, @NonNull Bitmap image) { - addImageAsync(name, image, false); - } - - /** - * Adds an drawable asynchronously, to be converted into a bitmap to be used in the map's style. - * - * @param name the name of the image - * @param drawable the drawable instance to convert - */ - public void addImageAsync(@NonNull String name, @NonNull Drawable drawable) { - Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable); - if (bitmap == null) { - throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap."); - } - addImageAsync(name, bitmap, false); - } - - /** - * Adds an image asynchronously, to be used in the map's style. - * - * @param name the name of the image - * @param bitmap the pre-multiplied Bitmap - * @param sdf the flag indicating image is an SDF or template image - */ - public void addImageAsync(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) { - validateState("addImage"); - new BitmapImageConversionTask(nativeMap).execute(new Builder.ImageWrapper(name, bitmap, sdf)); - } - - /** - * Adds images to be used in the map's style. - * - * @param images the map of images to add - */ - public void addImages(@NonNull HashMap images) { - addImages(images, false); - } - - /** - * Adds images to be used in the map's style. - * - * @param images the map of images to add - * @param sdf the flag indicating image is an SDF or template image - */ - public void addImages(@NonNull HashMap images, boolean sdf) { - validateState("addImage"); - Image[] convertedImages = new Image[images.size()]; - int index = 0; - for (Builder.ImageWrapper imageWrapper : Builder.ImageWrapper.convertToImageArray(images, sdf)) { - convertedImages[index] = toImage(imageWrapper); - index++; - } - - nativeMap.addImages(convertedImages); - } - - /** - * Adds images asynchronously, to be used in the map's style. - * - * @param images the map of images to add - */ - public void addImagesAsync(@NonNull HashMap images) { - addImagesAsync(images, false); - } - - /** - * Adds images asynchronously, to be used in the map's style. - * - * @param images the map of images to add - * @param sdf the flag indicating image is an SDF or template image - */ - public void addImagesAsync(@NonNull HashMap images, boolean sdf) { - validateState("addImages"); - new BitmapImageConversionTask(nativeMap).execute(Builder.ImageWrapper.convertToImageArray(images, sdf)); - } - - /** - * Removes an image from the map's style. - * - * @param name the name of the image to remove - */ - public void removeImage(@NonNull String name) { - validateState("removeImage"); - nativeMap.removeImage(name); - } - - /** - * Get an image from the map's style using an id. - * - * @param id the id of the image - * @return the image bitmap - */ - @Nullable - public Bitmap getImage(@NonNull String id) { - validateState("getImage"); - return nativeMap.getImage(id); - } - - // - // Transition - // - - /** - *

- * Set the transition options for style changes. - *

- * If not set, any changes take effect without animation, besides symbols, - * which will fade in/out with a default duration after symbol collision detection. - *

- * To disable symbols fade in/out animation, - * pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false. - *

- * Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay} - * will also change the behavior of the symbols fade in/out animation if the placement transition is enabled. - * - * @param transitionOptions the transition options - */ - public void setTransition(@NonNull TransitionOptions transitionOptions) { - validateState("setTransition"); - nativeMap.setTransitionOptions(transitionOptions); - } - - /** - *

- * Get the transition options for style changes. - *

- * By default, any changes take effect without animation, besides symbols, - * which will fade in/out with a default duration after symbol collision detection. - *

- * To disable symbols fade in/out animation, - * pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false - * into {@link #setTransition(TransitionOptions)}. - *

- * Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay} - * will also change the behavior of the symbols fade in/out animation if the placement transition is enabled. - * - * @return TransitionOptions the transition options - */ - @NonNull - public TransitionOptions getTransition() { - validateState("getTransition"); - return nativeMap.getTransitionOptions(); - } - - // - // Light - // - - /** - * Get the light source used to change lighting conditions on extruded fill layers. - * - * @return the global light source - */ - @Nullable - public Light getLight() { - validateState("getLight"); - return nativeMap.getLight(); - } - - // - // State - // - - /** - * Called when the underlying map will start loading a new style or the map is destroyed. - * This method will clean up this style by setting the java sources and layers - * in a detached state and removing them from core. - */ - void clear() { - fullyLoaded = false; - for (Layer layer : layers.values()) { - if (layer != null) { - layer.setDetached(); - } - } - - for (Source source : sources.values()) { - if (source != null) { - source.setDetached(); - } - } - - for (Map.Entry bitmapEntry : images.entrySet()) { - nativeMap.removeImage(bitmapEntry.getKey()); - bitmapEntry.getValue().recycle(); - } - - sources.clear(); - layers.clear(); - images.clear(); - } - - /** - * Called when the underlying map has finished loading this style. - * This method will add all components added to the builder that were defined with the 'with' prefix. - */ - void onDidFinishLoadingStyle() { - if (!fullyLoaded) { - fullyLoaded = true; - for (Source source : builder.sources) { - addSource(source); - } - - for (Builder.LayerWrapper layerWrapper : builder.layers) { - if (layerWrapper instanceof Builder.LayerAtWrapper) { - addLayerAt(layerWrapper.layer, ((Builder.LayerAtWrapper) layerWrapper).index); - } else if (layerWrapper instanceof Builder.LayerAboveWrapper) { - addLayerAbove(layerWrapper.layer, ((Builder.LayerAboveWrapper) layerWrapper).aboveLayer); - } else if (layerWrapper instanceof Builder.LayerBelowWrapper) { - addLayerBelow(layerWrapper.layer, ((Builder.LayerBelowWrapper) layerWrapper).belowLayer); - } else { - // just add layer to map, but below annotations - addLayerBelow(layerWrapper.layer, MapboxConstants.LAYER_ID_ANNOTATIONS); - } - } - - for (Builder.ImageWrapper image : builder.images) { - addImage(image.id, image.bitmap, image.sdf); - } - - if (builder.transitionOptions != null) { - setTransition(builder.transitionOptions); - } - } - } - - /** - * Returns true if the style is fully loaded. Returns false if style hasn't been fully loaded or a new style is - * underway of being loaded. - * - * @return True if fully loaded, false otherwise - */ - public boolean isFullyLoaded() { - return fullyLoaded; - } - - /** - * Validates the style state, throw an IllegalArgumentException on invalid state. - * - * @param methodCall the calling method name - */ - private void validateState(String methodCall) { - if (!fullyLoaded) { - throw new IllegalStateException( - String.format("Calling %s when a newer style is loading/has loaded.", methodCall) - ); - } - } - - // - // Builder - // - - /** - * Builder for composing a style object. - */ - public static class Builder { - - private final List sources = new ArrayList<>(); - private final List layers = new ArrayList<>(); - private final List images = new ArrayList<>(); - - private TransitionOptions transitionOptions; - private String styleUri; - private String styleJson; - - /** - *

- * Will loads a new map style asynchronous from the specified URL. - *

- * {@code url} can take the following forms: - *
    - *
  • {@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.
  • - *
  • {@code mapbox://styles// - \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/AccountsManagerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/AccountsManagerTest.java deleted file mode 100644 index 5ce71ceac..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/AccountsManagerTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.content.SharedPreferences; -import android.text.format.DateUtils; - -import org.junit.Test; - -import static com.mapbox.mapboxsdk.constants.MapboxConstants.KEY_PREFERENCE_SKU_TOKEN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class AccountsManagerTest { - @Test - public void testIsExpired() { - long now = AccountsManager.getNow(); - - long defaultValue = 0L; - long tooOld = now - DateUtils.HOUR_IN_MILLIS - 1; - long futureValue = now + 1; - long immediatePast = now - 1; - - assertTrue(AccountsManager.isExpired(now, defaultValue)); - assertTrue(AccountsManager.isExpired(now, tooOld)); - - assertFalse(AccountsManager.isExpired(now, futureValue)); - assertFalse(AccountsManager.isExpired(now, immediatePast)); - } - - @Test - public void checksSkuTokenExternalManagement() { - SharedPreferences mockedSharedPreferences = mock(SharedPreferences.class); - when(mockedSharedPreferences.getString(KEY_PREFERENCE_SKU_TOKEN, "")).thenReturn("external-sku-token"); - boolean isNotManaged = false; - AccountsManager theAccountsManager = new AccountsManager(mockedSharedPreferences, isNotManaged); - - String skuToken = theAccountsManager.getSkuToken(); - - assertEquals("external-sku-token", skuToken); - } - - @Test - public void checksSkuTokenInternalManagement() { - SharedPreferences mockedSharedPreferences = mock(SharedPreferences.class, RETURNS_DEEP_STUBS); - when(mockedSharedPreferences.getString("com.mapbox.mapboxsdk.accounts.userid", "")) - .thenReturn("any-user-id"); - boolean isManaged = true; - AccountsManager theAccountsManager = new AccountsManager(mockedSharedPreferences, isManaged); - - String skuToken = theAccountsManager.getSkuToken(); - - assertFalse(skuToken.isEmpty()); - assertTrue(skuToken.startsWith("100")); - assertTrue(skuToken.endsWith("any-user-id")); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxInjector.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxInjector.java deleted file mode 100644 index 966c75631..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxInjector.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.content.Context; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; - -import java.lang.reflect.Field; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MapboxInjector { - - private static final String FIELD_INSTANCE = "INSTANCE"; - private static final String FIELD_ACCOUNTS = "accounts"; - - public static void inject(@NonNull Context context, @NonNull String accessToken) { - inject(context, accessToken, null); - } - - public static void inject(@NonNull Context context, @NonNull String accessToken, @Nullable String skuToken) { - Mapbox mapbox = new Mapbox(context, accessToken); - try { - Field instance = Mapbox.class.getDeclaredField(FIELD_INSTANCE); - instance.setAccessible(true); - instance.set(mapbox, mapbox); - - Field accounts = Mapbox.class.getDeclaredField(FIELD_ACCOUNTS); - accounts.setAccessible(true); - - AccountsManager manager = mock(AccountsManager.class); - when(manager.getSkuToken()).thenReturn(skuToken); - accounts.set(mapbox, manager); - } catch (Exception exception) { - throw new AssertionError(); - } - } - - public static void clear() { - try { - Field field = Mapbox.class.getDeclaredField(FIELD_INSTANCE); - field.setAccessible(true); - field.set(field, null); - } catch (Exception exception) { - throw new AssertionError(); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxTest.java deleted file mode 100644 index a4b573672..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/MapboxTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.mapbox.mapboxsdk; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.util.DisplayMetrics; - -import com.mapbox.mapboxsdk.exceptions.MapboxConfigurationException; -import com.mapbox.mapboxsdk.maps.MapView; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static junit.framework.TestCase.assertNotNull; -import static junit.framework.TestCase.assertSame; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MapboxTest { - - private Context context; - private Context appContext; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void before() { - context = mock(Context.class); - appContext = mock(Context.class); - when(context.getApplicationContext()).thenReturn(appContext); - } - - @Test - public void testGetAccessToken() { - final String accessToken = "pk.0000000001"; - MapboxInjector.inject(context, accessToken); - assertSame(accessToken, Mapbox.getAccessToken()); - } - - @Test - public void testApplicationContext() { - MapboxInjector.inject(context, "pk.0000000001"); - assertNotNull(Mapbox.getApplicationContext()); - assertNotEquals(context, appContext); - assertEquals(appContext, appContext); - } - - @Test - public void testPkTokenValid() { - assertTrue(Mapbox.isAccessTokenValid("pk.0000000001")); - } - - @Test - public void testSkTokenValid() { - assertTrue(Mapbox.isAccessTokenValid("sk.0000000001")); - } - - @Test - public void testEmptyToken() { - assertFalse(Mapbox.isAccessTokenValid("")); - } - - @Test - public void testNullToken() { - assertFalse(Mapbox.isAccessTokenValid(null)); - } - - @Test - public void testBlaBlaToken() { - assertFalse(Mapbox.isAccessTokenValid("blabla")); - } - - @Test - public void testNoInstance() { - DisplayMetrics displayMetrics = mock(DisplayMetrics.class); - Resources resources = mock(Resources.class); - when(resources.getDisplayMetrics()).thenReturn(displayMetrics); - when(context.getResources()).thenReturn(resources); - TypedArray typedArray = mock(TypedArray.class); - when(context.obtainStyledAttributes(nullable(AttributeSet.class), any(int[].class), anyInt(), anyInt())) - .thenReturn(typedArray); - - expectedException.expect(MapboxConfigurationException.class); - expectedException.expectMessage( - "\nUsing MapView requires calling Mapbox.getInstance(Context context, String accessToken) before " - + "inflating or creating the view. The access token parameter is required when using a Mapbox service." - + "\nPlease see https://www.mapbox.com/help/create-api-access-token/ to learn how to create one." - + "\nMore information in this guide https://www.mapbox.com/help/first-steps-android-sdk/#access-tokens." - ); - new MapView(context); - } - - @After - public void after() { - MapboxInjector.clear(); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java deleted file mode 100644 index 0c61b01be..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/AnnotationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.maps.MapboxMap; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -public class AnnotationTest { - - @InjectMocks - private MapboxMap mapboxMap = mock(MapboxMap.class); - private Annotation annotation; - @NonNull - private Annotation compare = new Annotation() { - @Override - public long getId() { - return 1; - } - }; - - @Before - public void beforeTest() { - annotation = new Annotation() { - // empty child - }; - } - - @Test - public void testSanity() { - assertNotNull("markerOptions should not be null", annotation); - } - - @Test - public void testRemove() { - annotation.setId(1); - annotation.setMapboxMap(mapboxMap); - annotation.remove(); - verify(mapboxMap, times(1)).removeAnnotation(annotation); - } - - @Test - public void testRemoveUnboundMapboxMap() { - annotation.setId(1); - annotation.remove(); - verify(mapboxMap, times(0)).removeAnnotation(annotation); - } - - @Test - public void testCompareToEqual() { - annotation.setId(1); - assertEquals("conparable equal", 0, annotation.compareTo(compare)); - } - - @Test - public void testCompareToHigher() { - annotation.setId(3); - assertEquals("conparable higher", -1, annotation.compareTo(compare)); - } - - @Test - public void testCompareTolower() { - annotation.setId(0); - assertEquals("conparable lower", 1, annotation.compareTo(compare)); - } - - @Test - public void testEquals() { - Annotation holder = null; - assertFalse(annotation.equals(holder)); - holder = annotation; - assertTrue(annotation.equals(holder)); - assertFalse(annotation.equals(new Object())); - } - - @Test - public void testHashcode() { - int id = 1; - annotation.setId(id); - assertSame("hashcode should match", annotation.hashCode(), id); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java deleted file mode 100644 index e56ca559d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/IconTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotSame; -import static org.mockito.Mockito.when; - -public class IconTest { - - @Mock - Bitmap bitmap; - - @Before - public void beforeTest() { - MockitoAnnotations.initMocks(this); - when(bitmap.getConfig()).thenReturn(Bitmap.Config.ARGB_8888); - } - - @Test - public void testId() { - String id = "test"; - Icon icon = IconFactory.recreate(id, Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)); - assertEquals("id should match", id, icon.getId()); - } - - @Test - public void testBitmap() { - Icon icon = IconFactory.recreate("test", bitmap); - assertEquals("bitmap should match", bitmap, icon.getBitmap()); - } - - @Test - public void testEquals() { - Icon icon1 = IconFactory.recreate("test", bitmap); - Icon icon2 = IconFactory.recreate("test", bitmap); - assertEquals("icons should not match", icon1, icon2); - } - - @Test - public void testEqualsObject() { - Icon icon = IconFactory.recreate("test", Bitmap.createBitmap(0, 0, Bitmap.Config.ALPHA_8)); - assertNotSame("icon should not match", new Object(), icon); - } - - @Test - public void testHashcode() { - Icon icon = IconFactory.recreate("test", bitmap); - long expectedHashcode = 31 * bitmap.hashCode() + "test".hashCode(); - assertEquals("hashcode should match", expectedHashcode, icon.hashCode()); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java deleted file mode 100644 index 94b629860..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.PointF; - -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapView; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; - -import org.junit.Test; -import org.mockito.InjectMocks; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class InfoWindowTest { - - @InjectMocks - MapView mMapView = mock(MapView.class); - - @InjectMocks - MapboxMap mMapboxMap = mock(MapboxMap.class); - - @Test - public void testSanity() { - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - assertNotNull("infoWindow should exist", infoWindow); - } - - @Test - public void testBoundMarker() { - MarkerOptions markerOptions = new MarkerOptions(); - Marker marker = markerOptions.position(new LatLng()).getMarker(); - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap).setBoundMarker(marker); - assertEquals("marker should match", marker, infoWindow.getBoundMarker()); - } - - @Test - public void testClose() { - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.close(); - assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); - } - - - @Test - public void testOpen() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); - assertEquals("infowindow should not be visible", true, infoWindow.isVisible()); - } - - @Test - public void testOpenClose() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); - infoWindow.close(); - assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); - } - - - @Test - public void testUpdate() { - LatLng latLng = new LatLng(0, 0); - Projection projection = mock(Projection.class); - when(mMapboxMap.getProjection()).thenReturn(projection); - when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); - - InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); - infoWindow.open(mMapView, new MarkerOptions().position(latLng).getMarker(), latLng, 0, 0); - infoWindow.update(); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java deleted file mode 100644 index fa571e06b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/MarkerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import android.graphics.Bitmap; -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.exceptions.InvalidMarkerPositionException; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; - -public class MarkerTest { - - @Test - public void testSanity() { - MarkerOptions markerOptions = new MarkerOptions(); - assertNotNull("markerOptions should not be null", markerOptions); - } - - @Test - public void testMarker() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()); - assertNotNull("marker should not be null", markerOptions.getMarker()); - } - - @Test(expected = InvalidMarkerPositionException.class) - public void testInvalidMarker() { - new MarkerOptions().getMarker(); - } - - @Test - public void testPosition() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(10, 12)); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getPosition(), new LatLng(10, 12)); - assertEquals(markerOptions.getPosition(), new LatLng(10, 12)); - } - - @Test - public void testTitle() { - MarkerOptions markerOptions = new MarkerOptions().title("Mapbox").position(new LatLng()); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getTitle(), "Mapbox"); - assertEquals(markerOptions.getTitle(), "Mapbox"); - } - - @Test - public void testSnippet() { - MarkerOptions markerOptions = new MarkerOptions().snippet("Mapbox").position(new LatLng()); - Marker marker = markerOptions.getMarker(); - assertEquals(marker.getSnippet(), "Mapbox"); - } - - @Test - public void testBuilder() { - Marker marker = new MarkerOptions().title("title").snippet("snippet").position(new LatLng(10, 12)).getMarker(); - assertEquals(marker.getSnippet(), "snippet"); - - assertEquals(marker.getPosition(), new LatLng(10, 12)); - } - - @Test - public void testIcon() { - Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_4444); - Icon icon = IconFactory.recreate("test", bitmap); - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()).icon(icon); - Marker marker = markerOptions.getMarker(); - assertEquals("Icon should match", icon, marker.getIcon()); - assertEquals("Icon should match", icon, markerOptions.getIcon()); - } - - @Test - public void testHashCode() { - Marker marker = new MarkerOptions().position(new LatLng()).getMarker(); - assertEquals("hash code should match", marker.hashCode(), 0); - } - - @Test - public void testHashCodeBuilder() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(10, 12)); - assertEquals("hash code should match", markerOptions.hashCode(), 579999617); - } - - @Test - public void testEquals() { - Marker markerOne = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - Marker markerTwo = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - assertEquals(markerOne, markerTwo); - } - - @Test - public void testEqualityDifferentLocation() { - MarkerOptions marker = new MarkerOptions().position(new LatLng(0, 0)); - MarkerOptions other = new MarkerOptions().position(new LatLng(1, 0)); - assertNotEquals("Should not match", other, marker); - } - - - @Test - public void testEqualityDifferentSnippet() { - MarkerOptions marker = new MarkerOptions().snippet("s"); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualityDifferentIcon() { - MarkerOptions marker = new MarkerOptions().icon(mock(Icon.class)); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualityDifferentTitle() { - MarkerOptions marker = new MarkerOptions().title("t"); - MarkerOptions other = new MarkerOptions(); - assertNotEquals("Should not match", other, marker); - } - - @Test - public void testEqualsItself() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(0, 0)); - Marker marker = markerOptions.getMarker(); - assertEquals("Marker should match", marker, marker); - assertEquals("MarkerOptions should match", markerOptions, markerOptions); - } - - @Test - public void testNotEquals() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(0, 0)); - Marker marker = markerOptions.getMarker(); - assertNotEquals("MarkerOptions should match", markerOptions, new Object()); - assertNotEquals("Marker should match", marker, new Object()); - } - - @Test - public void testEqualityBuilder() { - MarkerOptions markerOne = new MarkerOptions().position(new LatLng(0, 0)); - MarkerOptions markerTwo = new MarkerOptions().position(new LatLng(0, 0)); - assertEquals(markerOne, markerTwo); - } - - @Test - public void testToString() { - Marker marker = new MarkerOptions().position(new LatLng(0, 0)).getMarker(); - assertEquals(marker.toString(), "Marker [position[" + "LatLng [latitude=0.0, longitude=0.0, altitude=0.0]" + "]]"); - } - - @Test - public void testParcelable() { - MarkerOptions markerOptions = new MarkerOptions().position(new LatLng()).title("t").snippet("s"); - Parcelable parcelable = MockParcel.obtain(markerOptions); - assertEquals("Parcel should match original object", parcelable, markerOptions); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java deleted file mode 100644 index 3933c6888..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolygonTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class PolygonTest { - - @Test - public void testSanity() { - PolygonOptions polygonOptions = new PolygonOptions(); - assertNotNull("polygonOptions should not be null", polygonOptions); - } - - @Test - public void testPolygon() { - Polygon polygon = new PolygonOptions().getPolygon(); - assertNotNull("polyline should not be null", polygon); - } - - @Test - public void testAlpha() { - Polygon polygon = new PolygonOptions().alpha(0.5f).getPolygon(); - assertEquals(0.5f, polygon.getAlpha(), 0.0f); - } - - @Test - public void testStrokeColor() { - Polygon polygon = new PolygonOptions().strokeColor(1).getPolygon(); - assertEquals(1, polygon.getStrokeColor()); - } - - @Test - public void testFillColor() { - Polygon polygon = new PolygonOptions().fillColor(1).getPolygon(); - assertEquals(1, polygon.getFillColor()); - } - - @Test - public void testLatLng() { - Polygon polygon = new PolygonOptions().add(new LatLng(0, 0)).getPolygon(); - assertNotNull("points should not be null", polygon.getPoints()); - assertEquals(new LatLng(0, 0), polygon.getPoints().get(0)); - } - - @Test - public void testAddAllLatLng() { - List coordinates = new ArrayList<>(); - coordinates.add(new LatLng(0, 0)); - Polygon polygon = new PolygonOptions().addAll(coordinates).getPolygon(); - assertNotNull(polygon.getPoints()); - assertEquals(new LatLng(0, 0), polygon.getPoints().get(0)); - } - - @Test - public void testBuilder() { - PolylineOptions polylineOptions = new PolylineOptions(); - polylineOptions.width(1.0f); - polylineOptions.color(2); - polylineOptions.add(new LatLng(0, 0)); - - Polyline polyline = polylineOptions.getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - assertEquals(2, polyline.getColor()); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java deleted file mode 100644 index 54bb0e8cf..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/PolylineTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.mapbox.mapboxsdk.annotations; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class PolylineTest { - - @Test - public void testSanity() { - PolylineOptions polylineOptions = new PolylineOptions(); - assertNotNull("polylineOptions should not be null", polylineOptions); - } - - @Test - public void testPolyline() { - Polyline polyline = new PolylineOptions().getPolyline(); - assertNotNull("polyline should not be null", polyline); - } - - @Test - public void testAlpha() { - Polyline polyline = new PolylineOptions().alpha(0.2f).getPolyline(); - assertEquals(0.2f, polyline.getAlpha(), 0.0f); - } - - @Test - public void testWidth() { - Polyline polyline = new PolylineOptions().width(1).getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - } - - @Test - public void testColor() { - Polyline polyline = new PolylineOptions().color(1).getPolyline(); - assertEquals(1, polyline.getColor()); - } - - @Test - public void testAddLatLng() { - Polyline polyline = new PolylineOptions().add(new LatLng(0, 0)).getPolyline(); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - - @Test - public void testAddAllLatLng() { - List coordinates = new ArrayList<>(); - coordinates.add(new LatLng(0, 0)); - Polyline polyline = new PolylineOptions().addAll(coordinates).getPolyline(); - assertNotNull(polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - - @Test - public void testBuilder() { - PolylineOptions polylineOptions = new PolylineOptions(); - polylineOptions.width(1.0f); - polylineOptions.color(2); - polylineOptions.add(new LatLng(0, 0)); - - Polyline polyline = polylineOptions.getPolyline(); - assertEquals(1.0f, polyline.getWidth(), 0); - assertEquals(2, polyline.getColor()); - assertNotNull("Points should not be null", polyline.getPoints()); - assertEquals(new LatLng(0, 0), polyline.getPoints().get(0)); - } - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java deleted file mode 100644 index b72e85270..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/attribution/AttributionParseTest.java +++ /dev/null @@ -1,322 +0,0 @@ -package com.mapbox.mapboxsdk.attribution; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - -import java.util.Set; - -import static junit.framework.Assert.assertEquals; - -@RunWith(RobolectricTestRunner.class) -public class AttributionParseTest { - - private static final String STREETS_ATTRIBUTION = "© Mapbox © OpenStreetMap Improve this map\n"; - private static final String SATELLITE_ATTRIBUTION = "© Mapbox © OpenStreetMap Improve this map © DigitalGlobe\n"; - - @Test - public void testParseAttributionStringSatellite() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(SATELLITE_ATTRIBUTION) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 4, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL improve map should match", "https://apps.mapbox.com/feedback/", attribution.getUrl()); - assertEquals("Title improve map should match", "Improve This Map", attribution.getTitle()); - break; - case 3: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionStringStreets() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL improve map should match", "https://apps.mapbox.com/feedback/", attribution.getUrl()); - assertEquals("Title improve map should match", "Improve This Map", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionWithoutMapbox() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withMapboxAttribution(false) - .build(); - - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 2, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 1: - assertEquals("URL improve map should match", "https://apps.mapbox.com/feedback/", attribution.getUrl()); - assertEquals("Title improve map should match", "Improve This Map", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(new String[] {STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION}) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 4, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL improve map should match", "https://apps.mapbox.com/feedback/", attribution.getUrl()); - assertEquals("Title improve map should match", "Improve This Map", attribution.getTitle()); - break; - case 3: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testHideImproveThisMapAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(SATELLITE_ATTRIBUTION) - .withImproveMap(false) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 3, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "© Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "© OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "© DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testParseHideCopyrightAttributionArrayString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, "", SATELLITE_ATTRIBUTION) - .withCopyrightSign(false) - .build(); - Set attributionList = attributionParser.getAttributions(); - assertEquals("Size of list should match", 4, attributionList.size()); - - int counter = 0; - for (Attribution attribution : attributionList) { - switch (counter) { - case 0: - assertEquals("URL mapbox should match", "https://www.mapbox.com/about/maps/", attribution.getUrl()); - assertEquals("Title mapbox should match", "Mapbox", attribution.getTitle()); - break; - case 1: - assertEquals("URL openstreetmap should match", "http://www.openstreetmap.org/about/", attribution.getUrl()); - assertEquals("Title openstreetmap should match", "OpenStreetMap", attribution.getTitle()); - break; - case 2: - assertEquals("URL improve map should match", "https://apps.mapbox.com/feedback/", attribution.getUrl()); - assertEquals("Title improve map should match", "Improve This Map", attribution.getTitle()); - break; - case 3: - assertEquals("URL digital globe should match", "https://www.digitalglobe.com/", attribution.getUrl()); - assertEquals("Title digital globe should match", "DigitalGlobe", attribution.getTitle()); - break; - } - counter++; - } - } - - @Test - public void testOutputWithoutCopyRightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withCopyrightSign(false) - .withImproveMap(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - - @Test - public void testOutputWithCopyRightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withImproveMap(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / © OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputWithoutCopyRightWithoutMapboxString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withCopyrightSign(false) - .withImproveMap(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputWithCopyRightWithoutMapboxString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION) - .withImproveMap(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap", - attributionParser.createAttributionString() - ); - } - - @Test - public void testOutputSatelliteString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OpenStreetMap / DigitalGlobe", - attributionParser.createAttributionString() - ); - } - - @Test - public void testShortOpenStreetMapString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .withMapboxAttribution(false) - .build(); - - assertEquals( - "Attribution string should match", - "© OSM / DigitalGlobe", - attributionParser.createAttributionString(true) - ); - } - - @Test - public void testShortOpenStreetMapWithoutCopyrightString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, SATELLITE_ATTRIBUTION, "blabla", "") - .withImproveMap(false) - .withCopyrightSign(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / OSM / DigitalGlobe", - attributionParser.createAttributionString(true) - ); - } - - @Test - public void testWithImproveThisMapString() throws Exception { - AttributionParser attributionParser = new AttributionParser.Options(RuntimeEnvironment.application) - .withAttributionData(STREETS_ATTRIBUTION, "blabla", "") - .withImproveMap(true) - .withCopyrightSign(false) - .build(); - - assertEquals( - "Attribution string should match", - "© Mapbox / OSM / Improve This Map", - attributionParser.createAttributionString(true) - ); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java deleted file mode 100644 index dcf84c87b..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/camera/CameraPositionTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.mapbox.mapboxsdk.camera; - -import android.content.res.TypedArray; -import android.os.Parcel; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@RunWith(RobolectricTestRunner.class) -public class CameraPositionTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertNotNull("cameraPosition should not be null", cameraPosition); - } - - @Test - public void testDefaultTypedArrayBuilder() { - TypedArray typedArray = null; - CameraPosition cameraPosition = new CameraPosition.Builder(typedArray).build(); - assertEquals("bearing should match", -1, cameraPosition.bearing, DELTA); - assertNull("latlng should be null", cameraPosition.target); - assertEquals("tilt should match", -1, cameraPosition.tilt, DELTA); - assertEquals("zoom should match", -1, cameraPosition.zoom, DELTA); - assertNull("padding should be null", cameraPosition.padding); - } - - @Test - public void testTypedArrayBuilder() { - float bearing = 180; - float zoom = 12; - float latitude = 10; - float longitude = 11; - float tilt = 44; - - TypedArray typedArray = mock(TypedArray.class); - when(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraBearing, 0.0f)).thenReturn(bearing); - when(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTargetLat, 0.0f)).thenReturn(latitude); - when(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTargetLng, 0.0f)).thenReturn(longitude); - when(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraZoom, 0.0f)).thenReturn(zoom); - when(typedArray.getFloat(R.styleable.mapbox_MapView_mapbox_cameraTilt, 0.0f)).thenReturn(tilt); - doNothing().when(typedArray).recycle(); - - CameraPosition cameraPosition = new CameraPosition.Builder(typedArray).build(); - assertEquals("bearing should match", bearing, cameraPosition.bearing, DELTA); - assertEquals("latlng should match", new LatLng(latitude, longitude), cameraPosition.target); - assertEquals("tilt should match", tilt, cameraPosition.tilt, DELTA); - assertEquals("zoom should match", zoom, cameraPosition.zoom, DELTA); - } - - @Test - public void testToString() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertEquals("toString should match", "Target: LatLng [latitude=1.0, longitude=2.0, altitude=0.0], Zoom:3.0, " - + "Bearing:5.0, Tilt:4.0, Padding:[0.0, 500.0, 0.0, 0.0]", cameraPosition.toString()); - } - - @Test - public void testHashcode() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - assertEquals("hashCode should match", -420915327, cameraPosition.hashCode()); - } - - @Test - public void testZoomUpdateBuilder() { - float zoomLevel = 5; - CameraPosition.Builder builder = new CameraPosition.Builder( - (CameraUpdateFactory.ZoomUpdate) CameraUpdateFactory.zoomTo(zoomLevel)); - assertEquals("zoom should match", zoomLevel, builder.build().zoom, 0); - } - - @Test - public void testEquals() { - LatLng latLng = new LatLng(1, 2); - CameraPosition cameraPosition = new CameraPosition(latLng, 3, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionBearing = new CameraPosition(latLng, 3, 4, 9, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionTilt = new CameraPosition(latLng, 3, 9, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionZoom = new CameraPosition(latLng, 9, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionTarget = new CameraPosition(new LatLng(), 3, 4, 5, new double[] {0, 500, 0, 0}); - CameraPosition cameraPositionPadding = new CameraPosition(new LatLng(), 3, 4, 5, new double[] {0, 501, 0, 0}); - - assertEquals("cameraPosition should match itself", cameraPosition, cameraPosition); - assertNotEquals("cameraPosition should not match null", null, cameraPosition); - assertNotEquals("cameraPosition should not match object", new Object(), cameraPosition); - assertNotEquals("cameraPosition should not match for bearing", cameraPositionBearing, cameraPosition); - assertNotEquals("cameraPosition should not match for tilt", cameraPositionTilt, cameraPosition); - assertNotEquals("cameraPosition should not match for zoom", cameraPositionZoom, cameraPosition); - assertNotEquals("cameraPosition should not match for target", cameraPositionTarget, cameraPosition); - assertNotEquals("cameraPosition should not match for padding", cameraPositionPadding, cameraPosition); - } - - @Test - public void testParcelable() { - CameraPosition cameraPosition1 = new CameraPosition(new LatLng(1, 2), 3, 4, 5, new double[] {0, 500, 0, 0}); - Parcel parcel = Parcel.obtain(); - cameraPosition1.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - CameraPosition cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel); - assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2); - } - - @Test - public void testParcelableNulls() { - CameraPosition cameraPosition1 = new CameraPosition(null, 3, 4, 5, null); - Parcel parcel = Parcel.obtain(); - cameraPosition1.writeToParcel(parcel, 0); - parcel.setDataPosition(0); - - CameraPosition cameraPosition2 = CameraPosition.CREATOR.createFromParcel(parcel); - assertEquals("Parcel should match original object", cameraPosition1, cameraPosition2); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java deleted file mode 100644 index cb654aa55..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/constants/AppConstant.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.mapbox.mapboxsdk.constants; - -public class AppConstant { - - public static final int STYLE_VERSION = 9; -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java deleted file mode 100644 index 6c44c29e3..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngBoundsTest.java +++ /dev/null @@ -1,813 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; -import com.mapbox.mapboxsdk.constants.GeometryConstants; -import com.mapbox.mapboxsdk.exceptions.InvalidLatLngBoundsException; -import com.mapbox.mapboxsdk.utils.MockParcel; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.util.ArrayList; -import java.util.List; - -import static junit.framework.Assert.assertNotNull; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class LatLngBoundsTest { - - private static final double DELTA = 1e-15; - - private LatLngBounds latLngBounds; - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - private static final LatLng LAT_LNG_NOT_NULL_ISLAND = new LatLng(2, 2); - - @Before - public void beforeTest() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - } - - @Test - public void testSanity() { - LatLngBounds.Builder latLngBoundsBuilder = new LatLngBounds.Builder(); - latLngBoundsBuilder.include(LAT_LNG_NULL_ISLAND).include(LAT_LNG_NOT_NULL_ISLAND); - assertNotNull("latLng should not be null", latLngBoundsBuilder.build()); - } - - @Test(expected = InvalidLatLngBoundsException.class) - public void noLatLngs() { - new LatLngBounds.Builder().build(); - } - - @Test(expected = InvalidLatLngBoundsException.class) - public void oneLatLngs() { - new LatLngBounds.Builder().include(LAT_LNG_NULL_ISLAND).build(); - } - - @Test - public void latitiudeSpan() { - assertEquals("Span should be the same", 2, latLngBounds.getLatitudeSpan(), DELTA); - } - - @Test - public void longitudeSpan() { - assertEquals("Span should be the same", 2, latLngBounds.getLongitudeSpan(), DELTA); - } - - @Test - public void coordinateSpan() { - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(2, 2), latLngSpan); - } - - @Test - public void dateLineSpanBuilder1() { - latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -170)) - .include(new LatLng(-10, 170)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void dateLineSpanBuilder2() { - latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(-10, -170)) - .include(new LatLng(10, 170)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void dateLineSpanFrom1() { - latLngBounds = LatLngBounds.from(10, -170, -10, -190); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 20), - latLngSpan); - } - - @Test - public void dateLineSpanFrom2() { - latLngBounds = LatLngBounds.from(10, 170, -10, -170); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", new LatLngSpan(20, 340), - latLngSpan); - } - - @Test - public void zeroLongitudeSpan() { - latLngBounds = LatLngBounds.from(10, 10, -10, 10); - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be shortest distance", new LatLngSpan(20, 0), - latLngSpan); - } - - @Test - public void nearDateLineCenter1() { - latLngBounds = LatLngBounds.from(10, -175, -10, -195); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, -185), center); - } - - @Test - public void nearDateLineCenter2() { - latLngBounds = LatLngBounds.from(10, 195, -10, 175); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 185), center); - } - - @Test - public void nearDateLineCenter3() { - latLngBounds = LatLngBounds.from(10, -170, -10, -190); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, -180), center); - } - - @Test - public void nearDateLineCenter4() { - latLngBounds = LatLngBounds.from(10, 180, -10, 0); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 90), center); - } - - @Test - public void nearDateLineCenter5() { - latLngBounds = LatLngBounds.from(10, 180, -10, 0); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 90), center); - } - - @Test - public void centerForBoundsWithSameLongitude() { - latLngBounds = LatLngBounds.from(10, 10, -10, 10); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(0, 10), center); - } - - @Test - public void centerForBoundsWithSameLatitude() { - latLngBounds = LatLngBounds.from(10, 10, 10, -10); - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(10, 0), center); - } - - @Test - public void center() { - LatLng center = latLngBounds.getCenter(); - assertEquals("Center should match", new LatLng(1, 1), center); - } - - @Test - public void notEmptySpan() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertFalse("Should not be empty", latLngBounds.isEmptySpan()); - } - - @Test - public void includeSameLatLngs() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals(latLngBounds.getNorthEast(), LAT_LNG_NOT_NULL_ISLAND); - assertEquals(latLngBounds.getSouthWest(), LAT_LNG_NULL_ISLAND); - } - - @Test - public void toLatLngs() { - latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NOT_NULL_ISLAND) - .include(LAT_LNG_NULL_ISLAND) - .build(); - - assertArrayEquals("LatLngs should match", - new LatLng[] {LAT_LNG_NOT_NULL_ISLAND, LAT_LNG_NULL_ISLAND}, - latLngBounds.toLatLngs()); - } - - @Test - public void include() { - assertTrue("LatLng should be included", latLngBounds.contains(new LatLng(1, 1))); - } - - @Test - public void includes() { - List points = new ArrayList<>(); - points.add(LAT_LNG_NULL_ISLAND); - points.add(LAT_LNG_NOT_NULL_ISLAND); - - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .includes(points) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - - assertEquals("LatLngBounds should match", latLngBounds1, latLngBounds2); - } - - @Test - public void includesOrderDoesNotMatter() { - LatLngBounds sameLongitudeFirst = new LatLngBounds.Builder() - .include(new LatLng(50, 10)) // southWest - .include(new LatLng(60, 10)) - .include(new LatLng(60, 20)) // northEast - .include(new LatLng(50, 20)) - .include(new LatLng(50, 10)) // southWest again - .build(); - - LatLngBounds sameLatitudeFirst = new LatLngBounds.Builder() - .include(new LatLng(50, 20)) - .include(new LatLng(50, 10)) // southWest - .include(new LatLng(60, 10)) - .include(new LatLng(60, 20)) // northEast - .include(new LatLng(50, 20)) - .build(); - - assertEquals(sameLatitudeFirst, sameLongitudeFirst); - } - - @Test - public void includesOverDateline1() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -170)) - .include(new LatLng(-10, -175)) - .include(new LatLng(0, -190)) - .build(); - - LatLngSpan latLngSpan = latLngBounds.getSpan(); - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngSpan); - } - - @Test - public void includesOverDateline2() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(-10, 175)) - .include(new LatLng(0, 190)) - .build(); - - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngBounds.getSpan()); - } - - @Test - public void includesOverDateline3() { - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, -190)) - .include(new LatLng(-10, -170)) - .include(new LatLng(0, -180)) - .include(new LatLng(5, -180)) - .build(); - - assertEquals("LatLngSpan should be the same", - new LatLngSpan(20, 20), latLngBounds.getSpan()); - } - - @Test - public void containsNot() { - assertFalse("LatLng should not be included", - latLngBounds.contains(new LatLng(3, 1))); - } - - @Test - public void containsBoundsInWorld() { - assertTrue("LatLngBounds should be contained in the world", - LatLngBounds.world().contains(latLngBounds)); - } - - @Test - public void worldSpan() { - assertEquals("LatLngBounds world span should be 180, 360", - GeometryConstants.LATITUDE_SPAN, LatLngBounds.world().getLatitudeSpan(), DELTA); - assertEquals("LatLngBounds world span should be 180, 360", - GeometryConstants.LONGITUDE_SPAN, LatLngBounds.world().getLongitudeSpan(), DELTA); - } - - @Test - public void emptySpan() { - LatLngBounds latLngBounds = LatLngBounds.from( - GeometryConstants.MIN_LATITUDE, GeometryConstants.MAX_LONGITUDE, - GeometryConstants.MIN_LATITUDE, GeometryConstants.MAX_LONGITUDE); - assertTrue("LatLngBounds empty span", latLngBounds.isEmptySpan()); - } - - @Test - public void containsBounds() { - LatLngBounds inner = new LatLngBounds.Builder() - .include(new LatLng(-5, -5)) - .include(new LatLng(5, 5)) - .build(); - LatLngBounds outer = new LatLngBounds.Builder() - .include(new LatLng(-10, -10)) - .include(new LatLng(10, 10)) - .build(); - assertTrue(outer.contains(inner)); - assertFalse(inner.contains(outer)); - } - - @Test - public void testHashCode() { - assertEquals(2147483647, latLngBounds.hashCode(), -1946419200); - } - - @Test - public void equality() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(LAT_LNG_NULL_ISLAND) - .include(LAT_LNG_NOT_NULL_ISLAND) - .build(); - assertEquals("equality should match", this.latLngBounds, latLngBounds); - assertEquals("not equal to a different object type", - this.latLngBounds.equals(LAT_LNG_NOT_NULL_ISLAND), false); - } - - @Test - public void testToString() { - assertEquals(latLngBounds.toString(), "N:2.0; E:2.0; S:0.0; W:0.0"); - } - - @Test - public void intersect() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(1, 1)) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals("intersect should match", latLngBounds, - latLngBounds.intersect(this.latLngBounds.getLatNorth(), - this.latLngBounds.getLonEast(), - this.latLngBounds.getLatSouth(), - this.latLngBounds.getLonWest())); - } - - @Test - public void intersectNot() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - assertNull(latLngBounds.intersect(this.latLngBounds)); - } - - @Test - public void intersectNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .intersect(200, 200, 0, 0); - } - - @Test - public void intersectSouthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(0, 0, -10, -10) - .intersect(0, 0, -200, -200); - } - - @Test - public void intersectSouthLessThanNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .intersect(0, 200, 20, 0); - } - - @Test - public void intersectEastLessThanWestCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("lonEast cannot be less than lonWest"); - LatLngBounds intersectLatLngBounds = - LatLngBounds.from(10, -10, 0, 0) - .intersect(0, 200, 20, 0); - } - - public void intersectEastDoesNotWrapCheck() { - - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 210, 0, 0); - LatLngBounds latLngBounds2 = LatLngBounds.from(90, 200, 0, 0); - - LatLngBounds intersectLatLngBounds = LatLngBounds.from(10, 200, 0, 0); - - assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds); - assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds); - } - - @Test - public void intersectDoesNotWestWrapCheck() { - LatLngBounds latLngBounds1 = LatLngBounds.from(0, 0, -10, -210); - LatLngBounds latLngBounds2 = LatLngBounds.from(0, 0, -90, -200); - - LatLngBounds intersectLatLngBounds = LatLngBounds.from(0, 0, -10, -200); - - assertEquals(latLngBounds1.intersect(latLngBounds2), intersectLatLngBounds); - assertEquals(latLngBounds2.intersect(latLngBounds1), intersectLatLngBounds); - } - - @Test - public void innerUnion() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(1, 1)) - .include(LAT_LNG_NULL_ISLAND) - .build(); - assertEquals("union should match", latLngBounds, latLngBounds.intersect(this.latLngBounds)); - } - - @Test - public void outerUnion() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - assertEquals("outer union should match", - latLngBounds.union(this.latLngBounds), - new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(LAT_LNG_NULL_ISLAND) - .build()); - } - - @Test - public void unionOverDateLine() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 190)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine2() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 170)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 165)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine3() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 195)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 190)) - .include(new LatLng(-10, 200)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine4() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, -160)) - .include(new LatLng(0, -200)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, -170)) - .include(new LatLng(-10, -175)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, -200)) - .include(new LatLng(-10, -160)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLine5() { - LatLngBounds latLngBounds1 = new LatLngBounds.Builder() - .include(new LatLng(10, 200)) - .include(new LatLng(0, 160)) - .build(); - - LatLngBounds latLngBounds2 = new LatLngBounds.Builder() - .include(new LatLng(0, 170)) - .include(new LatLng(-10, 175)) - .build(); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, - new LatLngBounds.Builder() - .include(new LatLng(10, 160)) - .include(new LatLng(-10, 200)) - .build()); - - assertEquals(union1, union2); - } - - @Test - public void unionOverDateLineReturnLongerThanWorldLonSpan() { - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 200, -10, -10); - LatLngBounds latLngBounds2 = LatLngBounds.from(10, 10, -10, -200); - - LatLngBounds union1 = latLngBounds1.union(latLngBounds2); - LatLngBounds union2 = latLngBounds2.union(latLngBounds1); - - assertEquals(union1, union2); - assertEquals(union1, LatLngBounds.from(10, 200, -10, -200)); - } - - @Test - public void unionNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds unionLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .union(200, 200, 0, 0); - } - - @Test - public void unionSouthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds unionLatLngBounds = - LatLngBounds.from(0, 0, -10, -10) - .union(0, 0, -200, -200); - } - - @Test - public void unionSouthLessThanNorthCheck() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - - LatLngBounds unionLatLngBounds = - LatLngBounds.from(10, 10, 0, 0) - .union(0, 200, 20, 0); - } - - - @Test - public void unionEastDoesNotWrapCheck() { - - LatLngBounds latLngBounds1 = LatLngBounds.from(10, 10, 0, 0); - LatLngBounds latLngBounds2 = LatLngBounds.from(90, 200, 0, 0); - LatLngBounds unionLatLngBounds = LatLngBounds.from(90, 200, 0, 0); - - assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds); - assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds); - } - - @Test - public void unionWestDoesNotWrapCheck() { - LatLngBounds latLngBounds1 = LatLngBounds.from(0, 0, -10, -10); - LatLngBounds latLngBounds2 = LatLngBounds.from(0, 0, -90, -200); - - LatLngBounds unionLatLngBounds = LatLngBounds.from(0, 0, -90, -200); - - assertEquals(latLngBounds1.union(latLngBounds2), unionLatLngBounds); - assertEquals(latLngBounds2.union(latLngBounds1), unionLatLngBounds); - } - - @Test - public void northWest() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("NorthWest should match", latLngBounds.getNorthWest(), new LatLng(maxLat, minLon)); - } - - @Test - public void southWest() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("SouthWest should match", latLngBounds.getSouthWest(), new LatLng(minLat, minLon)); - } - - @Test - public void northEast() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("NorthEast should match", latLngBounds.getNorthEast(), new LatLng(maxLat, maxLon)); - } - - @Test - public void southEast() { - double minLat = 5; - double minLon = 6; - double maxLat = 20; - double maxLon = 21; - - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(minLat, minLon)) - .include(new LatLng(maxLat, maxLon)) - .build(); - - assertEquals("SouthEast should match", latLngBounds.getSouthEast(), new LatLng(minLat, maxLon)); - } - - @Test - public void testParcelable() { - LatLngBounds latLngBounds = new LatLngBounds.Builder() - .include(new LatLng(10, 10)) - .include(new LatLng(9, 8)) - .build(); - Parcelable parcel = MockParcel.obtain(latLngBounds); - assertEquals("Parcel should match original object", parcel, latLngBounds); - } - - @Test - public void fromTileID() { - LatLngBounds bounds = LatLngBounds.from(0, 0, 0); - assertEquals(GeometryConstants.MIN_WRAP_LONGITUDE, bounds.getLonWest(), DELTA); - assertEquals(GeometryConstants.MIN_MERCATOR_LATITUDE, bounds.getLatSouth(), DELTA); - assertEquals(GeometryConstants.MAX_WRAP_LONGITUDE, bounds.getLonEast(), DELTA); - assertEquals(GeometryConstants.MAX_MERCATOR_LATITUDE, bounds.getLatNorth(), DELTA); - - bounds = LatLngBounds.from(10, 288, 385); - assertEquals(-78.75, bounds.getLonWest(), DELTA); - assertEquals(40.446947059600497, bounds.getLatSouth(), DELTA); - assertEquals(-78.3984375, bounds.getLonEast(), DELTA); - assertEquals(40.713955826286039, bounds.getLatNorth(), DELTA); - - } - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void testConstructorChecksNorthLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - LatLngBounds.from(Double.NaN, 0, -20, -20); - } - - @Test - public void testConstructorChecksEastLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - LatLngBounds.from(0, Double.NaN, -20, -20); - } - - @Test - public void testConstructorChecksNorthLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(95, 0, -20, -20); - } - - @Test - public void testConstructorChecksNorthLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(-95, 0, -20, -20); - } - - @Test - public void testConstructorChecksEastLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - LatLngBounds.from(0, Double.POSITIVE_INFINITY, -20, -20); - } - - @Test - public void testConstructorChecksSouthLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - LatLngBounds.from(20, 20, Double.NaN, 0); - } - - @Test - public void testConstructorChecksWesttLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - LatLngBounds.from(20, 20, 0, Double.NaN); - } - - @Test - public void testConstructorChecksSouthLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(20, 20, 95, 0); - } - - @Test - public void testConstructorChecksSouthLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - LatLngBounds.from(20, 20, -95, 0); - } - - @Test - public void testConstructorChecksWestLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - LatLngBounds.from(20, 20, 0, Double.POSITIVE_INFINITY); - } - - @Test - public void testConstructorCheckLatSouthGreaterLatNorth() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latNorth cannot be less than latSouth"); - LatLngBounds.from(0, 20, 20, 0); - } - - @Test - public void testConstructorCheckLonWestGreaterLonEast() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("lonEast cannot be less than lonWest"); - LatLngBounds.from(20, 0, 0, 20); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java deleted file mode 100644 index 12297247c..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngSpanTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class LatLngSpanTest { - - private static final double DELTA = 1e-15; - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - - @Test - public void testSanity() { - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - assertNotNull("latLngSpan should not be null", latLngSpan); - } - - @Test - public void testEquality() { - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - assertEquals("latLngSpan is not equal to a LatLng", latLngSpan.equals(LAT_LNG_NULL_ISLAND), false); - } - - @Test - public void testLatitudeConstructor() { - double latitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(latitude, 0.0); - assertEquals("latitude in constructor", latLngSpan.getLatitudeSpan(), latitude, DELTA); - } - - @Test - public void testLongitudeConstructor() { - double longitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, longitude); - assertEquals("latitude in constructor", latLngSpan.getLongitudeSpan(), longitude, DELTA); - } - - @Test - public void testLatitudeMethod() { - double latitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - latLngSpan.setLatitudeSpan(latitude); - assertEquals("latitude in constructor", latLngSpan.getLatitudeSpan(), latitude, DELTA); - } - - @Test - public void testLongitudeMethod() { - double longitude = 1.23; - LatLngSpan latLngSpan = new LatLngSpan(0.0, 0.0); - latLngSpan.setLongitudeSpan(longitude); - assertEquals("latitude in constructor", latLngSpan.getLongitudeSpan(), longitude, DELTA); - } - - @Test - public void testParcelable() { - LatLngSpan object = new LatLngSpan(1, 2); - Parcelable parcel = MockParcel.obtain(object); - assertEquals("parcel should match initial object", object, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java deleted file mode 100644 index 862c56a52..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/LatLngTest.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.location.Location; -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class LatLngTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - LatLng latLng = new LatLng(0.0, 0.0); - assertNotNull("latLng should not be null", latLng); - } - - @Test - public void testLatitudeEmptyConstructor() { - LatLng latLng = new LatLng(); - assertEquals("latitude default value", latLng.getLatitude(), 0, DELTA); - } - - @Test - public void testLongitudeEmptyConstructor() { - LatLng latLng = new LatLng(); - assertEquals("longitude default value", latLng.getLongitude(), 0, DELTA); - } - - @Test - public void testAltitudeEmptyConstructor() { - LatLng latLng1 = new LatLng(); - assertEquals("altitude default value", latLng1.getAltitude(), 0.0, DELTA); - } - - @Test - public void testLatitudeConstructor() { - double latitude = 1.2; - LatLng latLng = new LatLng(latitude, 3.4); - assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA); - } - - @Test - public void testLongitudeConstructor() { - double longitude = 3.4; - LatLng latLng = new LatLng(1.2, longitude); - assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA); - } - - @Test - public void testAltitudeConstructor() { - LatLng latLng1 = new LatLng(1.2, 3.4); - assertEquals("altitude default value", latLng1.getAltitude(), 0.0, DELTA); - - double altitude = 5.6; - LatLng latLng2 = new LatLng(1.2, 3.4, altitude); - assertEquals("altitude default value", latLng2.getAltitude(), altitude, DELTA); - } - - @Test - public void testLatitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setLatitude(3); - assertEquals("latitude should match", 3, latLng.getLatitude(), DELTA); - } - - @Test - public void testLongitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setLongitude(3); - assertEquals("longitude should match", 3, latLng.getLongitude(), DELTA); - } - - @Rule - public final ExpectedException exception = ExpectedException.none(); - - @Test - public void testConstructorChecksLatitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - new LatLng(Double.NaN, 0); - } - - @Test - public void testConstructorChecksLongitudeNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - new LatLng(0, Double.NaN); - } - - @Test - public void testConstructorChecksLatitudeGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng(95, 0); - } - - @Test - public void testConstructorChecksLatitudeLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng(-95, 0); - } - - @Test - public void testConstructorChecksLongitudeInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - new LatLng(0, Double.POSITIVE_INFINITY); - } - - @Test - public void testLatitudeSetterChecksNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must not be NaN"); - new LatLng().setLatitude(Double.NaN); - } - - @Test - public void testLongitudeSetterChecksNaN() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be NaN"); - new LatLng().setLongitude(Double.NaN); - } - - @Test - public void testLatitudeSetterChecksGreaterThan90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng().setLatitude(95); - } - - @Test - public void testLatitudeSetterChecksLessThanThanNegative90() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("latitude must be between -90 and 90"); - new LatLng().setLatitude(-95); - } - - @Test - public void testLongitudeSetterChecksInfinity() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("longitude must not be infinite"); - new LatLng().setLongitude(Double.NEGATIVE_INFINITY); - } - - @Test - public void testAltitudeSetter() { - LatLng latLng = new LatLng(1.2, 3.4); - latLng.setAltitude(3); - assertEquals("altitude should match", 3, latLng.getAltitude(), DELTA); - } - - @Test - public void testLatLngConstructor() { - LatLng latLng1 = new LatLng(1.2, 3.4); - LatLng latLng2 = new LatLng(latLng1); - assertEquals("latLng should match", latLng1, latLng2); - } - - @Test - public void testDistanceTo() { - LatLng latLng1 = new LatLng(0.0, 0.0); - LatLng latLng2 = new LatLng(1.0, 1.0); - assertEquals("distances should match", - latLng1.distanceTo(latLng2), - 157298.7453847275, DELTA); - } - - @Test - public void testDistanceToSamePoint() { - LatLng latLng1 = new LatLng(40.71199035644531, -74.0081); - LatLng latLng2 = new LatLng(40.71199035644531, -74.0081); - double distance = latLng1.distanceTo(latLng2); - assertEquals("distance should match", 0.0, distance, DELTA); - } - - // Regression test for #14216 - @Test - public void testDistanceToClosePointNotNaN() { - LatLng latLng = new LatLng(40.00599, -105.29261); - LatLng other = new LatLng(40.005990000000025, -105.29260999999997); - double distance = latLng.distanceTo(other); - assertNotEquals(distance, Double.NaN); - } - - @Test - public void testLocationProvider() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - - // Mock the location class - Location locationMocked = mock(Location.class); - when(locationMocked.getLatitude()).thenReturn(latitude); - when(locationMocked.getLongitude()).thenReturn(longitude); - when(locationMocked.getAltitude()).thenReturn(altitude); - - // Test the constructor - LatLng latLng = new LatLng(locationMocked); - assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA); - assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA); - assertEquals("altitude should match", latLng.getAltitude(), altitude, DELTA); - } - - @Test - public void testHashCode() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng = new LatLng(latitude, longitude, altitude); - assertEquals("hash code should match", latLng.hashCode(), -151519232); - } - - @Test - public void testToString() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng = new LatLng(latitude, longitude, altitude); - assertEquals("string should match", - latLng.toString(), - "LatLng [latitude=1.2, longitude=3.4, altitude=5.6]"); - } - - @Test - public void testEqualsOther() { - double latitude = 1.2; - double longitude = 3.4; - double altitude = 5.6; - LatLng latLng1 = new LatLng(latitude, longitude, altitude); - LatLng latLng2 = new LatLng(latitude, longitude, altitude); - assertEquals("LatLng should match", latLng1, latLng2); - } - - @Test - public void testEqualsItself() { - LatLng latLng = new LatLng(1, 2, 3); - assertEquals("LatLng should match", latLng, latLng); - } - - @Test - public void testNotEquals() { - LatLng latLng = new LatLng(1, 2); - assertNotEquals("LatLng should match", latLng, new Object()); - } - - @Test - public void testParcelable() { - LatLng latLng = new LatLng(45.0, -185.0); - Parcelable parcel = MockParcel.obtain(latLng); - assertEquals("parcel should match initial object", latLng, parcel); - } - - @Test - public void testWrapped() { - LatLng originalLatLng = new LatLng(45.0, -185.0); - LatLng newLatlng = originalLatLng.wrap(); - assertNotSame(" new wrapped LatLng is created", originalLatLng, newLatlng); - assertEquals("longitude wrapped value", originalLatLng.getLongitude(), -185.0, DELTA); - assertEquals("longitude wrapped value", newLatlng.getLongitude(), 175.0, DELTA); - - newLatlng = new LatLng(45.0, 180.0).wrap(); - assertEquals("longitude wrapped max value", newLatlng.getLongitude(), 180.0, DELTA); - - newLatlng = new LatLng(45.0, -180.0).wrap(); - assertEquals("longitude wrapped min value", newLatlng.getLongitude(), -180.0, DELTA); - } - - @Test - public void testUnnecessaryWrapped() { - LatLng latLng = new LatLng(45.0, 50.0).wrap(); - assertEquals("longitude wrapped value", latLng.getLongitude(), 50.0, DELTA); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java deleted file mode 100644 index 00fd125a1..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/ProjectedMetersTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class ProjectedMetersTest { - - private static final LatLng LAT_LNG_NULL_ISLAND = new LatLng(0, 0); - - @Test - public void testSanity() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 0.0); - assertNotNull("projectedMeters should not be null", projectedMeters); - } - - @Test - public void testEquality() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 0.0); - assertEquals("projectedMeters is not equal to a LatLng", projectedMeters.equals(LAT_LNG_NULL_ISLAND), false); - assertEquals("projectedMeters is equal to itself", projectedMeters.equals(projectedMeters), true); - } - - @Test - public void testNorthing() { - ProjectedMeters projectedMeters = new ProjectedMeters(1.0, 0.0); - assertEquals("northing should be 1", 1, projectedMeters.getNorthing(), 0); - } - - @Test - public void testEasting() { - ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 1.0); - assertEquals("easting should be 1", 1, projectedMeters.getEasting(), 0); - } - - @Test - public void testConstructor() { - ProjectedMeters projectedMeters1 = new ProjectedMeters(1, 2); - ProjectedMeters projectedMeters2 = new ProjectedMeters(projectedMeters1); - assertEquals("projectedmeters should match", projectedMeters1, projectedMeters2); - } - - @Test - public void testHashcode() { - ProjectedMeters meters = new ProjectedMeters(1, 2); - assertEquals("hashcode should match", -1048576, meters.hashCode()); - } - - @Test - public void testToString() { - ProjectedMeters meters = new ProjectedMeters(1, 1); - assertEquals("toString should match", "ProjectedMeters [northing=1.0, easting=1.0]", meters.toString()); - } - - @Test - public void testParcelable() { - ProjectedMeters meters = new ProjectedMeters(1, 1); - Parcelable parcel = MockParcel.obtain(meters); - assertEquals("parcel should match initial object", meters, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java deleted file mode 100644 index 12b779de5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/geometry/VisibleRegionTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.mapbox.mapboxsdk.geometry; - -import android.os.Parcelable; - -import com.mapbox.mapboxsdk.utils.MockParcel; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -public class VisibleRegionTest { - - private static final LatLng FAR_LEFT = new LatLng(52, -12); - private static final LatLng NEAR_LEFT = new LatLng(34, -12); - private static final LatLng FAR_RIGHT = new LatLng(52, 26); - private static final LatLng NEAR_RIGHT = new LatLng(34, 26); - private static final LatLngBounds BOUNDS = - new LatLngBounds.Builder().include(FAR_LEFT).include(FAR_RIGHT).include(NEAR_LEFT).include(NEAR_RIGHT).build(); - - @Test - public void testSanity() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertNotNull("region should not be null", region); - } - - @Test - public void testEquality() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("visibleRegion is not equal to a LatLng", region.equals(FAR_LEFT), false); - assertEquals("visibleRegion is equal to itself", region.equals(region), true); - } - - @Test - public void testFarLeftConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.farLeft, FAR_LEFT); - } - - @Test - public void testNearLeftConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.nearLeft, NEAR_LEFT); - } - - @Test - public void testFarRightConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.farRight, FAR_RIGHT); - } - - @Test - public void testNearRightConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLng should match", region.nearRight, NEAR_RIGHT); - } - - @Test - public void testLatLngBoundsConstructor() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("LatLngBounds should match", region.latLngBounds, BOUNDS); - } - - @Test - public void testEquals() { - VisibleRegion regionLeft = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - VisibleRegion regionRight = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("VisibleRegions should match", regionLeft, regionRight); - } - - @Test - public void testHashcode() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("hashcode should match", -923534102, region.hashCode()); - } - - @Test - public void testToString() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - assertEquals("string should match", - "[farLeft [LatLng [latitude=52.0, longitude=-12.0, altitude=0.0]], " - + "farRight [LatLng [latitude=52.0, longitude=26.0, altitude=0.0]], " - + "nearLeft [LatLng [latitude=34.0, longitude=-12.0, altitude=0.0]], " - + "nearRight [LatLng [latitude=34.0, longitude=26.0, altitude=0.0]], " - + "latLngBounds [N:52.0; E:26.0; S:34.0; W:-12.0]]", - region.toString()); - } - - @Test - public void testParcelable() { - VisibleRegion region = new VisibleRegion(FAR_LEFT, FAR_RIGHT, NEAR_LEFT, NEAR_RIGHT, BOUNDS); - Parcelable parcel = MockParcel.obtain(region); - assertEquals("parcel should match initial object", region, parcel); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java deleted file mode 100644 index bebd82811..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/CompassEngineTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.hardware.Sensor; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; -import android.view.WindowManager; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import static com.mapbox.mapboxsdk.location.LocationComponentCompassEngine.SENSOR_DELAY_MICROS; -import static junit.framework.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class CompassEngineTest { - - private LocationComponentCompassEngine compassEngine; - - @Mock - private WindowManager windowManager; - - @Mock - private SensorManager sensorManager; - - @Mock - private Sensor compassSensor; - - @Mock - private CompassListener compassListener; - - @Before - public void setUp() throws Exception { - when(sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)).thenReturn(compassSensor); - compassEngine = new LocationComponentCompassEngine(windowManager, sensorManager); - } - - @Test - public void lastKnownCompassBearingAccuracyDefault() { - assertEquals("Last accuracy should match", compassEngine.getLastAccuracySensorStatus(), 0); - } - - @Test - public void lastKnownCompassAccuracyStatusValue() { - Sensor sensor = mock(Sensor.class); - compassEngine.onAccuracyChanged(sensor, 2); - assertEquals("Last accuracy should match", compassEngine.getLastAccuracySensorStatus(), 2); - } - - @Test - public void whenGyroscopeIsNull_fallbackToGravity() { - SensorManager sensorManager = mock(SensorManager.class); - when(sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)).thenReturn(null); - new LocationComponentCompassEngine(windowManager, sensorManager); - - verify(sensorManager, times(1)).getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - } - - @Test - public void whenGyroscopeIsNull_fallbackToMagneticField() { - SensorManager sensorManager = mock(SensorManager.class); - when(sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)).thenReturn(null); - new LocationComponentCompassEngine(windowManager, sensorManager); - - verify(sensorManager, times(1)).getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); - } - - @Test - public void listener_registerOnAdd() { - compassEngine.addCompassListener(compassListener); - verify(sensorManager) - .registerListener(any(SensorEventListener.class), eq(compassSensor), eq(SENSOR_DELAY_MICROS)); - } - - @Test - public void listener_unregisterOnRemove() { - compassEngine.addCompassListener(compassListener); - compassEngine.removeCompassListener(compassListener); - verify(sensorManager).unregisterListener(any(SensorEventListener.class), eq(compassSensor)); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinatorTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinatorTest.kt deleted file mode 100644 index 1b927d213..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationAnimatorCoordinatorTest.kt +++ /dev/null @@ -1,532 +0,0 @@ -package com.mapbox.mapboxsdk.location - -import android.animation.Animator -import android.location.Location -import android.util.SparseArray -import android.view.animation.LinearInterpolator -import com.mapbox.mapboxsdk.camera.CameraPosition -import com.mapbox.mapboxsdk.geometry.LatLng -import com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_TRACKING_TILT_ANIM_DURATION -import com.mapbox.mapboxsdk.location.LocationComponentConstants.DEFAULT_TRACKING_ZOOM_ANIM_DURATION -import com.mapbox.mapboxsdk.location.MapboxAnimator.* -import com.mapbox.mapboxsdk.location.modes.CameraMode -import com.mapbox.mapboxsdk.location.modes.RenderMode -import com.mapbox.mapboxsdk.maps.MapboxMap -import com.mapbox.mapboxsdk.maps.Projection -import io.mockk.* -import junit.framework.Assert.assertEquals -import junit.framework.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mockito -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class LocationAnimatorCoordinatorTest { - - private lateinit var locationAnimatorCoordinator: LocationAnimatorCoordinator - private val cameraPosition: CameraPosition = CameraPosition.DEFAULT - - private val animatorProvider: MapboxAnimatorProvider = mockk() - private val animatorSetProvider: MapboxAnimatorSetProvider = mockk() - - private val projection: Projection = mockk() - - @Before - fun setUp() { - locationAnimatorCoordinator = LocationAnimatorCoordinator(projection, animatorSetProvider, animatorProvider) - configureAnimatorProvider() - every { projection.getMetersPerPixelAtLatitude(any()) } answers { 1.0 } - every { animatorSetProvider.startAnimation(any(), any(), any()) } answers {} - locationAnimatorCoordinator.updateAnimatorListenerHolders(getListenerHoldersSet( - ANIMATOR_LAYER_LATLNG, - ANIMATOR_CAMERA_LATLNG, - ANIMATOR_LAYER_GPS_BEARING, - ANIMATOR_LAYER_COMPASS_BEARING, - ANIMATOR_CAMERA_GPS_BEARING, - ANIMATOR_CAMERA_COMPASS_BEARING, - ANIMATOR_LAYER_ACCURACY, - ANIMATOR_ZOOM, - ANIMATOR_TILT - )) - } - - private fun configureAnimatorProvider() { - // workaround https://github.com/mockk/mockk/issues/229#issuecomment-457816131 - registerInstanceFactory { AnimationsValueChangeListener {} } - registerInstanceFactory { AnimationsValueChangeListener {} } - val previousFloatSlot = slot() - val targetFloatSlot = slot() - val listenerSlot = slot>() - val maxFpsSlot = slot() - every { - animatorProvider.floatAnimator(capture(previousFloatSlot), capture(targetFloatSlot), capture(listenerSlot), capture(maxFpsSlot)) - } answers { - MapboxFloatAnimator(previousFloatSlot.captured, targetFloatSlot.captured, listenerSlot.captured, maxFpsSlot.captured) - } - - val previousLatLngSlot = slot() - val targetLatLngSlot = slot() - every { - animatorProvider.latLngAnimator(capture(previousLatLngSlot), capture(targetLatLngSlot), capture(listenerSlot), capture(maxFpsSlot)) - } answers { - MapboxLatLngAnimator(previousLatLngSlot.captured, targetLatLngSlot.captured, listenerSlot.captured, maxFpsSlot.captured) - } - - val callback = slot() - every { - animatorProvider.cameraAnimator(capture(previousFloatSlot), capture(targetFloatSlot), capture(listenerSlot), capture(callback)) - } answers { - MapboxCameraAnimatorAdapter(previousFloatSlot.captured, targetFloatSlot.captured, listenerSlot.captured, callback.captured) - } - every { - animatorProvider.cameraAnimator(capture(previousFloatSlot), capture(targetFloatSlot), capture(listenerSlot), null) - } answers { - MapboxCameraAnimatorAdapter(previousFloatSlot.captured, targetFloatSlot.captured, listenerSlot.captured, null) - } - } - - @Test - fun feedNewLocation_animatorsAreCreated() { - locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, false) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING] != null) - } - - @Test - fun feedNewLocation_animatorValue() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 35f - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val cameraLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG]?.target as LatLng - assertEquals(cameraLatLngTarget.latitude, cameraLatLngTarget.latitude) - - val layerLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG]?.target as LatLng - assertEquals(layerLatLngTarget.latitude, layerLatLngTarget.latitude) - - val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]?.target as Float - assertEquals(location.bearing, cameraBearingTarget) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(location.bearing, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_1() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 0f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns 270f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(360f, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_2() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 90f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns 280f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(450f, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_3() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 300f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns 450f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(-60f, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_4() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 350f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns 10f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(-10f, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_5() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 90f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns -280f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(90f, layerBearingTarget) - } - - @Test - fun feedNewLocation_animatorValue_correctRotation_6() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 270f - - val animator = mockk(relaxed = true) - every { animator.animatedValue } returns -350f - locationAnimatorCoordinator.animatorArray.put(ANIMATOR_LAYER_GPS_BEARING, animator) - - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(-90f, layerBearingTarget) - } - - @Test - fun feedNewLocation_isNorth_animatorsAreCreated() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 35f - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, false) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING] != null) - } - - @Test - fun feedNewLocation_isNorth_animatorValue() { - val location = Location("") - location.latitude = 51.0 - location.longitude = 17.0 - location.bearing = 35f - locationAnimatorCoordinator.feedNewLocation(location, cameraPosition, true) - - val cameraLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG]?.target as LatLng - assertEquals(cameraLatLngTarget.latitude, cameraLatLngTarget.latitude) - - val layerLatLngTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_LATLNG]?.target as LatLng - assertEquals(layerLatLngTarget.latitude, layerLatLngTarget.latitude) - - val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_GPS_BEARING]?.target as Float - assertEquals(0f, cameraBearingTarget) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_GPS_BEARING]?.target as Float - assertEquals(location.bearing, layerBearingTarget) - } - - @Test - fun feedNewCompassBearing_animatorsAreCreated() { - locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING] != null) - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING] != null) - } - - @Test - fun feedNewCompassBearing_animatorValue() { - val bearing = 77f - locationAnimatorCoordinator.feedNewCompassBearing(bearing, cameraPosition) - - val cameraBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]?.target as Float - assertEquals(bearing, cameraBearingTarget) - - val layerBearingTarget = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING]?.target as Float - assertEquals(bearing, layerBearingTarget) - } - - @Test - fun feedNewAccuracyRadius_animatorsCreated() { - locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY] != null) - } - - @Test - fun feedNewAccuracyRadius_animatorValue() { - val accuracy = 150f - locationAnimatorCoordinator.feedNewAccuracyRadius(accuracy, false) - - val layerAccuracy = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]?.target as Float - assertEquals(layerAccuracy, accuracy) - } - - @Test - fun feedNewAccuracyRadius_noAnimation_animatorsCreated() { - locationAnimatorCoordinator.feedNewAccuracyRadius(150f, true) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY] != null) - } - - @Test - fun feedNewAccuracyRadius_noAnimation_animatorValue() { - val accuracy = 150f - locationAnimatorCoordinator.feedNewAccuracyRadius(accuracy, true) - - val layerAccuracy = locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]?.target as Float - assertEquals(layerAccuracy, accuracy) - } - - @Test - fun feedNewZoomLevel_animatorsCreated() { - locationAnimatorCoordinator.feedNewZoomLevel( - 15.0, - cameraPosition, - DEFAULT_TRACKING_ZOOM_ANIM_DURATION, - null - ) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM] != null) - } - - @Test - fun feedNewZoomLevel_animatorValue() { - val zoom = 15.0f - locationAnimatorCoordinator.feedNewZoomLevel( - zoom.toDouble(), - cameraPosition, - DEFAULT_TRACKING_ZOOM_ANIM_DURATION, - null - ) - - val animator = locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM] - assertEquals(zoom, animator.target) - verify { animatorSetProvider.startAnimation(eq(listOf(animator)), any(), DEFAULT_TRACKING_ZOOM_ANIM_DURATION) } - } - - @Test - fun feedNewTiltLevel_animatorsCreated() { - locationAnimatorCoordinator.feedNewTilt( - 30.0, - cameraPosition, - DEFAULT_TRACKING_TILT_ANIM_DURATION, - null - ) - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT] != null) - } - - @Test - fun feedNewTiltLevel_animatorValue() { - val tilt = 30.0f - locationAnimatorCoordinator.feedNewTilt( - tilt.toDouble(), - cameraPosition, - DEFAULT_TRACKING_TILT_ANIM_DURATION, - null - ) - - val animator = locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT] - assertEquals(tilt, animator.target) - verify { animatorSetProvider.startAnimation(eq(listOf(animator)), any(), DEFAULT_TRACKING_TILT_ANIM_DURATION) } - } - - @Test - fun cancelAllAnimators() { - locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, true) - locationAnimatorCoordinator.cancelAllAnimations() - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_LATLNG] == null) - } - - @Test - fun cancelZoomAnimators() { - locationAnimatorCoordinator.feedNewZoomLevel( - 15.0, - cameraPosition, - DEFAULT_TRACKING_ZOOM_ANIM_DURATION, - null - ) - locationAnimatorCoordinator.cancelZoomAnimation() - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_ZOOM] == null) - } - - @Test - fun cancelTiltAnimation() { - locationAnimatorCoordinator.feedNewTilt( - 30.0, - cameraPosition, - DEFAULT_TRACKING_TILT_ANIM_DURATION, - null - ) - - locationAnimatorCoordinator.cancelTiltAnimation() - - assertTrue(locationAnimatorCoordinator.animatorArray[ANIMATOR_TILT] == null) - } - - @Test - fun resetAllCameraAnimations_empty() { - locationAnimatorCoordinator.resetAllCameraAnimations(cameraPosition, false) - assertTrue(locationAnimatorCoordinator.animatorArray.size() == 0) - } - - @Test - fun resetAllLayerAnimations_empty() { - locationAnimatorCoordinator.resetAllLayerAnimations() - assertTrue(locationAnimatorCoordinator.animatorArray.size() == 0) - } - - @Test - fun addNewListener() { - val listener = Mockito.mock(AnimationsValueChangeListener::class.java) - val holder = AnimatorListenerHolder(RenderMode.NORMAL, listener) - val set = HashSet().also { - it.add(holder) - } - locationAnimatorCoordinator.updateAnimatorListenerHolders(set) - - assertTrue(locationAnimatorCoordinator.listeners.contains(listener)) - } - - @Test - fun updateListeners() { - val listener = Mockito.mock(AnimationsValueChangeListener::class.java) - val holder = AnimatorListenerHolder(RenderMode.NORMAL, listener) - val set = HashSet().also { - it.add(holder) - } - locationAnimatorCoordinator.updateAnimatorListenerHolders(set) - - val listener2 = Mockito.mock(AnimationsValueChangeListener::class.java) - val holder2 = AnimatorListenerHolder(RenderMode.NORMAL, listener2) - val listener3 = Mockito.mock(AnimationsValueChangeListener::class.java) - val holder3 = AnimatorListenerHolder(CameraMode.TRACKING_GPS, listener3) - val set2 = HashSet().also { - it.add(holder2) - it.add(holder3) - } - locationAnimatorCoordinator.updateAnimatorListenerHolders(set2) - - assertTrue(locationAnimatorCoordinator.listeners.size() == 2) - assertTrue(locationAnimatorCoordinator.listeners.contains(listener2)) - assertTrue(locationAnimatorCoordinator.listeners.contains(listener3)) - } - - @Test - fun feedNewCompassBearing_withAnimation() { - locationAnimatorCoordinator.setCompassAnimationEnabled(true) - locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition) - - val animators = mutableListOf( - locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING], - locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]) - - verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(LocationComponentConstants.COMPASS_UPDATE_RATE_MS)) } - } - - @Test - fun feedNewCompassBearing_withoutAnimation() { - locationAnimatorCoordinator.setCompassAnimationEnabled(false) - locationAnimatorCoordinator.feedNewCompassBearing(77f, cameraPosition) - - val animators = mutableListOf( - locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_COMPASS_BEARING], - locationAnimatorCoordinator.animatorArray[ANIMATOR_CAMERA_COMPASS_BEARING]) - - verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(0)) } - } - - @Test - fun feedNewAccuracy_withAnimation() { - locationAnimatorCoordinator.setAccuracyAnimationEnabled(true) - locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false) - - val animators = mutableListOf( - locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]) - - verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(LocationComponentConstants.ACCURACY_RADIUS_ANIMATION_DURATION)) } - } - - @Test - fun feedNewAccuracy_withoutAnimation() { - locationAnimatorCoordinator.setAccuracyAnimationEnabled(false) - locationAnimatorCoordinator.feedNewAccuracyRadius(150f, false) - - val animators = mutableListOf( - locationAnimatorCoordinator.animatorArray[ANIMATOR_LAYER_ACCURACY]) - - verify(exactly = 1) { animatorSetProvider.startAnimation(eq(animators), ofType(LinearInterpolator::class), eq(0)) } - } - - @Test - fun maxFps_setter() { - locationAnimatorCoordinator.setMaxAnimationFps(5) - assertEquals(5, locationAnimatorCoordinator.maxAnimationFps) - } - - @Test - fun maxFps_moreThanZeroRequired() { - locationAnimatorCoordinator.setMaxAnimationFps(0) - assertEquals(Int.MAX_VALUE, locationAnimatorCoordinator.maxAnimationFps) - locationAnimatorCoordinator.setMaxAnimationFps(-1) - assertEquals(Int.MAX_VALUE, locationAnimatorCoordinator.maxAnimationFps) - } - - @Test - fun maxFps_givenToAnimator() { - locationAnimatorCoordinator.setMaxAnimationFps(5) - locationAnimatorCoordinator.feedNewLocation(Location(""), cameraPosition, false) - verify { animatorProvider.latLngAnimator(any(), any(), any(), 5) } - verify { animatorProvider.floatAnimator(any(), any(), any(), 5) } - } - - private fun getListenerHoldersSet(vararg animatorTypes: Int): Set { - return HashSet().also { - for (type in animatorTypes) { - it.add(AnimatorListenerHolder(type, mockk())) - } - } - } -} - -private fun SparseArray.contains(listener: AnimationsValueChangeListener<*>?): Boolean { - for (i in 0 until this.size()) { - val element = this.get(this.keyAt(i)) - if (element == listener) { - return true - } - } - return false -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java deleted file mode 100644 index d1b8642c3..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationCameraControllerTest.java +++ /dev/null @@ -1,1001 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.PointF; -import android.location.Location; - -import com.mapbox.android.gestures.AndroidGesturesManager; -import com.mapbox.android.gestures.MoveGestureDetector; -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.camera.CameraUpdate; -import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Projection; -import com.mapbox.mapboxsdk.maps.Transform; -import com.mapbox.mapboxsdk.maps.UiSettings; - -import junit.framework.Assert; - -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_CAMERA_LATLNG; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_TILT; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_ZOOM; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE_COMPASS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.NONE_GPS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_COMPASS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_GPS; -import static com.mapbox.mapboxsdk.location.modes.CameraMode.TRACKING_GPS_NORTH; -import static junit.framework.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class LocationCameraControllerTest { - - @Test - public void setCameraMode_mapTransitionsAreCancelled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING_GPS); - - verify(mapboxMap).cancelTransitions(); - } - - @Test - public void setCameraMode_gestureThresholdIsAdjusted() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - float moveThreshold = 5f; - when(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING_GPS); - - verify(moveGestureDetector).setMoveThreshold(moveThreshold); - } - - @Test - public void setCameraMode_gestureThresholdNotAdjustedWhenDisabled() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - float moveThreshold = 5f; - when(options.trackingInitialMoveThreshold()).thenReturn(moveThreshold); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - camera.setCameraMode(TRACKING_GPS); - - verify(moveGestureDetector, times(0)).setMoveThreshold(moveThreshold); - verify(moveGestureDetector, times(0)).setMoveThreshold(0f); - } - - @Test - public void setCameraMode_gestureThresholdIsResetWhenNotTracking() { - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(moveGestureDetector); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - camera.setCameraMode(NONE); - - verify(moveGestureDetector, times(2)).setMoveThreshold(0f); // one for initialization - } - - @Test - public void setCameraMode_notTrackingAdjustsFocalPoint() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING_GPS); - camera.setCameraMode(NONE); - - verify(mapboxMap.getUiSettings()).setFocalPoint(null); - } - - @Test - public void setCameraMode_trackingChangeListenerCameraDismissedIsCalled() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING_GPS); - camera.setCameraMode(NONE); - - verify(internalTrackingChangedListener).onCameraTrackingDismissed(); - } - - @Test - public void setCameraMode_internalCameraTrackingChangeListenerIsCalled() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = NONE; - - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_doNotNotifyAboutDuplicates_NONE() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = NONE; - - camera.setCameraMode(cameraMode); - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener, times(1)).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_doNotNotifyAboutDuplicates_TRACKING_GPS() { - OnCameraTrackingChangedListener internalTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - LocationCameraController camera = buildCamera(internalTrackingChangedListener); - camera.initializeOptions(mock(LocationComponentOptions.class)); - int cameraMode = TRACKING_GPS; - - camera.setCameraMode(cameraMode); - camera.setCameraMode(cameraMode); - - verify(internalTrackingChangedListener, times(1)).onCameraTrackingChanged(cameraMode); - } - - @Test - public void setCameraMode_cancelTransitionsWhenSet() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - when(mapboxMap.getProjection()).thenReturn(mock(Projection.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE_COMPASS); - verify(mapboxMap, times(1)).cancelTransitions(); - - camera.setCameraMode(NONE_GPS); - verify(mapboxMap, times(2)).cancelTransitions(); - - camera.setCameraMode(TRACKING); - verify(mapboxMap, times(3)).cancelTransitions(); - - camera.setCameraMode(TRACKING_COMPASS); - verify(mapboxMap, times(4)).cancelTransitions(); - - camera.setCameraMode(TRACKING_GPS); - verify(mapboxMap, times(5)).cancelTransitions(); - - camera.setCameraMode(TRACKING_GPS_NORTH); - verify(mapboxMap, times(6)).cancelTransitions(); - } - - @Test - public void setCameraMode_dontCancelTransitionsWhenNoneSet() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - when(mapboxMap.getProjection()).thenReturn(mock(Projection.class)); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE); - verify(mapboxMap, never()).cancelTransitions(); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingGpsNorthUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingGpsUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeTrackingCompassUpdatesLatLng() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_COMPASS); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewLatLngValue_focalPointIsAdjusted() { - MapboxMap mapboxMap = mock(MapboxMap.class); - UiSettings uiSettings = mock(UiSettings.class); - when(mapboxMap.getUiSettings()).thenReturn(uiSettings); - Projection projection = mock(Projection.class); - PointF pointF = mock(PointF.class); - when(projection.toScreenLocation(any(LatLng.class))).thenReturn(pointF); - when(mapboxMap.getProjection()).thenReturn(projection); - LocationCameraController camera = buildCamera(mapboxMap); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - camera.setCameraMode(TRACKING); - LatLng latLng = mock(LatLng.class); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - - verify(uiSettings).setFocalPoint(pointF); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingGpsUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeNoneGpsUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE_GPS); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingNorthUpdatesBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - CameraPosition cameraPosition = new CameraPosition.Builder().bearing(7d).build(); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeTrackingNorthBearingZeroIgnored() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - CameraPosition cameraPosition = new CameraPosition.Builder().bearing(0d).build(); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_GPS_NORTH); - float gpsBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(transform, times(0)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewGpsBearingValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeTrackingCompassUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING_COMPASS); - float compassBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeNoneCompassUpdatesBearing() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE_COMPASS); - float compassBearing = 5f; - - getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewCompassBearingValue_cameraModeNoneIgnored() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(NONE); - - assertNull(getAnimationListener(ANIMATOR_CAMERA_COMPASS_BEARING, camera.getAnimationListeners())); - verify(transform, times(0)).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNewZoomValue_cameraIsUpdated() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - float zoom = 5f; - - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(zoom); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void onNeTiltValue_cameraIsUpdated() { - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - camera.setCameraMode(TRACKING); - float tilt = 5f; - - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(tilt); - - verify(transform).moveCamera(any(MapboxMap.class), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void gesturesManagement_enabled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(initialGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - verify(mapboxMap).setGesturesManager(internalGesturesManager, true, true); - } - - @Test - public void gesturesManagement_disabled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(internalGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - verify(mapboxMap).setGesturesManager(initialGesturesManager, true, true); - } - - @Test - public void gesturesManagement_optionNotChangedInitial() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(initialGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(false); - camera.initializeOptions(options); - - verify(mapboxMap, times(0)).setGesturesManager(initialGesturesManager, true, true); - } - - @Test - public void gesturesManagement_optionNotChangedInternal() { - MapboxMap mapboxMap = mock(MapboxMap.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - when(mapboxMap.getGesturesManager()).thenReturn(internalGesturesManager); - LocationCameraController camera = buildCamera(mapboxMap, initialGesturesManager, internalGesturesManager); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.trackingGesturesManagement()).thenReturn(true); - camera.initializeOptions(options); - - verify(mapboxMap, times(0)).setGesturesManager(internalGesturesManager, true, true); - } - - @Test - public void onMove_notCancellingTransitionWhileNone() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(0)).cancelTransitions(); - verify(moveGestureDetector, times(0)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(0)).cancelTransitions(); - verify(moveGestureDetector, times(0)).interrupt(); - } - - @Test - public void onMove_cancellingTransitionWhileGps() { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(TRACKING); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - } - - @Test - public void onMove_cancellingTransitionWhileBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - LocationCameraController camera = buildCamera(mapboxMap); - camera.initializeOptions(mock(LocationComponentOptions.class)); - - camera.setCameraMode(NONE_COMPASS); - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - - // testing subsequent calls - camera.onMoveListener.onMove(moveGestureDetector); - verify(mapboxMap, times(1)).cancelTransitions(); - verify(moveGestureDetector, times(1)).interrupt(); - } - - @Test - public void transition_locationIsNull() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - - camera.setCameraMode(TRACKING, null, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - Assert.assertEquals(TRACKING, camera.getCameraMode()); - verify(listener).onLocationCameraTransitionFinished(TRACKING); - verify(transform, times(0)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_notTracking() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - camera.setCameraMode(NONE, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener, times(1)).onLocationCameraTransitionFinished(NONE); - verify(transform, times(0)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_trackingChanged() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionFinished(TRACKING); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener).onLocationCameraTransitionFinished(TRACKING); - verify(transform) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_trackingNotChanged() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionFinished(TRACKING_GPS_NORTH); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING_GPS_NORTH, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener, times(1)).onLocationCameraTransitionFinished(TRACKING_GPS_NORTH); - verify(transform, times(1)) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_canceled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - listener.onLocationCameraTransitionCanceled(TRACKING); - return null; - } - }).when(transform).animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - verify(listener).onLocationCameraTransitionCanceled(TRACKING); - verify(transform) - .animateCamera(eq(mapboxMap), any(CameraUpdate.class), any(Integer.class), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_mapboxCallbackFinished() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onFinish(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionFinished(TRACKING); - } - - @Test - public void transition_mapboxCallbackFinishedImmediately() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).moveCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onFinish(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionFinished(TRACKING); - } - - @Test - public void transition_mapboxCallbackCanceled() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - Assert.assertTrue(camera.isTransitioning()); - - callbackCaptor.getValue().onCancel(); - - Assert.assertFalse(camera.isTransitioning()); - - verify(listener).onLocationCameraTransitionCanceled(TRACKING); - } - - @Test - public void transition_mapboxAnimateBearing() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - camera.setCameraMode(TRACKING_GPS, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)).bearing(30); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_mapboxAnimateNorth() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - when(location.getLatitude()).thenReturn(1.0); - when(location.getLongitude()).thenReturn(1.0); - when(location.getBearing()).thenReturn(30f); - when(location.getAltitude()).thenReturn(0.0); - - camera.setCameraMode(TRACKING_GPS_NORTH, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - CameraPosition.Builder builder = new CameraPosition.Builder().target(new LatLng(location)).bearing(0); - verify(transform).animateCamera( - eq(mapboxMap), - eq(CameraUpdateFactory.newCameraPosition(builder.build())), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - any(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_animatorValuesDuringTransition() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - final OnLocationCameraTransitionListener listener = mock(OnLocationCameraTransitionListener.class); - Location location = mock(Location.class); - - ArgumentCaptor callbackCaptor - = ArgumentCaptor.forClass(MapboxMap.CancelableCallback.class); - - camera.setCameraMode(TRACKING_GPS, location, TRANSITION_ANIMATION_DURATION_MS, null, null, null, listener); - - verify(transform).animateCamera( - eq(mapboxMap), - any(CameraUpdate.class), - eq((int) TRANSITION_ANIMATION_DURATION_MS), - callbackCaptor.capture()); - - LatLng latLng = new LatLng(10, 10); - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(10f); - - verify(transform, times(0)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - - callbackCaptor.getValue().onFinish(); - - getAnimationListener(ANIMATOR_CAMERA_LATLNG, camera.getAnimationListeners()).onNewAnimationValue(latLng); - getAnimationListener(ANIMATOR_CAMERA_GPS_BEARING, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_TILT, camera.getAnimationListeners()).onNewAnimationValue(10f); - getAnimationListener(ANIMATOR_ZOOM, camera.getAnimationListeners()).onNewAnimationValue(10f); - - verify(transform, times(4)).moveCamera(eq(mapboxMap), any(CameraUpdate.class), - nullable(MapboxMap.CancelableCallback.class)); - } - - @Test - public void transition_customAnimation() { - MapboxMap mapboxMap = mock(MapboxMap.class); - Transform transform = mock(Transform.class); - when(mapboxMap.getCameraPosition()).thenReturn(CameraPosition.DEFAULT); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - LocationCameraController camera = buildCamera(mapboxMap, transform); - camera.initializeOptions(mock(LocationComponentOptions.class)); - Location location = mock(Location.class); - CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition( - new CameraPosition.Builder() - .target(new LatLng(location)) - .zoom(14.0) - .bearing(13.0) - .tilt(45.0) - .build() - ); - - camera.setCameraMode(TRACKING, location, 1200, 14.0, 13.0, 45.0, null); - verify(transform) - .animateCamera(eq(mapboxMap), eq(cameraUpdate), eq(1200), any(MapboxMap.CancelableCallback.class)); - } - - private LocationCameraController buildCamera(OnCameraTrackingChangedListener onCameraTrackingChangedListener) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Transform transform = mock(Transform.class); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MoveGestureDetector moveGestureDetector) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Transform transform = mock(Transform.class); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap) { - Transform transform = mock(Transform.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(Transform transform) { - MapboxMap mapboxMap = mock(MapboxMap.class); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - Projection projection = mock(Projection.class); - when(mapboxMap.getProjection()).thenReturn(projection); - when(projection.getMetersPerPixelAtLatitude(any(Double.class))).thenReturn(Double.valueOf(1000)); - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap, Transform transform) { - when(mapboxMap.getUiSettings()).thenReturn(mock(UiSettings.class)); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - AndroidGesturesManager initialGesturesManager = mock(AndroidGesturesManager.class); - AndroidGesturesManager internalGesturesManager = mock(AndroidGesturesManager.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private LocationCameraController buildCamera(MapboxMap mapboxMap, AndroidGesturesManager initialGesturesManager, - AndroidGesturesManager internalGesturesManager) { - Transform transform = mock(Transform.class); - MoveGestureDetector moveGestureDetector = mock(MoveGestureDetector.class); - OnCameraTrackingChangedListener onCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener.class); - OnCameraMoveInvalidateListener onCameraMoveInvalidateListener = mock(OnCameraMoveInvalidateListener.class); - return new LocationCameraController(mapboxMap, transform, moveGestureDetector, - onCameraTrackingChangedListener, onCameraMoveInvalidateListener, initialGesturesManager, internalGesturesManager); - } - - private MapboxAnimator.AnimationsValueChangeListener getAnimationListener( - @MapboxAnimator.Type int animatorType, - Set holders) { - for (AnimatorListenerHolder holder : holders) { - @MapboxAnimator.Type int type = holder.getAnimatorType(); - if (type == animatorType) { - return holder.getListener(); - } - } - - return null; - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java deleted file mode 100644 index 2660c819d..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentActivationOptionsTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; -import android.support.annotation.NonNull; - -import com.mapbox.mapboxsdk.R; -import com.mapbox.mapboxsdk.maps.Style; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.junit.MockitoRule; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class LocationComponentActivationOptionsTest { - - @Mock - private Context context; - @Mock - private TypedArray array; - @Mock - private Resources resources; - @Mock - private Style style; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @NonNull - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - when(context.obtainStyledAttributes(R.style.mapbox_LocationComponent, R.styleable.mapbox_LocationComponent)) - .thenReturn(array); - when(array.getResourceId(R.styleable.mapbox_LocationComponent_mapbox_foregroundDrawable, -1)) - .thenReturn(R.drawable.mapbox_user_icon); - when(context.getResources()).thenReturn(resources); - } - - @Test - public void sanity() throws Exception { - when(style.isFullyLoaded()).thenReturn(true); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - assertNotNull(locationComponentOptions); - - LocationComponentActivationOptions locationComponentActivationOptions = - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .useDefaultLocationEngine(true) - .build(); - assertNotNull(locationComponentActivationOptions); - } - - @Test - public void includingBothStyleResAndComponentOptions_causesExceptionToBeThrown() throws Exception { - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("You've provided both a style resource and a LocationComponentOptions" - + " object to the LocationComponentActivationOptions builder. You can't use both and " - + "you must choose one of the two to style the LocationComponent."); - - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - - LocationComponentActivationOptions.builder(context, style) - .locationComponentOptions(locationComponentOptions) - .styleRes(R.style.mapbox_LocationComponent) - .build(); - } - - @Test - public void nullContext_causesExceptionToBeThrown() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Context in LocationComponentActivationOptions is null."); - - LocationComponentActivationOptions.builder(null, style) - .build(); - } - - @Test - public void nullStyle_causesExceptionToBeThrown() throws Exception { - thrown.expect(NullPointerException.class); - thrown.expectMessage("Style in LocationComponentActivationOptions is null. Make sure the Style object isn't null." - + " Wait for the map to fully load before passing the Style object to LocationComponentActivationOptions."); - - LocationComponentActivationOptions.builder(context, null) - .build(); - } - - @Test - public void locationComponent_exceptionThrownWithDefaultLocationEngineButNotFullyLoadedStyle() throws Exception { - - when(style.isFullyLoaded()).thenReturn(false); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Style in LocationComponentActivationOptions isn't fully loaded. Wait for the " - + "map to fully load before passing the Style object to " - + "LocationComponentActivationOptions."); - - LocationComponentActivationOptions.builder(context, style) - .build(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java deleted file mode 100644 index b1e1f14cb..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentOptionsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.content.Context; -import android.content.res.Resources; -import android.content.res.TypedArray; - -import android.support.annotation.NonNull; -import com.mapbox.mapboxsdk.R; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class LocationComponentOptionsTest { - - @Mock - private Context context; - @Mock - private TypedArray array; - @Mock - private Resources resources; - - @NonNull - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - when(context.obtainStyledAttributes(R.style.mapbox_LocationComponent, R.styleable.mapbox_LocationComponent)) - .thenReturn(array); - when(array.getResourceId(R.styleable.mapbox_LocationComponent_mapbox_foregroundDrawable, -1)) - .thenReturn(R.drawable.mapbox_user_icon); - when(context.getResources()).thenReturn(resources); - } - - @Test - public void sanity() throws Exception { - LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(context) - .accuracyAlpha(0.5f) - .build(); - assertNotNull(locationComponentOptions); - } - - @Test - public void passingOutOfRangeAccuracyAlpha_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Accuracy alpha value must be between 0.0 and " - + "1.0."); - LocationComponentOptions.builder(context) - .accuracyAlpha(2f) - .build(); - } - - @Test - public void negativeElevation_causesExceptionToBeThrown() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Invalid shadow size -500.0. Must be >= 0"); - LocationComponentOptions.builder(context) - .elevation(-500) - .build(); - } - - @Test - public void passingBothLayerPositionOptions_throwsException() throws Exception { - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("You cannot set both layerAbove and layerBelow options." - + "Choose one or the other."); - LocationComponentOptions.builder(context) - .layerAbove("above") - .layerBelow("below") - .build(); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManagerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManagerTest.kt deleted file mode 100644 index c8a75b670..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentPositionManagerTest.kt +++ /dev/null @@ -1,130 +0,0 @@ -package com.mapbox.mapboxsdk.location - -import com.mapbox.mapboxsdk.maps.Style -import com.mapbox.mapboxsdk.style.layers.Layer -import io.mockk.mockk -import io.mockk.verify -import junit.framework.Assert.assertFalse -import junit.framework.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.junit.MockitoJUnitRunner - -@RunWith(MockitoJUnitRunner::class) -class LocationComponentPositionManagerTest { - - private lateinit var style: Style - private lateinit var layer: Layer - - @Before - fun setup() { - style = mockk(relaxed = true) - layer = mockk(relaxed = true) - } - - @Test - fun update_noChange_null() { - val positionManager = LocationComponentPositionManager(style, null, null) - val requiresUpdate = positionManager.update(null, null) - assertFalse(requiresUpdate) - } - - @Test - fun update_noChange_above() { - val positionManager = LocationComponentPositionManager(style, "above", null) - val requiresUpdate = positionManager.update("above", null) - assertFalse(requiresUpdate) - } - - @Test - fun update_noChange_below() { - val positionManager = LocationComponentPositionManager(style, null, "below") - val requiresUpdate = positionManager.update(null, "below") - assertFalse(requiresUpdate) - } - - @Test - fun update_fromNull_above() { - val positionManager = LocationComponentPositionManager(style, null, null) - val requiresUpdate = positionManager.update("above", null) - assertTrue(requiresUpdate) - } - - @Test - fun update_fromNull_below() { - val positionManager = LocationComponentPositionManager(style, null, null) - val requiresUpdate = positionManager.update(null, "below") - assertTrue(requiresUpdate) - } - - @Test - fun update_toNull_above() { - val positionManager = LocationComponentPositionManager(style, "above", null) - val requiresUpdate = positionManager.update(null, null) - assertTrue(requiresUpdate) - } - - @Test - fun update_toNull_below() { - val positionManager = LocationComponentPositionManager(style, null, "below") - val requiresUpdate = positionManager.update(null, null) - assertTrue(requiresUpdate) - } - - @Test - fun update_fromValue_above() { - val positionManager = LocationComponentPositionManager(style, "above1", null) - val requiresUpdate = positionManager.update("above2", null) - assertTrue(requiresUpdate) - } - - @Test - fun update_fromValue_below() { - val positionManager = LocationComponentPositionManager(style, null, "below1") - val requiresUpdate = positionManager.update(null, "below2") - assertTrue(requiresUpdate) - } - - @Test - fun addLayer_noModifier() { - val positionManager = LocationComponentPositionManager(style, null, null) - positionManager.addLayerToMap(layer) - - verify { style.addLayer(layer) } - } - - @Test - fun addLayer_above() { - val positionManager = LocationComponentPositionManager(style, "above", null) - positionManager.addLayerToMap(layer) - - verify { style.addLayerAbove(layer, "above") } - } - - @Test - fun addLayer_below() { - val positionManager = LocationComponentPositionManager(style, null, "below") - positionManager.addLayerToMap(layer) - - verify { style.addLayerBelow(layer, "below") } - } - - @Test - fun addLayer_afterUpdate_above() { - val positionManager = LocationComponentPositionManager(style, null, null) - positionManager.update("above", null) - positionManager.addLayerToMap(layer) - - verify { style.addLayerAbove(layer, "above") } - } - - @Test - fun addLayer_afterUpdate_below() { - val positionManager = LocationComponentPositionManager(style, null, null) - positionManager.update(null, "below") - positionManager.addLayerToMap(layer) - - verify { style.addLayerBelow(layer, "below") } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentTest.kt deleted file mode 100644 index 2994c29d5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationComponentTest.kt +++ /dev/null @@ -1,453 +0,0 @@ -package com.mapbox.mapboxsdk.location - -import android.content.Context -import android.content.res.Resources -import android.content.res.TypedArray -import android.location.Location -import android.os.Looper -import com.mapbox.android.core.location.LocationEngine -import com.mapbox.android.core.location.LocationEngineRequest -import com.mapbox.mapboxsdk.R -import com.mapbox.mapboxsdk.camera.CameraPosition -import com.mapbox.mapboxsdk.location.LocationComponentConstants.TRANSITION_ANIMATION_DURATION_MS -import com.mapbox.mapboxsdk.location.modes.CameraMode -import com.mapbox.mapboxsdk.location.modes.RenderMode -import com.mapbox.mapboxsdk.maps.MapboxMap -import com.mapbox.mapboxsdk.maps.Style -import com.mapbox.mapboxsdk.maps.Transform -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.ArgumentCaptor -import org.mockito.Mock -import org.mockito.Mockito.* -import org.mockito.MockitoAnnotations -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class LocationComponentTest { - private lateinit var locationComponent: LocationComponent - - @Mock - private lateinit var locationComponentOptions: LocationComponentOptions - - @Mock - private lateinit var mapboxMap: MapboxMap - - @Mock - private lateinit var transform: Transform - - @Mock - private lateinit var context: Context - - @Mock - private lateinit var locationEngine: LocationEngine - - @Mock - private lateinit var locationEngineRequest: LocationEngineRequest - - @Mock - private lateinit var currentListener: LocationComponent.CurrentLocationEngineCallback - - @Mock - private lateinit var lastListener: LocationComponent.LastLocationEngineCallback - - @Mock - private lateinit var compassEngine: CompassEngine - - @Mock - private lateinit var locationLayerController: LocationLayerController - - @Mock - private lateinit var locationCameraController: LocationCameraController - - @Mock - private lateinit var locationAnimatorCoordinator: LocationAnimatorCoordinator - - @Mock - private lateinit var staleStateManager: StaleStateManager - - @Mock - private lateinit var locationEngineProvider: LocationComponent.InternalLocationEngineProvider - - @Mock - private lateinit var style: Style - - private lateinit var developerAnimationListeners: List - - @Before - fun before() { - MockitoAnnotations.initMocks(this) - developerAnimationListeners = mutableListOf() - locationComponent = LocationComponent(mapboxMap, transform, developerAnimationListeners, currentListener, lastListener, locationLayerController, locationCameraController, locationAnimatorCoordinator, staleStateManager, compassEngine, locationEngineProvider) - doReturn(locationEngine).`when`(locationEngineProvider).getBestLocationEngine(context, false) - doReturn(style).`when`(mapboxMap).style - } - - @Test - fun activateWithRequestTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - - Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest) - - doReturn(mock(TypedArray::class.java)).`when`(context) - .obtainStyledAttributes(R.style.mapbox_LocationComponent, R.styleable.mapbox_LocationComponent) - - val resources = mock(Resources::class.java) - - doReturn(resources).`when`(context).resources - doReturn(0f).`when`(resources) - .getDimension(R.dimen.mapbox_locationComponentTrackingMultiFingerMoveThreshold) - doReturn(0f).`when`(resources) - .getDimension(R.dimen.mapbox_locationComponentTrackingMultiFingerMoveThreshold) - locationComponent.activateLocationComponent(context, mock(Style::class.java), true, locationEngineRequest) - Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest) - } - - @Test - fun activateWithDefaultLocationEngineRequestAndOptionsTestDefaultLocationEngine() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), true, locationEngineRequest, locationComponentOptions) - Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest) - Assert.assertNotNull(locationComponent.locationEngine) - } - - @Test - fun activateWithDefaultLocationEngineRequestAndOptionsTestCustomLocationEngine() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), false, locationEngineRequest, locationComponentOptions) - Assert.assertEquals(locationEngineRequest, locationComponent.locationEngineRequest) - Assert.assertNull(locationComponent.locationEngine) - } - - @Test - fun locationUpdatesWhenEnabledDisableTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - verify(locationEngine, times(0)).removeLocationUpdates(currentListener) - verify(locationEngine, times(0)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java)) - - locationComponent.onStart() - verify(locationEngine, times(0)).removeLocationUpdates(currentListener) - verify(locationEngine, times(0)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java)) - - locationComponent.isLocationComponentEnabled = true - verify(locationEngine).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java)) - - locationComponent.isLocationComponentEnabled = false - verify(locationEngine).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java)) - verify(locationEngine).removeLocationUpdates(currentListener) - } - - @Test - fun locationUpdatesWhenStartedStoppedTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - - locationComponent.onStop() - verify(locationEngine).removeLocationUpdates(currentListener) - - locationComponent.onStart() - verify(locationEngine, times(2)).requestLocationUpdates(eq(locationEngineRequest), eq(currentListener), any(Looper::class.java)) - } - - @Test - fun locationUpdatesWhenNewRequestTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - - val newRequest = mock(LocationEngineRequest::class.java) - locationComponent.locationEngineRequest = newRequest - verify(locationEngine).removeLocationUpdates(currentListener) - verify(locationEngine).requestLocationUpdates(eq(newRequest), eq(currentListener), any(Looper::class.java)) - } - - @Test - fun lastLocationUpdateOnStartTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - - verify(locationEngine).getLastLocation(lastListener) - } - - @Test - fun transitionCallbackFinishedTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - val listener = mock(OnLocationCameraTransitionListener::class.java) - - val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java) - locationComponent.setCameraMode(CameraMode.TRACKING, listener) - verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull(), isNull(), isNull(), callback.capture()) - callback.value.onLocationCameraTransitionFinished(CameraMode.TRACKING) - - verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) - verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false) - } - - @Test - fun transitionCallbackCanceledTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - val listener = mock(OnLocationCameraTransitionListener::class.java) - - val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java) - locationComponent.setCameraMode(CameraMode.TRACKING, listener) - verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull(), isNull(), isNull(), callback.capture()) - callback.value.onLocationCameraTransitionCanceled(CameraMode.TRACKING) - - verify(listener).onLocationCameraTransitionCanceled(CameraMode.TRACKING) - verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false) - } - - @Test - fun transitionCustomFinishedTest() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - val listener = mock(OnLocationCameraTransitionListener::class.java) - - val callback = ArgumentCaptor.forClass(OnLocationCameraTransitionListener::class.java) - locationComponent.setCameraMode(CameraMode.TRACKING, 1200, 14.0, 13.0, 45.0, listener) - verify(locationCameraController).setCameraMode(eq(CameraMode.TRACKING), any(), eq(1200L), eq(14.0), eq(13.0), eq(45.0), callback.capture()) - callback.value.onLocationCameraTransitionFinished(CameraMode.TRACKING) - - verify(listener).onLocationCameraTransitionFinished(CameraMode.TRACKING) - verify(locationAnimatorCoordinator).resetAllCameraAnimations(CameraPosition.DEFAULT, false) - } - - @Test - fun compass_listenWhenConsumedByNoneCamera() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationCameraController.isConsumingCompass).thenReturn(true) - locationComponent.cameraMode = CameraMode.NONE_COMPASS - verify(compassEngine).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_listenWhenConsumedByTrackingCamera() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationCameraController.isConsumingCompass).thenReturn(true) - locationComponent.cameraMode = CameraMode.TRACKING_COMPASS - verify(compassEngine).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_listenWhenConsumedByLayer() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - verify(compassEngine).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_notListenWhenNotConsumed() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(false) - `when`(locationCameraController.isConsumingCompass).thenReturn(false) - locationComponent.renderMode = RenderMode.GPS - locationComponent.renderMode = RenderMode.NORMAL - locationComponent.cameraMode = CameraMode.TRACKING - locationComponent.cameraMode = CameraMode.NONE - locationComponent.cameraMode = CameraMode.NONE_GPS - locationComponent.cameraMode = CameraMode.TRACKING_GPS - locationComponent.cameraMode = CameraMode.TRACKING_GPS_NORTH - verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_removeListenerOnChange() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - `when`(locationLayerController.isConsumingCompass).thenReturn(false) - locationComponent.renderMode = RenderMode.NORMAL - verify(compassEngine).removeCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_removeListenerOnStop() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - locationComponent.onStop() - verify(compassEngine).removeCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_reAddListenerOnStart() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - locationComponent.onStop() - locationComponent.onStart() - verify(compassEngine, times(2)).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_removeListenerOnStyleStartLoad() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - locationComponent.onStartLoadingMap() - verify(compassEngine).removeCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_reAddListenerOnStyleLoadFinished() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - locationComponent.onStartLoadingMap() - locationComponent.onFinishLoadingStyle() - verify(compassEngine, times(2)).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_reAddListenerOnlyWhenEnabled() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - locationComponent.isLocationComponentEnabled = false - - locationComponent.onStartLoadingMap() - locationComponent.onFinishLoadingStyle() - verify(compassEngine).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_notAdListenerWhenDisabled() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.onStart() - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun compass_notAdListenerWhenStopped() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.isLocationComponentEnabled = true - `when`(mapboxMap.cameraPosition).thenReturn(CameraPosition.DEFAULT) - - `when`(locationLayerController.isConsumingCompass).thenReturn(true) - locationComponent.renderMode = RenderMode.COMPASS - verify(compassEngine, never()).addCompassListener(any(CompassListener::class.java)) - } - - @Test - fun developerAnimationCalled() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.isLocationComponentEnabled = true - for (listener in developerAnimationListeners) { - listener.onDeveloperAnimationStarted() - } - verify(locationCameraController).setCameraMode(eq(CameraMode.NONE), isNull(), eq(TRANSITION_ANIMATION_DURATION_MS), isNull(), isNull(), isNull(), any()) - } - - @Test - fun internal_cameraTrackingChangedListener_onCameraTrackingDismissed() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.isLocationComponentEnabled = true - - val cameraChangeListener: OnCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener::class.java) - locationComponent.addOnCameraTrackingChangedListener(cameraChangeListener) - - locationComponent.cameraTrackingChangedListener.onCameraTrackingDismissed() - - verify(cameraChangeListener).onCameraTrackingDismissed() - } - - @Test - fun internal_cameraTrackingChangedListener_onCameraTrackingChanged() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.isLocationComponentEnabled = true - - val cameraValueListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java) - val layerValueListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java) - `when`(locationCameraController.animationListeners).thenReturn(setOf(cameraValueListener)) - `when`(locationLayerController.animationListeners).thenReturn(setOf(layerValueListener)) - val cameraChangeListener: OnCameraTrackingChangedListener = mock(OnCameraTrackingChangedListener::class.java) - locationComponent.addOnCameraTrackingChangedListener(cameraChangeListener) - - locationComponent.cameraTrackingChangedListener.onCameraTrackingChanged(CameraMode.TRACKING_GPS) - - verify(locationAnimatorCoordinator).cancelZoomAnimation() - verify(locationAnimatorCoordinator).cancelTiltAnimation() - verify(locationAnimatorCoordinator).updateAnimatorListenerHolders(eq(setOf(cameraValueListener, layerValueListener))) - verify(locationAnimatorCoordinator).resetAllCameraAnimations(any(), anyBoolean()) - verify(locationAnimatorCoordinator).resetAllLayerAnimations() - verify(cameraChangeListener).onCameraTrackingChanged(CameraMode.TRACKING_GPS) - } - - @Test - fun internal_renderModeChangedListener_onRenderModeChanged() { - locationComponent.activateLocationComponent(context, mock(Style::class.java), locationEngine, locationEngineRequest, locationComponentOptions) - locationComponent.isLocationComponentEnabled = true - - val cameraListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java) - val layerListener: AnimatorListenerHolder = mock(AnimatorListenerHolder::class.java) - `when`(locationCameraController.animationListeners).thenReturn(setOf(cameraListener)) - `when`(locationLayerController.animationListeners).thenReturn(setOf(layerListener)) - val renderChangeListener: OnRenderModeChangedListener = mock(OnRenderModeChangedListener::class.java) - locationComponent.addOnRenderModeChangedListener(renderChangeListener) - - locationComponent.renderModeChangedListener.onRenderModeChanged(RenderMode.NORMAL) - - verify(locationAnimatorCoordinator).updateAnimatorListenerHolders(eq(setOf(cameraListener, layerListener))) - verify(locationAnimatorCoordinator).resetAllCameraAnimations(any(), anyBoolean()) - verify(locationAnimatorCoordinator).resetAllLayerAnimations() - verify(renderChangeListener).onRenderModeChanged(RenderMode.NORMAL) - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java deleted file mode 100644 index ed2d015d8..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/LocationLayerControllerTest.java +++ /dev/null @@ -1,718 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import android.graphics.Bitmap; -import android.support.annotation.NonNull; - -import com.google.gson.JsonElement; -import com.mapbox.geojson.Feature; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.location.modes.RenderMode; -import com.mapbox.mapboxsdk.maps.MapboxMap; -import com.mapbox.mapboxsdk.maps.Style; -import com.mapbox.mapboxsdk.style.layers.Layer; -import com.mapbox.mapboxsdk.style.sources.GeoJsonSource; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import java.util.Set; - -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.ACCURACY_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BACKGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.BEARING_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_LAYER; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.FOREGROUND_STALE_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.LOCATION_SOURCE; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_ACCURACY_RADIUS; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_FOREGROUND_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.PROPERTY_SHADOW_ICON_OFFSET; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_ICON; -import static com.mapbox.mapboxsdk.location.LocationComponentConstants.SHADOW_LAYER; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_ACCURACY; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_COMPASS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_GPS_BEARING; -import static com.mapbox.mapboxsdk.location.MapboxAnimator.ANIMATOR_LAYER_LATLNG; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class LocationLayerControllerTest { - - private MapboxMap mapboxMap = mock(MapboxMap.class); - private Style style = mock(Style.class); - - @Before - public void before() { - when(mapboxMap.getStyle()).thenReturn(style); - } - - @Test - public void onInitialization_locationSourceIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addSource(locationSource); - } - - @Test - public void onInitialization_shadowLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer shadowLayer = mock(Layer.class); - when(sourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addLayerBelow(shadowLayer, BACKGROUND_LAYER); - } - - @Test - public void onInitialization_backgroundLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer backgroundLayer = mock(Layer.class); - when(sourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addLayerBelow(backgroundLayer, FOREGROUND_LAYER); - } - - @Test - public void onInitialization_foregroundLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer foregroundLayer = mock(Layer.class); - when(sourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addLayerBelow(foregroundLayer, BEARING_LAYER); - } - - @Test - public void onInitialization_bearingLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer bearingLayer = mock(Layer.class); - when(sourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addLayerBelow(bearingLayer, layerBelow); - } - - @Test - public void onInitialization_accuracyLayerIsAdded() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - Layer accuracyLayer = mock(Layer.class); - when(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addLayerBelow(accuracyLayer, BACKGROUND_LAYER); - } - - @Test - public void onInitialization_numberOfCachedLayerIdsIsConstant() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - controller.initializeComponents(mapboxMap.getStyle(), options); - - assertEquals(5, controller.layerSet.size()); - } - - @Test - public void applyStyle_styleShadowWithValidElevation() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.elevation()).thenReturn(2f); - - // Style is applied on initialization - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(SHADOW_ICON, bitmap); - } - - @Test - public void applyStyle_ignoreStyleShadowWithInvalidElevation() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - LocationComponentOptions options = mock(LocationComponentOptions.class); - when(options.elevation()).thenReturn(0f); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style, times(0)).addImage(SHADOW_ICON, bitmap); - } - - @Test - public void applyStyle_styleForegroundFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawable()).thenReturn(drawableResId); - when(options.foregroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(FOREGROUND_ICON, bitmap); - } - - @Test - public void applyStyle_styleForegroundStaleFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawableStale()).thenReturn(drawableResId); - when(options.foregroundStaleTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(FOREGROUND_STALE_ICON, bitmap); - } - - @Test - public void applyStyle_styleBackgroundFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.backgroundDrawable()).thenReturn(drawableResId); - when(options.backgroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(BACKGROUND_ICON, bitmap); - } - - @Test - public void applyStyle_styleBackgroundStaleFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.backgroundDrawableStale()).thenReturn(drawableResId); - when(options.backgroundStaleTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(BACKGROUND_STALE_ICON, bitmap); - } - - @Test - public void applyStyle_styleBearingFromOptions() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.bearingDrawable()).thenReturn(drawableResId); - when(options.bearingTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(BEARING_ICON, bitmap); - } - - @Test - public void applyStyle_layerBelowChanged() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - Layer bearingLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer2); - Layer foregroundLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer2); - Layer backgroundLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer2); - Layer shadowLayer2 = mock(Layer.class); - when(sourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer2); - Layer accuracyLayer2 = mock(Layer.class); - when(sourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer2); - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - layerController.applyStyle(options); - - verify(style).removeLayer(BEARING_LAYER); - verify(style).removeLayer(FOREGROUND_LAYER); - verify(style).removeLayer(BACKGROUND_LAYER); - verify(style).removeLayer(SHADOW_LAYER); - verify(style).removeLayer(ACCURACY_LAYER); - - verify(style).addLayerBelow(bearingLayer2, layerBelow); - verify(style).addLayerBelow(foregroundLayer2, BEARING_LAYER); - verify(style).addLayerBelow(backgroundLayer2, FOREGROUND_LAYER); - verify(style).addLayerBelow(shadowLayer2, BACKGROUND_LAYER); - verify(style).addLayerBelow(accuracyLayer2, BACKGROUND_LAYER); - } - - @Test - public void applyStyle_layerBelowNotChanged() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - String layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - options = mock(LocationComponentOptions.class); - layerBelow = "layer-below"; - when(options.layerBelow()).thenReturn(layerBelow); - layerController.applyStyle(options); - - verify(style, times(0)).removeLayer(any(String.class)); - verify(style, times(5)).addLayerBelow(any(Layer.class), any(String.class)); - } - - @Test - public void applyStyle_layerBelowNotChangedNull() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateShadowBitmap(any(LocationComponentOptions.class))).thenReturn(bitmap); - - LocationLayerController layerController = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - options = mock(LocationComponentOptions.class); - layerController.applyStyle(options); - - verify(style, times(0)).removeLayer(any(String.class)); - verify(style, times(1)).addLayer(any(Layer.class)); - verify(style, times(4)).addLayerBelow(any(Layer.class), Mockito.any()); - } - - @Test - public void updateForegroundOffset_foregroundIconPropertyIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - - layer.updateForegroundOffset(2d); - - verify(locationFeature).addProperty(eq(PROPERTY_FOREGROUND_ICON_OFFSET), any(JsonElement.class)); - } - - @Test - public void updateForegroundOffset_shadowPropertyIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.updateForegroundOffset(2d); - - verify(locationFeature).addProperty(eq(PROPERTY_SHADOW_ICON_OFFSET), any(JsonElement.class)); - } - - @Test - public void onNewLatLngValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - - getAnimationListener(ANIMATOR_LAYER_LATLNG, layer.getAnimationListeners()).onNewAnimationValue(new LatLng()); - - // wanted twice (once for initialization) - verify(locationSource, times(2)).setGeoJson(locationFeature); - } - - @Test - public void onNewGpsBearingValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.GPS); - float gpsBearing = 2f; - - getAnimationListener(ANIMATOR_LAYER_GPS_BEARING, layer.getAnimationListeners()).onNewAnimationValue(gpsBearing); - - verify(locationFeature).addNumberProperty(PROPERTY_GPS_BEARING, gpsBearing); - } - - @Test - public void onNewGpsBearingValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.COMPASS); - float gpsBearing = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_GPS_BEARING, layer.getAnimationListeners())); - verify(locationFeature, times(0)).addNumberProperty(PROPERTY_GPS_BEARING, gpsBearing); - } - - @Test - public void onNewCompassBearingValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.COMPASS); - float compassBearing = 2f; - - getAnimationListener(ANIMATOR_LAYER_COMPASS_BEARING, layer.getAnimationListeners()) - .onNewAnimationValue(compassBearing); - - verify(locationFeature).addNumberProperty(PROPERTY_COMPASS_BEARING, compassBearing); - } - - @Test - public void onNewCompassBearingValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.GPS); - float compassBearing = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_COMPASS_BEARING, layer.getAnimationListeners())); - verify(locationFeature, times(0)).addNumberProperty(PROPERTY_COMPASS_BEARING, compassBearing); - } - - @Test - public void onNewAccuracyRadiusValue_locationFeatureIsUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.NORMAL); - float accuracyRadiusValue = 2f; - - getAnimationListener(ANIMATOR_LAYER_ACCURACY, layer.getAnimationListeners()) - .onNewAnimationValue(accuracyRadiusValue); - - verify(locationFeature).addNumberProperty(PROPERTY_ACCURACY_RADIUS, accuracyRadiusValue); - } - - @Test - public void onNewAccuracyRadiusValue_updateIgnoredWithInvalidRenderMode() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(style.getSourceAs(LOCATION_SOURCE)).thenReturn(locationSource); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - Feature locationFeature = mock(Feature.class); - LocationLayerController layer = new LocationLayerController( - mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(locationFeature, options), - bitmapProvider, options, internalRenderModeChangedListener - ); - layer.setRenderMode(RenderMode.GPS); - float accuracyRadiusValue = 2f; - - assertNull(getAnimationListener(ANIMATOR_LAYER_ACCURACY, layer.getAnimationListeners())); - verify(locationFeature, times(0)) - .addNumberProperty(PROPERTY_ACCURACY_RADIUS, accuracyRadiusValue); - } - - @Test - public void renderModeChanged_doNotNotifyAboutDuplicates_NORMAL() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - controller.setRenderMode(RenderMode.NORMAL); - controller.setRenderMode(RenderMode.NORMAL); - - verify(internalRenderModeChangedListener, times(1)).onRenderModeChanged(RenderMode.NORMAL); - } - - @Test - public void renderModeChanged_doNotNotifyAboutDuplicates_GPS() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - GeoJsonSource locationSource = mock(GeoJsonSource.class); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(locationSource); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - LocationComponentOptions options = mock(LocationComponentOptions.class); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - controller.setRenderMode(RenderMode.GPS); - controller.setRenderMode(RenderMode.GPS); - - verify(internalRenderModeChangedListener, times(1)).onRenderModeChanged(RenderMode.GPS); - } - - @Test - public void layerHidden_renderModeChanged_layerShown_foregroundIconUpdated() { - OnRenderModeChangedListener internalRenderModeChangedListener = mock(OnRenderModeChangedListener.class); - LayerSourceProvider sourceProvider = buildLayerProvider(); - when(sourceProvider.generateSource(any(Feature.class))).thenReturn(mock(GeoJsonSource.class)); - LocationComponentOptions options = mock(LocationComponentOptions.class); - int drawableResId = 123; - int tintColor = 456; - when(options.foregroundDrawable()).thenReturn(drawableResId); - when(options.foregroundTintColor()).thenReturn(tintColor); - LayerBitmapProvider bitmapProvider = mock(LayerBitmapProvider.class); - Bitmap bitmap = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableResId, tintColor)).thenReturn(bitmap); - - LocationLayerController controller = - new LocationLayerController(mapboxMap, mapboxMap.getStyle(), sourceProvider, buildFeatureProvider(options), - bitmapProvider, options, internalRenderModeChangedListener); - - verify(style).addImage(FOREGROUND_ICON, bitmap); - - int drawableGpsResId = 789; - when(options.gpsDrawable()).thenReturn(drawableGpsResId); - - Bitmap bitmapGps = mock(Bitmap.class); - when(bitmapProvider.generateBitmap(drawableGpsResId, tintColor)).thenReturn(bitmapGps); - - controller.hide(); - - controller.setRenderMode(RenderMode.GPS); - - controller.show(); - - verify(style).addImage(FOREGROUND_ICON, bitmapGps); - } - - private LayerFeatureProvider buildFeatureProvider(@NonNull LocationComponentOptions options) { - LayerFeatureProvider provider = mock(LayerFeatureProvider.class); - when(provider.generateLocationFeature(null, options)).thenReturn(mock(Feature.class)); - return provider; - } - - private LayerFeatureProvider buildFeatureProvider(Feature feature, @NonNull LocationComponentOptions options) { - LayerFeatureProvider provider = mock(LayerFeatureProvider.class); - when(provider.generateLocationFeature(null, options)).thenReturn(feature); - return provider; - } - - private LayerSourceProvider buildLayerProvider() { - LayerSourceProvider layerSourceProvider = mock(LayerSourceProvider.class); - - Layer shadowLayer = mock(Layer.class); - when(shadowLayer.getId()).thenReturn(SHADOW_LAYER); - when(layerSourceProvider.generateLayer(SHADOW_LAYER)).thenReturn(shadowLayer); - - Layer backgroundLayer = mock(Layer.class); - when(backgroundLayer.getId()).thenReturn(BACKGROUND_LAYER); - when(layerSourceProvider.generateLayer(BACKGROUND_LAYER)).thenReturn(backgroundLayer); - - Layer foregroundLayer = mock(Layer.class); - when(foregroundLayer.getId()).thenReturn(FOREGROUND_LAYER); - when(layerSourceProvider.generateLayer(FOREGROUND_LAYER)).thenReturn(foregroundLayer); - - Layer bearingLayer = mock(Layer.class); - when(bearingLayer.getId()).thenReturn(BEARING_LAYER); - when(layerSourceProvider.generateLayer(BEARING_LAYER)).thenReturn(bearingLayer); - - Layer accuracyLayer = mock(Layer.class); - when(accuracyLayer.getId()).thenReturn(ACCURACY_LAYER); - when(layerSourceProvider.generateAccuracyLayer()).thenReturn(accuracyLayer); - return layerSourceProvider; - } - - private MapboxAnimator.AnimationsValueChangeListener getAnimationListener( - @MapboxAnimator.Type int animatorType, - Set holders) { - for (AnimatorListenerHolder holder : holders) { - @MapboxAnimator.Type int type = holder.getAnimatorType(); - if (type == animatorType) { - return holder.getListener(); - } - } - return null; - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/MapboxAnimatorTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/MapboxAnimatorTest.kt deleted file mode 100644 index 7c126c783..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/MapboxAnimatorTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.mapbox.mapboxsdk.location - -import android.animation.ValueAnimator -import io.mockk.every -import io.mockk.mockk -import io.mockk.verify -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class MapboxAnimatorTest { - - @Test - fun fps_unlimited() { - val valueAnimator = mockk() - every { valueAnimator.animatedValue } answers { 5f } - val listener = mockk>() - every { listener.onNewAnimationValue(any()) } answers {} - val mapboxAnimator = MapboxFloatAnimator(0f, 10f, listener, Int.MAX_VALUE) - - for (i in 0 until 5) - mapboxAnimator.onAnimationUpdate(valueAnimator) - - verify(exactly = 5) { listener.onNewAnimationValue(5f) } - } - - @Test - fun fps_limited() { - val valueAnimator = mockk() - every { valueAnimator.animatedValue } answers { 5f } - val listener = mockk>() - every { listener.onNewAnimationValue(any()) } answers {} - val mapboxAnimator = MapboxFloatAnimator(0f, 10f, listener, 5) - - for (i in 0 until 5) { - mapboxAnimator.onAnimationUpdate(valueAnimator) - Thread.sleep(150) - } - - verify(exactly = 3) { listener.onNewAnimationValue(5f) } - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java deleted file mode 100644 index bf5ee40f4..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/location/UtilsTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.mapbox.mapboxsdk.location; - -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public final class UtilsTest { - - @Test - public void shortestRotation_doesReturnValueDistanceQuickestToZero() throws Exception { - float value = Utils.shortestRotation(0, 181); - assertEquals(360f, value); - value = Utils.shortestRotation(0, 179); - assertEquals(0f, value); - value = Utils.shortestRotation(0, 180); - assertEquals(0f, value); - } - - @Test - public void shortestRotation_doesReturnValueDistanceQuickestToFifty() throws Exception { - float value = Utils.shortestRotation(50, 231); - assertEquals(410f, value); - value = Utils.shortestRotation(50, 229); - assertEquals(50f, value); - value = Utils.shortestRotation(50, 180); - assertEquals(50f, value); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/log/LoggerTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/log/LoggerTest.kt deleted file mode 100644 index 82e1c67f6..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/log/LoggerTest.kt +++ /dev/null @@ -1,93 +0,0 @@ -package com.mapbox.mapboxsdk.log - -import io.mockk.mockk -import io.mockk.verify -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class LoggerTest { - - private val logger: LoggerDefinition = mockk(relaxed = true) - - @Before - fun setUp() { - Logger.setLoggerDefinition(logger) - } - - @Test - fun verbosityLogLevel() { - Logger.setVerbosity(Logger.VERBOSE) - Logger.v(TAG, MESSAGE) - verify { logger.v(TAG, MESSAGE) } - } - - @Test - fun verbosityLogLevelIgnore() { - Logger.setVerbosity(Logger.DEBUG) - Logger.v(TAG, MESSAGE) - verify(exactly = 0) { logger.v(TAG, MESSAGE) } - } - - @Test - fun debugLogLevel() { - Logger.setVerbosity(Logger.VERBOSE) - Logger.d(TAG, MESSAGE) - verify { logger.d(TAG, MESSAGE) } - } - - @Test - fun debugLogLevelIgnore() { - Logger.setVerbosity(Logger.WARN) - Logger.d(TAG, MESSAGE) - verify(exactly = 0) { logger.d(TAG, MESSAGE) } - } - - @Test - fun warnLogLevel() { - Logger.setVerbosity(Logger.WARN) - Logger.w(TAG, MESSAGE) - verify { logger.w(TAG, MESSAGE) } - } - - @Test - fun warnLogLevelIgnore() { - Logger.setVerbosity(Logger.ERROR) - Logger.w(TAG, MESSAGE) - verify(exactly = 0) { logger.w(TAG, MESSAGE) } - } - - @Test - fun errorLogLevel() { - Logger.setVerbosity(Logger.ERROR) - Logger.e(TAG, MESSAGE) - verify { logger.e(TAG, MESSAGE) } - } - - @Test - fun errorLogLevelIgnore() { - Logger.setVerbosity(Logger.NONE) - Logger.e(TAG, MESSAGE) - verify(exactly = 0) { logger.e(TAG, MESSAGE) } - } - - @Test - fun noneLogLevelIgnore() { - Logger.setVerbosity(Logger.NONE) - Logger.v(TAG, MESSAGE) - Logger.d(TAG, MESSAGE) - Logger.w(TAG, MESSAGE) - Logger.e(TAG, MESSAGE) - verify(exactly = 0) { logger.v(TAG, MESSAGE) } - verify(exactly = 0) { logger.d(TAG, MESSAGE) } - verify(exactly = 0) { logger.w(TAG, MESSAGE) } - verify(exactly = 0) { logger.e(TAG, MESSAGE) } - } - - companion object { - const val TAG: String = "TAG" - const val MESSAGE: String = "message" - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java deleted file mode 100644 index fd59f52a5..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AnnotationManagerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.support.v4.util.LongSparseArray; - -import com.mapbox.mapboxsdk.annotations.Annotation; -import com.mapbox.mapboxsdk.annotations.BaseMarkerOptions; -import com.mapbox.mapboxsdk.annotations.Marker; -import com.mapbox.mapboxsdk.annotations.MarkerOptions; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.mockito.ArgumentMatchers; - -import java.util.ArrayList; -import java.util.List; - -import static junit.framework.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class AnnotationManagerTest { - - @Test - public void checksAddAMarker() throws Exception { - NativeMap aNativeMapView = mock(NativeMapView.class); - MapView aMapView = mock(MapView.class); - LongSparseArray annotationsArray = new LongSparseArray<>(); - IconManager aIconManager = mock(IconManager.class); - Annotations annotations = new AnnotationContainer(aNativeMapView, annotationsArray); - Markers markers = new MarkerContainer(aNativeMapView, annotationsArray, aIconManager); - Polygons polygons = new PolygonContainer(aNativeMapView, annotationsArray); - Polylines polylines = new PolylineContainer(aNativeMapView, annotationsArray); - ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(aNativeMapView, annotationsArray); - AnnotationManager annotationManager = new AnnotationManager(aMapView, annotationsArray, - aIconManager, annotations, markers, polygons, polylines, shapeAnnotations); - Marker aMarker = mock(Marker.class); - long aId = 5L; - when(aNativeMapView.addMarker(aMarker)).thenReturn(aId); - BaseMarkerOptions aMarkerOptions = mock(BaseMarkerOptions.class); - MapboxMap aMapboxMap = mock(MapboxMap.class); - when(aMarkerOptions.getMarker()).thenReturn(aMarker); - - annotationManager.addMarker(aMarkerOptions, aMapboxMap); - - assertEquals(aMarker, annotationManager.getAnnotations().get(0)); - assertEquals(aMarker, annotationManager.getAnnotation(aId)); - } - - @Test - public void checksAddMarkers() throws Exception { - NativeMapView aNativeMapView = mock(NativeMapView.class); - MapView aMapView = mock(MapView.class); - LongSparseArray annotationsArray = new LongSparseArray<>(); - IconManager aIconManager = mock(IconManager.class); - Annotations annotations = new AnnotationContainer(aNativeMapView, annotationsArray); - Markers markers = new MarkerContainer(aNativeMapView, annotationsArray, aIconManager); - Polygons polygons = new PolygonContainer(aNativeMapView, annotationsArray); - Polylines polylines = new PolylineContainer(aNativeMapView, annotationsArray); - ShapeAnnotations shapeAnnotations = new ShapeAnnotationContainer(aNativeMapView, annotationsArray); - AnnotationManager annotationManager = new AnnotationManager(aMapView, annotationsArray, - aIconManager, annotations, markers, polygons, polylines, shapeAnnotations); - - long firstId = 1L; - long secondId = 2L; - List markerList = new ArrayList<>(); - MarkerOptions firstMarkerOption = new MarkerOptions().position(new LatLng()).title("first"); - MarkerOptions secondMarkerOption = new MarkerOptions().position(new LatLng()).title("second"); - - markerList.add(firstMarkerOption); - markerList.add(secondMarkerOption); - MapboxMap aMapboxMap = mock(MapboxMap.class); - when(aNativeMapView.addMarker(any(Marker.class))).thenReturn(firstId, secondId); - - when(aNativeMapView.addMarkers(ArgumentMatchers.anyList())) - .thenReturn(new long[] {firstId, secondId}); - - annotationManager.addMarkers(markerList, aMapboxMap); - - assertEquals(2, annotationManager.getAnnotations().size()); - assertEquals("first", ((Marker) annotationManager.getAnnotations().get(0)).getTitle()); - assertEquals("second", ((Marker) annotationManager.getAnnotations().get(1)).getTitle()); - assertEquals("first", ((Marker) annotationManager.getAnnotation(firstId)).getTitle()); - assertEquals("second", ((Marker) annotationManager.getAnnotation(secondId)).getTitle()); - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java deleted file mode 100644 index 9b4eeb27a..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/AttributionDialogManagerTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.content.Context; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.robolectric.RobolectricTestRunner; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@RunWith(RobolectricTestRunner.class) -public class AttributionDialogManagerTest { - @InjectMocks - Context context = mock(Context.class); - - @InjectMocks - MapboxMap mapboxMap = mock(MapboxMap.class); - - @InjectMocks - Style style = mock(Style.class); - - private AttributionDialogManager attributionDialogManager; - private CameraPosition cameraPosition; - - private static final String ASSERT_MAPBOX_TOKEN = "TestAccessToken"; - - private static final String ASSERT_MAPBOX_STYLE_URI = "mapbox://styles/mapbox/streets-v11"; - private static final String ASSERT_MAPBOX_LOCAL_STYLE_URI = "asset://style.json"; - - private static final String ASSERT_MAPBOX_PACKAGE_NAME = "com.mapbox.attributionmanagertest"; - - private static final String ASSERT_MAPBOX_FEEDBACK_FINAL_URL = - "https://apps.mapbox.com/feedback?referrer=com.mapbox.attributionmanagertest&" - + "access_token=TestAccessToken&owner=mapbox&id=streets-v11" - + "#/22.200001/11.100000/12.000000/24.000000/5"; - private static final String ASSERT_MAPBOX_FEEDHACK_FINAL_URL_LOCAL_STYLE = - "https://apps.mapbox.com/feedback?referrer=com.mapbox.attributionmanagertest&" - + "access_token=TestAccessToken#/22.200001/11.100000/12.000000/24.000000/5"; - private static final String ASSERT_MAPBOX_FEEDBACL_FINAL_URL_NULL_CAMERA_POSITION = - "https://apps.mapbox.com/feedback?referrer=com.mapbox.attributionmanagertest&access_token=TestAccessToken"; - - @Before - public void beforeTest() { - attributionDialogManager = new AttributionDialogManager(context, mapboxMap); - cameraPosition = new CameraPosition.Builder(CameraPosition.DEFAULT) - .tilt(5.0f).zoom(12).bearing(24.0f).target(new LatLng(11.1f, 22.2f)).build(); - } - - @Test - public void testSanity() { - assertNotNull("AttributionDialogManager should not be null", attributionDialogManager); - } - - @Test - public void testBuildMapFeedbackMapUrl() { - when(context.getApplicationContext()).thenReturn(context); - when(context.getPackageName()).thenReturn(ASSERT_MAPBOX_PACKAGE_NAME); - when(style.getUri()).thenReturn(ASSERT_MAPBOX_STYLE_URI); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - when(mapboxMap.getStyle()).thenReturn(style); - - Assert.assertEquals(ASSERT_MAPBOX_FEEDBACK_FINAL_URL, - attributionDialogManager.buildMapFeedbackMapUrl(ASSERT_MAPBOX_TOKEN)); - } - - @Test - public void testBuildMapFeedbackMapUrlWithLocalStyleJson() { - when(context.getApplicationContext()).thenReturn(context); - when(context.getPackageName()).thenReturn(ASSERT_MAPBOX_PACKAGE_NAME); - when(style.getUri()).thenReturn(ASSERT_MAPBOX_LOCAL_STYLE_URI); - when(mapboxMap.getCameraPosition()).thenReturn(cameraPosition); - when(mapboxMap.getStyle()).thenReturn(style); - - Assert.assertEquals(ASSERT_MAPBOX_FEEDHACK_FINAL_URL_LOCAL_STYLE, - attributionDialogManager.buildMapFeedbackMapUrl(ASSERT_MAPBOX_TOKEN)); - } - - @Test - public void testBuildMapFeedbackMapUrlWithNullCameraPosition() { - when(context.getApplicationContext()).thenReturn(context); - when(context.getPackageName()).thenReturn(ASSERT_MAPBOX_PACKAGE_NAME); - when(style.getUri()).thenReturn(ASSERT_MAPBOX_LOCAL_STYLE_URI); - when(mapboxMap.getCameraPosition()).thenReturn(null); - when(mapboxMap.getStyle()).thenReturn(style); - - Assert.assertEquals(ASSERT_MAPBOX_FEEDBACL_FINAL_URL_NULL_CAMERA_POSITION, - attributionDialogManager.buildMapFeedbackMapUrl(ASSERT_MAPBOX_TOKEN)); - } - - -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java deleted file mode 100644 index 025f06752..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapChangeReceiverTest.java +++ /dev/null @@ -1,586 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import com.google.common.util.concurrent.ExecutionError; -import com.mapbox.mapboxsdk.log.Logger; -import com.mapbox.mapboxsdk.log.LoggerDefinition; - -import junit.framework.Assert; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; - -/** - * Tests integration of MapChangeDispatcher and see if events are correctly forwarded. - */ -public class MapChangeReceiverTest { - - private static final String TEST_STRING = "mapChangeRandom"; - - private MapChangeReceiver mapChangeEventManager; - - @Mock - private MapView.OnCameraWillChangeListener onCameraWillChangeListener; - - @Mock - private MapView.OnCameraDidChangeListener onCameraDidChangeListener; - - @Mock - private MapView.OnCameraIsChangingListener onCameraIsChangingListener; - - @Mock - private MapView.OnWillStartLoadingMapListener onWillStartLoadingMapListener; - - @Mock - private MapView.OnDidFinishLoadingMapListener onDidFinishLoadingMapListener; - - @Mock - private MapView.OnDidFailLoadingMapListener onDidFailLoadingMapListener; - - @Mock - private MapView.OnWillStartRenderingFrameListener onWillStartRenderingFrameListener; - - @Mock - private MapView.OnDidFinishRenderingFrameListener onDidFinishRenderingFrameListener; - - @Mock - private MapView.OnWillStartRenderingMapListener onWillStartRenderingMapListener; - - @Mock - private MapView.OnDidFinishRenderingMapListener onDidFinishRenderingMapListener; - - @Mock - private MapView.OnDidBecomeIdleListener onDidBecomeIdleListener; - - @Mock - private MapView.OnDidFinishLoadingStyleListener onDidFinishLoadingStyleListener; - - @Mock - private MapView.OnSourceChangedListener onSourceChangedListener; - - @Mock - private LoggerDefinition loggerDefinition; - - @Before - public void beforeTest() { - MockitoAnnotations.initMocks(this); - mapChangeEventManager = new MapChangeReceiver(); - } - - @Test - public void testOnCameraRegionWillChangeListener() { - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(false); - verify(onCameraWillChangeListener).onCameraWillChange(false); - - mapChangeEventManager.removeOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(false); - verify(onCameraWillChangeListener).onCameraWillChange(false); - - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraWillChangeListener).onCameraWillChange(false); - try { - mapChangeEventManager.onCameraWillChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraWillChangeListener).onCameraWillChange(false); - try { - mapChangeEventManager.onCameraWillChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionWillChangeAnimatedListener() { - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(true); - verify(onCameraWillChangeListener).onCameraWillChange(true); - mapChangeEventManager.removeOnCameraWillChangeListener(onCameraWillChangeListener); - mapChangeEventManager.onCameraWillChange(true); - verify(onCameraWillChangeListener).onCameraWillChange(true); - - mapChangeEventManager.addOnCameraWillChangeListener(onCameraWillChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraWillChangeListener).onCameraWillChange(true); - try { - mapChangeEventManager.onCameraWillChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraWillChangeListener).onCameraWillChange(true); - try { - mapChangeEventManager.onCameraWillChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraIsChangingListener() { - mapChangeEventManager.addOnCameraIsChangingListener(onCameraIsChangingListener); - mapChangeEventManager.onCameraIsChanging(); - verify(onCameraIsChangingListener).onCameraIsChanging(); - mapChangeEventManager.removeOnCameraIsChangingListener(onCameraIsChangingListener); - mapChangeEventManager.onCameraIsChanging(); - verify(onCameraIsChangingListener).onCameraIsChanging(); - - mapChangeEventManager.addOnCameraIsChangingListener(onCameraIsChangingListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraIsChangingListener).onCameraIsChanging(); - try { - mapChangeEventManager.onCameraIsChanging(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraIsChangingListener).onCameraIsChanging(); - try { - mapChangeEventManager.onCameraIsChanging(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionDidChangeListener() { - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(false); - verify(onCameraDidChangeListener).onCameraDidChange(false); - mapChangeEventManager.removeOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(false); - verify(onCameraDidChangeListener).onCameraDidChange(false); - - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraDidChangeListener).onCameraDidChange(false); - try { - mapChangeEventManager.onCameraDidChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraDidChangeListener).onCameraDidChange(false); - try { - mapChangeEventManager.onCameraDidChange(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnCameraRegionDidChangeAnimatedListener() { - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(true); - verify(onCameraDidChangeListener).onCameraDidChange(true); - mapChangeEventManager.removeOnCameraDidChangeListener(onCameraDidChangeListener); - mapChangeEventManager.onCameraDidChange(true); - verify(onCameraDidChangeListener).onCameraDidChange(true); - - mapChangeEventManager.addOnCameraDidChangeListener(onCameraDidChangeListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onCameraDidChangeListener).onCameraDidChange(true); - try { - mapChangeEventManager.onCameraDidChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onCameraDidChangeListener).onCameraDidChange(true); - try { - mapChangeEventManager.onCameraDidChange(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartLoadingMapListener() { - mapChangeEventManager.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - mapChangeEventManager.onWillStartLoadingMap(); - verify(onWillStartLoadingMapListener).onWillStartLoadingMap(); - mapChangeEventManager.removeOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - mapChangeEventManager.onWillStartLoadingMap(); - verify(onWillStartLoadingMapListener).onWillStartLoadingMap(); - - mapChangeEventManager.addOnWillStartLoadingMapListener(onWillStartLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartLoadingMapListener).onWillStartLoadingMap(); - try { - mapChangeEventManager.onWillStartLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartLoadingMapListener).onWillStartLoadingMap(); - try { - mapChangeEventManager.onWillStartLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishLoadingMapListener() { - mapChangeEventManager.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - mapChangeEventManager.onDidFinishLoadingMap(); - verify(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - mapChangeEventManager.removeOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - mapChangeEventManager.onDidFinishLoadingMap(); - verify(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - - mapChangeEventManager.addOnDidFinishLoadingMapListener(onDidFinishLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - try { - mapChangeEventManager.onDidFinishLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishLoadingMapListener).onDidFinishLoadingMap(); - try { - mapChangeEventManager.onDidFinishLoadingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFailLoadingMapListener() { - mapChangeEventManager.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - verify(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - mapChangeEventManager.removeOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - verify(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - - mapChangeEventManager.addOnDidFailLoadingMapListener(onDidFailLoadingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - try { - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFailLoadingMapListener).onDidFailLoadingMap(TEST_STRING); - try { - mapChangeEventManager.onDidFailLoadingMap(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartRenderingFrameListener() { - mapChangeEventManager.addOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - mapChangeEventManager.onWillStartRenderingFrame(); - verify(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - mapChangeEventManager.removeOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - mapChangeEventManager.onWillStartRenderingFrame(); - verify(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - - mapChangeEventManager.addOnWillStartRenderingFrameListener(onWillStartRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - try { - mapChangeEventManager.onWillStartRenderingFrame(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartRenderingFrameListener).onWillStartRenderingFrame(); - try { - mapChangeEventManager.onWillStartRenderingFrame(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingFrameListener() { - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(true); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - mapChangeEventManager.removeOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(true); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - try { - mapChangeEventManager.onDidFinishRenderingFrame(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(true); - try { - mapChangeEventManager.onDidFinishRenderingFrame(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingFrameFullyRenderedListener() { - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(false); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - mapChangeEventManager.removeOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - mapChangeEventManager.onDidFinishRenderingFrame(false); - verify(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - - mapChangeEventManager.addOnDidFinishRenderingFrameListener(onDidFinishRenderingFrameListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - try { - mapChangeEventManager.onDidFinishRenderingFrame(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingFrameListener).onDidFinishRenderingFrame(false); - try { - mapChangeEventManager.onDidFinishRenderingFrame(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnWillStartRenderingMapListener() { - mapChangeEventManager.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - mapChangeEventManager.onWillStartRenderingMap(); - verify(onWillStartRenderingMapListener).onWillStartRenderingMap(); - mapChangeEventManager.removeOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - mapChangeEventManager.onWillStartRenderingMap(); - verify(onWillStartRenderingMapListener).onWillStartRenderingMap(); - - mapChangeEventManager.addOnWillStartRenderingMapListener(onWillStartRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onWillStartRenderingMapListener).onWillStartRenderingMap(); - try { - mapChangeEventManager.onWillStartRenderingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onWillStartRenderingMapListener).onWillStartRenderingMap(); - try { - mapChangeEventManager.onWillStartRenderingMap(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingMapListener() { - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(true); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - mapChangeEventManager.removeOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(true); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - try { - mapChangeEventManager.onDidFinishRenderingMap(true); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(true); - try { - mapChangeEventManager.onDidFinishRenderingMap(true); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishRenderingMapFullyRenderedListener() { - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(false); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - mapChangeEventManager.removeOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - mapChangeEventManager.onDidFinishRenderingMap(false); - verify(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - - mapChangeEventManager.addOnDidFinishRenderingMapListener(onDidFinishRenderingMapListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - try { - mapChangeEventManager.onDidFinishRenderingMap(false); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishRenderingMapListener).onDidFinishRenderingMap(false); - try { - mapChangeEventManager.onDidFinishRenderingMap(false); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidBecomeIdleListener() { - mapChangeEventManager.addOnDidBecomeIdleListener(onDidBecomeIdleListener); - mapChangeEventManager.onDidBecomeIdle(); - verify(onDidBecomeIdleListener).onDidBecomeIdle(); - mapChangeEventManager.removeOnDidBecomeIdleListener(onDidBecomeIdleListener); - mapChangeEventManager.onDidBecomeIdle(); - verify(onDidBecomeIdleListener).onDidBecomeIdle(); - - mapChangeEventManager.addOnDidBecomeIdleListener(onDidBecomeIdleListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidBecomeIdleListener).onDidBecomeIdle(); - try { - mapChangeEventManager.onDidBecomeIdle(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidBecomeIdleListener).onDidBecomeIdle(); - try { - mapChangeEventManager.onDidBecomeIdle(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnDidFinishLoadingStyleListener() { - mapChangeEventManager.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - mapChangeEventManager.onDidFinishLoadingStyle(); - verify(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - mapChangeEventManager.removeOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - mapChangeEventManager.onDidFinishLoadingStyle(); - verify(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - - mapChangeEventManager.addOnDidFinishLoadingStyleListener(onDidFinishLoadingStyleListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - try { - mapChangeEventManager.onDidFinishLoadingStyle(); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onDidFinishLoadingStyleListener).onDidFinishLoadingStyle(); - try { - mapChangeEventManager.onDidFinishLoadingStyle(); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } - - @Test - public void testOnSourceChangedListener() { - mapChangeEventManager.addOnSourceChangedListener(onSourceChangedListener); - mapChangeEventManager.onSourceChanged(TEST_STRING); - verify(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - mapChangeEventManager.removeOnSourceChangedListener(onSourceChangedListener); - mapChangeEventManager.onSourceChanged(TEST_STRING); - verify(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - - mapChangeEventManager.addOnSourceChangedListener(onSourceChangedListener); - Logger.setLoggerDefinition(loggerDefinition); - Exception exc = new RuntimeException(); - doThrow(exc).when(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - try { - mapChangeEventManager.onSourceChanged(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (RuntimeException throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(exc)); - } - - Error err = new ExecutionError("", new Error()); - doThrow(err).when(onSourceChangedListener).onSourceChangedListener(TEST_STRING); - try { - mapChangeEventManager.onSourceChanged(TEST_STRING); - Assert.fail("The exception should've been re-thrown."); - } catch (ExecutionError throwable) { - verify(loggerDefinition).e(anyString(), anyString(), eq(err)); - } - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java deleted file mode 100644 index cb097c283..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapTouchListenersTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.PointF; - -import android.support.annotation.Nullable; -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.mapboxsdk.geometry.LatLng; - -import org.junit.Before; -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class MapTouchListenersTest { - - @Nullable - private MapGestureDetector mapGestureDetector; - private LatLng latLng; - private PointF pointF; - - @Before - public void setUp() throws Exception { - latLng = new LatLng(); - pointF = new PointF(); - - Projection projection = mock(Projection.class); - when(projection.fromScreenLocation(pointF)).thenReturn(latLng); - mapGestureDetector = new MapGestureDetector(null, - null, projection, null, null, null); - } - - @Test - public void onMapClickListenerTest() throws Exception { - MapboxMap.OnMapClickListener listener = mock(MapboxMap.OnMapClickListener.class); - mapGestureDetector.addOnMapClickListener(listener); - mapGestureDetector.notifyOnMapClickListeners(pointF); - verify(listener, times(1)).onMapClick(latLng); - - mapGestureDetector.removeOnMapClickListener(listener); - mapGestureDetector.notifyOnMapClickListeners(pointF); - verify(listener, times(1)).onMapClick(latLng); - } - - @Test - public void onMapLongClickListenerTest() throws Exception { - MapboxMap.OnMapLongClickListener listener = mock(MapboxMap.OnMapLongClickListener.class); - mapGestureDetector.addOnMapLongClickListener(listener); - mapGestureDetector.notifyOnMapLongClickListeners(pointF); - verify(listener, times(1)).onMapLongClick(latLng); - - mapGestureDetector.removeOnMapLongClickListener(listener); - mapGestureDetector.notifyOnMapLongClickListeners(pointF); - verify(listener, times(1)).onMapLongClick(latLng); - } - - @Test - public void onFlingListenerTest() throws Exception { - MapboxMap.OnFlingListener listener = mock(MapboxMap.OnFlingListener.class); - mapGestureDetector.addOnFlingListener(listener); - mapGestureDetector.notifyOnFlingListeners(); - verify(listener, times(1)).onFling(); - - mapGestureDetector.removeOnFlingListener(listener); - mapGestureDetector.notifyOnFlingListeners(); - verify(listener, times(1)).onFling(); - } - - @Test - public void onMoveListenerTest() throws Exception { - MapboxMap.OnMoveListener listener = mock(MapboxMap.OnMoveListener.class); - MoveGestureDetector detector = mock(MoveGestureDetector.class); - mapGestureDetector.addOnMoveListener(listener); - mapGestureDetector.notifyOnMoveBeginListeners(detector); - mapGestureDetector.notifyOnMoveListeners(detector); - mapGestureDetector.notifyOnMoveEndListeners(detector); - verify(listener, times(1)).onMoveBegin(detector); - verify(listener, times(1)).onMove(detector); - verify(listener, times(1)).onMoveEnd(detector); - - mapGestureDetector.removeOnMoveListener(listener); - mapGestureDetector.notifyOnMoveBeginListeners(detector); - mapGestureDetector.notifyOnMoveListeners(detector); - mapGestureDetector.notifyOnMoveEndListeners(detector); - verify(listener, times(1)).onMoveBegin(detector); - verify(listener, times(1)).onMove(detector); - verify(listener, times(1)).onMoveEnd(detector); - } - - @Test - public void onRotateListenerTest() throws Exception { - MapboxMap.OnRotateListener listener = mock(MapboxMap.OnRotateListener.class); - RotateGestureDetector detector = mock(RotateGestureDetector.class); - mapGestureDetector.addOnRotateListener(listener); - mapGestureDetector.notifyOnRotateBeginListeners(detector); - mapGestureDetector.notifyOnRotateListeners(detector); - mapGestureDetector.notifyOnRotateEndListeners(detector); - verify(listener, times(1)).onRotateBegin(detector); - verify(listener, times(1)).onRotate(detector); - verify(listener, times(1)).onRotateEnd(detector); - - mapGestureDetector.removeOnRotateListener(listener); - mapGestureDetector.notifyOnRotateBeginListeners(detector); - mapGestureDetector.notifyOnRotateListeners(detector); - mapGestureDetector.notifyOnRotateEndListeners(detector); - verify(listener, times(1)).onRotateBegin(detector); - verify(listener, times(1)).onRotate(detector); - verify(listener, times(1)).onRotateEnd(detector); - } - - @Test - public void onScaleListenerTest() throws Exception { - MapboxMap.OnScaleListener listener = mock(MapboxMap.OnScaleListener.class); - StandardScaleGestureDetector detector = mock(StandardScaleGestureDetector.class); - mapGestureDetector.addOnScaleListener(listener); - mapGestureDetector.notifyOnScaleBeginListeners(detector); - mapGestureDetector.notifyOnScaleListeners(detector); - mapGestureDetector.notifyOnScaleEndListeners(detector); - verify(listener, times(1)).onScaleBegin(detector); - verify(listener, times(1)).onScale(detector); - verify(listener, times(1)).onScaleEnd(detector); - - mapGestureDetector.removeOnScaleListener(listener); - mapGestureDetector.notifyOnScaleBeginListeners(detector); - mapGestureDetector.notifyOnScaleListeners(detector); - mapGestureDetector.notifyOnScaleEndListeners(detector); - verify(listener, times(1)).onScaleBegin(detector); - verify(listener, times(1)).onScale(detector); - verify(listener, times(1)).onScaleEnd(detector); - } - - @Test - public void onShoveListenerTest() throws Exception { - MapboxMap.OnShoveListener listener = mock(MapboxMap.OnShoveListener.class); - ShoveGestureDetector detector = mock(ShoveGestureDetector.class); - mapGestureDetector.addShoveListener(listener); - mapGestureDetector.notifyOnShoveBeginListeners(detector); - mapGestureDetector.notifyOnShoveListeners(detector); - mapGestureDetector.notifyOnShoveEndListeners(detector); - verify(listener, times(1)).onShoveBegin(detector); - verify(listener, times(1)).onShove(detector); - verify(listener, times(1)).onShoveEnd(detector); - - mapGestureDetector.removeShoveListener(listener); - mapGestureDetector.notifyOnShoveBeginListeners(detector); - mapGestureDetector.notifyOnShoveListeners(detector); - mapGestureDetector.notifyOnShoveEndListeners(detector); - verify(listener, times(1)).onShoveBegin(detector); - verify(listener, times(1)).onShove(detector); - verify(listener, times(1)).onShoveEnd(detector); - } -} diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsAttrsTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsAttrsTest.kt deleted file mode 100644 index ee8024257..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsAttrsTest.kt +++ /dev/null @@ -1,101 +0,0 @@ -package com.mapbox.mapboxsdk.maps - -import android.content.Context -import android.content.res.Resources -import android.content.res.TypedArray -import com.mapbox.mapboxsdk.R -import io.mockk.MockKAnnotations -import io.mockk.every -import io.mockk.impl.annotations.RelaxedMockK -import io.mockk.verify -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class MapboxMapOptionsAttrsTest { - - @RelaxedMockK - private lateinit var options: MapboxMapOptions - - @RelaxedMockK - private lateinit var typedArray: TypedArray - - @RelaxedMockK - private lateinit var context: Context - - @RelaxedMockK - private lateinit var resources: Resources - - @Before - fun setUp() { - MockKAnnotations.init(this) - every { - context.resources - }.returns(resources) - } - - @Test - fun enabledLocalIdeographFontFamily() { - mockEnableLocalIdeograph(enabled = true) - - val options = MapboxMapOptions.createFromAttributes(options, context, typedArray) - - verify(exactly = 1) { - options.localIdeographFontFamily(any()) - } - } - - @Test - fun localIdeographFontFamily() { - mockEnableLocalIdeograph(enabled = true) - - val font = "foo" - mockLocalIdeographString(font) - - val options = MapboxMapOptions.createFromAttributes(options, context, typedArray) - - verify(exactly = 1) { - options.localIdeographFontFamily(font) - } - } - - @Test - fun localIdeographFontFamilies() { - mockEnableLocalIdeograph(enabled = true) - - val fonts = arrayOf("foo", "bar") - mockLocalIdeographStringArray(fonts) - - val options = MapboxMapOptions.createFromAttributes(options, context, typedArray) - - verify(exactly = 1) { - options.localIdeographFontFamily(*fonts) - } - } - - private fun mockEnableLocalIdeograph(enabled: Boolean) { - every { - typedArray.getBoolean(R.styleable.mapbox_MapView_mapbox_localIdeographEnabled, true) - }.returns(enabled) - } - - private fun mockLocalIdeographString(font: String) { - every { - typedArray.getString(R.styleable.mapbox_MapView_mapbox_localIdeographFontFamily) - }.returns(font) - } - - private fun mockLocalIdeographStringArray(fonts: Array) { - val resId = 9000 - - every { - typedArray.getResourceId(R.styleable.mapbox_MapView_mapbox_localIdeographFontFamilies, 0) - }.returns(resId) - - every { - resources.getStringArray(resId) - }.returns(fonts) - } -} \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java deleted file mode 100644 index c46e6e319..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapOptionsTest.java +++ /dev/null @@ -1,196 +0,0 @@ -package com.mapbox.mapboxsdk.maps; - -import android.graphics.Color; -import android.view.Gravity; - -import com.mapbox.mapboxsdk.camera.CameraPosition; -import com.mapbox.mapboxsdk.constants.MapboxConstants; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; - -import java.util.Arrays; - -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertNull; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -@RunWith(RobolectricTestRunner.class) -public class MapboxMapOptionsTest { - - private static final double DELTA = 1e-15; - - @Test - public void testSanity() { - assertNotNull("should not be null", new MapboxMapOptions()); - } - - @Test - public void testDebugEnabled() { - assertFalse(new MapboxMapOptions().getDebugActive()); - assertTrue(new MapboxMapOptions().debugActive(true).getDebugActive()); - assertFalse(new MapboxMapOptions().debugActive(false).getDebugActive()); - } - - @Test - public void testCompassEnabled() { - assertTrue(new MapboxMapOptions().compassEnabled(true).getCompassEnabled()); - assertFalse(new MapboxMapOptions().compassEnabled(false).getCompassEnabled()); - } - - @Test - public void testCompassGravity() { - assertEquals(Gravity.TOP | Gravity.END, new MapboxMapOptions().getCompassGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().compassGravity(Gravity.BOTTOM).getCompassGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().compassGravity(Gravity.BOTTOM).getCompassGravity()); - } - - @Test - public void testCompassMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().compassMargins( - new int[] {0, 1, 2, 3}).getCompassMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().compassMargins( - new int[] {0, 0, 0, 0}).getCompassMargins())); - } - - @Test - public void testLogoEnabled() { - assertTrue(new MapboxMapOptions().logoEnabled(true).getLogoEnabled()); - assertFalse(new MapboxMapOptions().logoEnabled(false).getLogoEnabled()); - } - - @Test - public void testLogoGravity() { - assertEquals(Gravity.BOTTOM | Gravity.START, new MapboxMapOptions().getLogoGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().logoGravity(Gravity.BOTTOM).getLogoGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().logoGravity(Gravity.BOTTOM).getLogoGravity()); - } - - @Test - public void testLogoMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().logoMargins( - new int[] {0, 1, 2, 3}).getLogoMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().logoMargins( - new int[] {0, 0, 0, 0}).getLogoMargins())); - } - - @Test - public void testAttributionTintColor() { - assertEquals(-1, new MapboxMapOptions().getAttributionTintColor()); - assertEquals(Color.RED, new MapboxMapOptions().attributionTintColor(Color.RED).getAttributionTintColor()); - } - - @Test - public void testAttributionEnabled() { - assertTrue(new MapboxMapOptions().attributionEnabled(true).getAttributionEnabled()); - assertFalse(new MapboxMapOptions().attributionEnabled(false).getAttributionEnabled()); - } - - @Test - public void testAttributionGravity() { - assertEquals(Gravity.BOTTOM | Gravity.START, new MapboxMapOptions().getAttributionGravity()); - assertEquals(Gravity.BOTTOM, new MapboxMapOptions().attributionGravity(Gravity.BOTTOM).getAttributionGravity()); - assertNotEquals(Gravity.START, new MapboxMapOptions().attributionGravity(Gravity.BOTTOM).getAttributionGravity()); - } - - @Test - public void testAttributionMargins() { - assertTrue(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().attributionMargins( - new int[] {0, 1, 2, 3}).getAttributionMargins())); - assertFalse(Arrays.equals(new int[] {0, 1, 2, 3}, new MapboxMapOptions().attributionMargins( - new int[] {0, 0, 0, 0}).getAttributionMargins())); - } - - @Test - public void testMinZoom() { - assertEquals(MapboxConstants.MINIMUM_ZOOM, new MapboxMapOptions().getMinZoomPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().minZoomPreference(5.0f).getMinZoomPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().minZoomPreference(5.0f).getMinZoomPreference(), DELTA); - } - - @Test - public void testMaxZoom() { - assertEquals(MapboxConstants.MAXIMUM_ZOOM, new MapboxMapOptions().getMaxZoomPreference(), DELTA); - assertEquals(5.0f, new MapboxMapOptions().maxZoomPreference(5.0f).getMaxZoomPreference(), DELTA); - assertNotEquals(2.0f, new MapboxMapOptions().maxZoomPreference(5.0f).getMaxZoomPreference(), DELTA); - } - - @Test - public void testTiltGesturesEnabled() { - assertTrue(new MapboxMapOptions().getTiltGesturesEnabled()); - assertTrue(new MapboxMapOptions().tiltGesturesEnabled(true).getTiltGesturesEnabled()); - assertFalse(new MapboxMapOptions().tiltGesturesEnabled(false).getTiltGesturesEnabled()); - } - - @Test - public void testScrollGesturesEnabled() { - assertTrue(new MapboxMapOptions().getScrollGesturesEnabled()); - assertTrue(new MapboxMapOptions().scrollGesturesEnabled(true).getScrollGesturesEnabled()); - assertFalse(new MapboxMapOptions().scrollGesturesEnabled(false).getScrollGesturesEnabled()); - } - - @Test - public void testZoomGesturesEnabled() { - assertTrue(new MapboxMapOptions().getZoomGesturesEnabled()); - assertTrue(new MapboxMapOptions().zoomGesturesEnabled(true).getZoomGesturesEnabled()); - assertFalse(new MapboxMapOptions().zoomGesturesEnabled(false).getZoomGesturesEnabled()); - } - - @Test - public void testRotateGesturesEnabled() { - assertTrue(new MapboxMapOptions().getRotateGesturesEnabled()); - assertTrue(new MapboxMapOptions().rotateGesturesEnabled(true).getRotateGesturesEnabled()); - assertFalse(new MapboxMapOptions().rotateGesturesEnabled(false).getRotateGesturesEnabled()); - } - - @Test - public void testCamera() { - CameraPosition position = new CameraPosition.Builder().build(); - assertEquals(new CameraPosition.Builder(position).build(), new MapboxMapOptions().camera(position).getCamera()); - assertNotEquals(new CameraPosition.Builder().target(new LatLng(1, 1)), new MapboxMapOptions().camera(position)); - assertNull(new MapboxMapOptions().getCamera()); - } - - @Test - public void testPrefetchesTiles() { - // Default value - assertTrue(new MapboxMapOptions().getPrefetchesTiles()); - - // Check mutations - assertTrue(new MapboxMapOptions().setPrefetchesTiles(true).getPrefetchesTiles()); - assertFalse(new MapboxMapOptions().setPrefetchesTiles(false).getPrefetchesTiles()); - } - - @Test - public void testPrefetchZoomDelta() { - // Default value - assertEquals(4, new MapboxMapOptions().getPrefetchZoomDelta()); - - // Check mutations - assertEquals(5, new MapboxMapOptions().setPrefetchZoomDelta(5).getPrefetchZoomDelta()); - } - - - @Test - public void testCrossSourceCollisions() { - // Default value - assertTrue(new MapboxMapOptions().getCrossSourceCollisions()); - - // check mutations - assertTrue(new MapboxMapOptions().crossSourceCollisions(true).getCrossSourceCollisions()); - assertFalse(new MapboxMapOptions().crossSourceCollisions(false).getCrossSourceCollisions()); - } - - @Test - public void testLocalIdeographFontFamily_enabledByDefault() { - MapboxMapOptions options = MapboxMapOptions.createFromAttributes(RuntimeEnvironment.application, null); - assertEquals(MapboxConstants.DEFAULT_FONT, options.getLocalIdeographFontFamily()); - } -} - diff --git a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapTest.kt b/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapTest.kt deleted file mode 100644 index 6647fe559..000000000 --- a/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/maps/MapboxMapTest.kt +++ /dev/null @@ -1,214 +0,0 @@ -package com.mapbox.mapboxsdk.maps - -import com.mapbox.mapboxsdk.camera.CameraPosition -import com.mapbox.mapboxsdk.camera.CameraUpdateFactory -import com.mapbox.mapboxsdk.constants.MapboxConstants -import com.mapbox.mapboxsdk.geometry.LatLng -import com.mapbox.mapboxsdk.geometry.LatLngBounds -import com.mapbox.mapboxsdk.style.layers.TransitionOptions -import io.mockk.* -import junit.framework.Assert.assertEquals -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class MapboxMapTest { - - private lateinit var mapboxMap: MapboxMap - - private lateinit var nativeMapView: NativeMap - - private lateinit var transform: Transform - - private lateinit var cameraChangeDispatcher: CameraChangeDispatcher - - private lateinit var developerAnimationListener: MapboxMap.OnDeveloperAnimationListener - - @Before - fun setup() { - cameraChangeDispatcher = spyk() - developerAnimationListener = mockk(relaxed = true) - nativeMapView = mockk(relaxed = true) - transform = mockk(relaxed = true) - mapboxMap = MapboxMap(nativeMapView, transform, mockk(relaxed = true), null, null, cameraChangeDispatcher, listOf(developerAnimationListener)) - every { nativeMapView.isDestroyed } returns false - every { nativeMapView.nativePtr } returns 5 - mapboxMap.injectLocationComponent(spyk()) - mapboxMap.setStyle(Style.MAPBOX_STREETS) - mapboxMap.onFinishLoadingStyle() - } - - @Test - fun testTransitionOptions() { - val expected = TransitionOptions(100, 200) - mapboxMap.style?.transition = expected - verify { nativeMapView.transitionOptions = expected } - } - - @Test - fun testMoveCamera() { - val callback = mockk() - val target = LatLng(1.0, 2.0) - val expected = CameraPosition.Builder().target(target).build() - val update = CameraUpdateFactory.newCameraPosition(expected) - mapboxMap.moveCamera(update, callback) - verify { transform.moveCamera(mapboxMap, update, callback) } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testEaseCamera() { - val callback = mockk() - val target = LatLng(1.0, 2.0) - val expected = CameraPosition.Builder().target(target).build() - val update = CameraUpdateFactory.newCameraPosition(expected) - mapboxMap.easeCamera(update, callback) - verify { transform.easeCamera(mapboxMap, update, MapboxConstants.ANIMATION_DURATION, true, callback) } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testAnimateCamera() { - val callback = mockk() - val target = LatLng(1.0, 2.0) - val expected = CameraPosition.Builder().target(target).build() - val update = CameraUpdateFactory.newCameraPosition(expected) - mapboxMap.animateCamera(update, callback) - verify { transform.animateCamera(mapboxMap, update, MapboxConstants.ANIMATION_DURATION, callback) } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testScrollBy() { - mapboxMap.scrollBy(100f, 200f) - verify { nativeMapView.moveBy(100.0, 200.0, 0) } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testResetNorth() { - mapboxMap.resetNorth() - verify { transform.resetNorth() } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testFocalBearing() { - mapboxMap.setFocalBearing(35.0, 100f, 200f, 1000) - verify { transform.setBearing(35.0, 100f, 200f, 1000) } - verify { developerAnimationListener.onDeveloperAnimationStarted() } - } - - @Test - fun testMinZoom() { - mapboxMap.setMinZoomPreference(10.0) - verify { transform.minZoom = 10.0 } - } - - @Test - fun testMaxZoom() { - mapboxMap.setMaxZoomPreference(10.0) - verify { transform.maxZoom = 10.0 } - } - - @Test - fun testFpsListener() { - val fpsChangedListener = mockk() - mapboxMap.onFpsChangedListener = fpsChangedListener - assertEquals("Listener should match", fpsChangedListener, mapboxMap.onFpsChangedListener) - } - - @Test - fun testTilePrefetch() { - mapboxMap.prefetchesTiles = true - verify { nativeMapView.prefetchTiles = true } - } - - @Test - fun testGetPrefetchZoomDelta() { - every { nativeMapView.prefetchZoomDelta } answers { 3 } - assertEquals(3, mapboxMap.prefetchZoomDelta) - } - - @Test - fun testSetPrefetchZoomDelta() { - mapboxMap.prefetchZoomDelta = 2 - verify { nativeMapView.prefetchZoomDelta = 2 } - } - - @Test - fun testCameraForLatLngBounds() { - val bounds = LatLngBounds.Builder().include(LatLng()).include(LatLng(1.0, 1.0)).build() - mapboxMap.setLatLngBoundsForCameraTarget(bounds) - verify { nativeMapView.setLatLngBounds(bounds) } - } - - @Test(expected = IllegalArgumentException::class) - fun testAnimateCameraChecksDurationPositive() { - mapboxMap.animateCamera(CameraUpdateFactory.newLatLng(LatLng(30.0, 30.0)), 0, null) - } - - @Test(expected = IllegalArgumentException::class) - fun testEaseCameraChecksDurationPositive() { - mapboxMap.easeCamera(CameraUpdateFactory.newLatLng(LatLng(30.0, 30.0)), 0, null) - } - - @Test - fun testGetNativeMapPtr() { - assertEquals(5, mapboxMap.nativeMapPtr) - } - - @Test - fun testNativeMapIsNotCalledOnStateSave() { - clearMocks(nativeMapView) - mapboxMap.onSaveInstanceState(mockk(relaxed = true)) - verify { nativeMapView wasNot Called } - } - - @Test - fun testCameraChangeDispatcherCleared() { - mapboxMap.onDestroy() - verify { cameraChangeDispatcher.onDestroy() } - } - - @Test - fun testStyleClearedOnDestroy() { - val style = mockk - - - - - - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/actions.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/actions.xml deleted file mode 100644 index d36c741c5..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/actions.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - Concurrent Open InfoWindows - Deselect Markers On Tap - Reset - Toggle icon overlap - Filter layer - Change location - Accelerate/Decelerate interpolator - Bounce interpolator - Anticipate/Overshoot interpolator - PathInterpolator interpolator - Toggle Symbol Layer Visibility - Move - Ease - Animate - Open dialog - Download region - List regions - Remove polylines - Change visibility - Change alpha - Change points - Change color - Change holes - Change width - "Click the map to calculate the distance" - Move the map by x/y pixels - Open navigation drawer - Close navigation drawer - X: %1$d - Y: %1$d - Animate to new position - Chelsea - Stamford Bridge - Arsenal - Emirates Stadium - Zoom: %.2f - ViewCache size %d - Latitude - -180 - Longitude - Zoom - 18 - Bearing - 0 - Tilt - No Results - Change intensity - Change Anchor - Amount of markers - Update layer (invalidate) - Red - Green - Blue - Add an exponential zoom function - Add an interval zoom function - Add a categorical source function - Add an exponential source function - Add an identity source function - Add an interval source function - Add a composite, categorical function - Add a composite, exponential function - Add a composite, interval function - Bangalore - List all layers in the style - List all sources in the style - Color the water - Set background opacity - Set road symbol placement to Point - Set layer visibility to false - Add a parks layer - Add a dynamic GeoJSON source - Remove buildings layer - Add a terrain layer - Add a satellite layer - Change the water color on zoom - Custom tiles - Apply filtered fill - Apply filtered line - Apply numeric fill filter - Bring water to front - Toggle text size - Toggle text field contents - Toggle text font - Zoom in - Zoom out - Zoom by 2 - Zoom to point - Zoom to 4 - Restrict almost worldview - Restrict across IDL - Reset bounds - \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/arrays.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/arrays.xml deleted file mode 100644 index ad9f88a46..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/arrays.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - 10 - 100 - 500 - 1000 - 10000 - - - foo - monospace - bar - - \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/categories.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/categories.xml deleted file mode 100644 index 94c805f35..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/categories.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - category - _Basic - Annotation - Camera - Custom Layer - Fragment - Image Generator - Info Window - Map Layout - Offline - Styling - Features - Storage - Texture View - Location - _Integration - Telemetry - Turf - \ No newline at end of file diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/colors.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/colors.xml deleted file mode 100644 index 88524d44e..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/colors.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - #52A1D8 - #3887BE - #E55E5E - #F9F9F9 - #56B881 - - #D50000 - #2962FF - #1B5E20 - - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/descriptions.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/descriptions.xml deleted file mode 100644 index 7f018a43f..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/descriptions.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - Overlay a custom native layer on the map - Learn how to create a custom InfoWindow - CameraPosition capabilities - Showcase MapFragment - Showcase SupportMapFragment - Showcase using a Map Fragment with a fragment backstack - Activity with multiple maps on screen - Add marker to map on long press - Different types of zoom methods - Configure a max and min zoomlevel - Learn how to handle the InfoWindow - Add Markers In Bulk to a Map - Showcase the different animation types - Center the camera around a bounds - Update position and icon - Map Padding example - Debug Mode - Offline Map example - Download an offline region. - Update metadata example - Delete region example - Change resources cache path example - Animate the position change of a symbol layer - Add a polyline to a map - Add a polygon to a map - Scroll with pixels in x,y direction - Example to make a snapshot of the map - 2 maps in a view hierarchy - Learn how to create a dynamic custom InfoWindow - Use SupportMapFragments in a ViewPager - Adopt the map style on the fly - Show a gradient line layer from a geojson source - Use functions to change the map appearance - Manipulate symbols at runtime - Use a custom sprite in a Symbol Layer - Use GeoJson sources and dynamic layers to cluster information - Use realtime GeoJSON data streams to move a symbol on your map - Shows how to print a map - Query rendered feature properties on click - Count all rendered features in box - Count all rendered symbols in box - Highlight buildings in box - Query source for features - Shows a simple map - Logs map change events to Logcat - Changes visibility of map and view parent - Change Symbol icon when zoom levels changes - Use a local file as the style - Display a map inside a dialog fragment - Show bus stops and route in Singapore - Transform urls on the fly - Control the cache management with FileSource API - Limit viewport to Iceland - Shows how to add 3D extruded shapes - Shows how to show 3D extruded buildings - Shows how to animate georeferenced images - Show 2 MapView on screen with a bottom sheet - Show a static bitmap taken with the MapSnapshotter - Show how to reuse a MapSnapshotter instance - Show how to add a marker to a Snapshot - Show how to load a local style with a Snapshot - Use Android SDK Animators to animate camera position changes - Use Android SDK Views as symbols - Use TextureView to render the map - Resize a map rendered on a TextureView - Animate a map rendered on a TextureView - Enable a transparent surface on TextureView - Blend an overlay on a map - Example Custom Geometry Source - Load a map without providing a style URI or JSON - Suzhou using Droid Sans for Chinese glyphs - Example raster-dem source and hillshade layer - Use HeatmapLayer to visualise earthquakes - Manipulate gestures detector\'s settings - Merge external offline database - Click to add a marker, long-click to drag - Change map\'s style while location is displayed - Showcases location render and tracking modes - Uses LocationComponent in a Fragment - Force location updates and don\'t rely on the engine - Use LocationComponentActivationOptions to set options - Show multiple TextureView MapViews as recyclerView items - Show multiple GLSurfaceView MapViews as recyclerView items - Show a MapView inside a viewpager inside a recyclerView - Show the use PerformanceEvent for performance measurements - Use TurfTransformation#circle() to show a Cirlce expressed in physical units - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/dimens.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/dimens.xml deleted file mode 100644 index 9d3418343..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/dimens.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - 16dp - 10dp - 96dp - 256dp - 32dp - 0dp - 240dp - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/ids.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/ids.xml deleted file mode 100644 index 6701032d9..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/ids.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml deleted file mode 100644 index 45048f8b0..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - Mapbox Android SDK TestApp - fps30 - fps60 - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/styles.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/styles.xml deleted file mode 100644 index 8d7da603f..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/styles.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/titles.xml b/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/titles.xml deleted file mode 100644 index 90baaed28..000000000 --- a/platform/android/MapboxGLAndroidSDKTestApp/src/main/res/values/titles.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - Support Map Fragment - Map Fragment - Backstack Map Fragment - Multiple Maps on Screen - Add Markers In Bulk - Animated SymbolLayer - Dynamic Marker - Polyline - Polygon - Press Map For Marker - Zoom function with SymbolLayer - Standard InfoWindow - Custom InfoWindow - Custom Dynamic InfoWindow - Animation Types - Zoom Methods - LatLngBounds Method - CameraPosition Method - Scroll By Method - Double Map Activity - Snapshot Activity - Custom Layer - Map Padding - Debug Mode - Offline Map - Update metadata Map - Delete region - Change resources cache path - Min/Max Zoom - ViewPager - Runtime Style - Gradient line layer - Data Driven Style - Circle layer - Local Style file - GeoJson Clustering - Add live realtime data - Print a map - Query feature properties - Count features in box - Count symbols in box - Highlight features in box - Query source features - Symbols - Add Custom Sprite - Simple Map - Map Change Events - Visibility Map - Dialog with map - Url transform - Cache management - Restrict camera to a bounds - Fill extrusions - Building layer - Animated Image Source - Bottom sheet - Map Snapshotter - Map Snapshotter Reuse - Map Snapshot with marker - Map Snapshot with local style - Animator animation - SymbolGenerator - TextureView debug - TextureView resize - TextureView animation - TextureView transparent background - Map overlay - Grid Source - No Style URI/JSON - Local CJK glyph generation - Hillshade - Heatmap layer - Gestures detector - Offline DB merge - Draggable marker - Simple Location Activity - Location Modes Activity - Location Fragment - Manual Location updates - Build Location Activation - RecyclerView TextureView - RecyclerView GLSurfaceView - Nested ViewPager - Performance Measurement - Physical Unit Circle - Download region - \ No newline at end of file diff --git a/platform/android/TESTS.md b/platform/android/TESTS.md deleted file mode 100644 index f0bdeb2dc..000000000 --- a/platform/android/TESTS.md +++ /dev/null @@ -1,117 +0,0 @@ -# Mapbox GL Test App - -## Testing - -### Running Espresso tests on a device - -This test project comes with all the required Android Testing Support Library dependencies -in the Gradle file. Tests are under the `app/src/androidTest` folder. - -Note that before running your tests, you might want to turn off animations on your test device. -It's a known issue that leaving system animations turned on in a test device -(window animation scale, transition animation scale, animator duration scale) -might cause unexpected results, or may lead tests to fail. - -To create a new run configuration: -* Click on Run -> Edit Configurations... -* Click on the plus sign and then on "Android Tests" -* Give a name to the configuration, e.g. `TestAppTests` -* Choose the `MapboxGLAndroidSDKTestApp` module -* Choose `android.support.test.runner.AndroidJUnitRunner` as the instrumentation runner -* Click OK to save the new configuration - -You can now run this configuration from the main toolbar dropdown menu. - -### Running Espresso tests on Firebase within AS - -Tests are under the `app/src/androidTest` folder. - -1) _Sign In_ with your Google account. - -![Firebase Tests AS 1][1] - -2) Or _Add Account_ if you want to sign in with a different account. - -![Firebase Tests AS 2][2] - -3) Select the test configuration you want to run and click _Play_ button. - -4) Click on _Cloud Testing_ tab. You need to create a project in Firebase and define a _Matrix configuration_ previously (see -[Firebase Test Lab for Android guide](https://firebase.google.com/docs/test-lab/overview)). Select your template (e.g. _Nexus 5 (3)_). - -5) Select your _Cloud project_ (e.g. _android-gl-native (android-gl-native)_). - -![Firebase Tests AS 3-5][3] - -6) Click on _OK_ button to run the tests. - -![Firebase Tests AS 6][4] - -7) When tests finish the results will appear within AS. - -![Firebase Tests AS 7][5] - -### Running Espresso tests on AWS Device Farm - -On a terminal, within `mapbox-gl-native/android/java`, -run the tests (`cC` stands for `connectedCheck`): - -``` -$ ./gradlew -Pmapbox.abis=all cC -p MapboxGLAndroidSDKTestApp -``` - -Then: -* Go to your AWS Console and choose Device Farm. -* Create a new project, e.g. `MapboxGLAndroidSDKTestApp` -* On step 1, upload the APK in `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-unaligned.apk` -* On step 2, choose Instrumentation, test filter is `com.mapbox.mapboxgl.testapp.MainActivityTest` and upload the APK in `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-androidTest-unaligned.apk` -* On step 3, choose a device pool. E.g. Top Devices -* On step 4, customize your device state (if needed) -* Finally, confirm the configuration and run the tests. - -On Step 2, you can also separate by commas different classes: `com.mapbox.mapboxgl.testapp.MainActivityTest,com.mapbox.mapboxgl.testapp.MainActivityScreenTest` - -If you have no tests for your app, or want to test some random user behavior, -you can just choose "Built-in: Fuzz" in step 2. - -### Running pure JUnit tests - -These tests run on a local JVM on your development machine and they are extremely fast to run -(as compared to Espresso). These tests are located under `src/test/java`. To run them you switch -to the Unit Tests build variant, then right click the corresponding test class or method -and select "Run ...". - -You can also have a run configuration: -* Click on Run -> Edit Configurations... -* Click on "Junit Tests" -* Give a name to the configuration, e.g. `JUnit tests` -* As "Test Kind", choose "All in directory" -* As folder, choose the following folder: `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/src/test/java` -* Click OK to save the new configuration - -You can also run the tests from the command line with: - -``` -$ ./gradlew -Pmapbox.abis=none test -p MapboxGLAndroidSDKTestApp -``` - -### Running the UI/Application Exerciser Monkey - -Similar to the "Built-in: Fuzz" test mentioned above, Android provides -[Monkey](http://developer.android.com/tools/help/monkey.html), -"a program that runs on your emulator or device and generates pseudo-random streams of user events -such as clicks, touches, or gestures, as well as a number of system-level events." - -To exercise Monkey on the test app, install the package on the device (e.g. via Android Studio) -and then: - -``` -$ adb shell monkey -p com.mapbox.mapboxgl.testapp -v 500 -``` - - -[1]: ./art/tests/FirebaseTestsAS_1.png -[2]: ./art/tests/FirebaseTestsAS_2.png -[3]: ./art/tests/FirebaseTestsAS_3-5.png -[4]: ./art/tests/FirebaseTestsAS_6.png -[5]: ./art/tests/FirebaseTestsAS_7.png diff --git a/platform/android/art/tests/FirebaseTestsAS_1.png b/platform/android/art/tests/FirebaseTestsAS_1.png deleted file mode 100644 index 5bdd9907f..000000000 Binary files a/platform/android/art/tests/FirebaseTestsAS_1.png and /dev/null differ diff --git a/platform/android/art/tests/FirebaseTestsAS_2.png b/platform/android/art/tests/FirebaseTestsAS_2.png deleted file mode 100644 index a482a0178..000000000 Binary files a/platform/android/art/tests/FirebaseTestsAS_2.png and /dev/null differ diff --git a/platform/android/art/tests/FirebaseTestsAS_3-5.png b/platform/android/art/tests/FirebaseTestsAS_3-5.png deleted file mode 100644 index 760acb05c..000000000 Binary files a/platform/android/art/tests/FirebaseTestsAS_3-5.png and /dev/null differ diff --git a/platform/android/art/tests/FirebaseTestsAS_6.png b/platform/android/art/tests/FirebaseTestsAS_6.png deleted file mode 100644 index 2c1ad8be3..000000000 Binary files a/platform/android/art/tests/FirebaseTestsAS_6.png and /dev/null differ diff --git a/platform/android/art/tests/FirebaseTestsAS_7.png b/platform/android/art/tests/FirebaseTestsAS_7.png deleted file mode 100644 index f7db39728..000000000 Binary files a/platform/android/art/tests/FirebaseTestsAS_7.png and /dev/null differ diff --git a/platform/android/build.gradle b/platform/android/build.gradle deleted file mode 100644 index 607958a8a..000000000 --- a/platform/android/build.gradle +++ /dev/null @@ -1,38 +0,0 @@ -buildscript { - apply from: "${rootDir}/gradle/dependencies.gradle" - - repositories { - google() - jcenter() - } - dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' - classpath dependenciesList.licensesPlugin - classpath dependenciesList.kotlinPlugin - classpath dependenciesList.bintrayPlugin - classpath dependenciesList.artifactoryPlugin - classpath dependenciesList.androidPublishPlugin - classpath dependenciesList.jacocoPlugin - } -} - -allprojects { - repositories { - mavenCentral() - google() - jcenter() - // For publishing Maps SDK files to Bintray - maven { url 'https://mapbox.bintray.com/mapbox' } - // Snapshot repository - // maven { url 'https://oss.jfrog.org/artifactory/oss-snapshot-local/' } - } - apply from: "${rootDir}/gradle/ktlint.gradle" -} - -subprojects { - apply from: "${rootDir}/gradle/dependencies.gradle" -} - -// Load build system information. If this file does not exist, run -// `make platform/android/gradle/configuration.gradle` -apply from: "${rootDir}/gradle/configuration.gradle" \ No newline at end of file diff --git a/platform/android/checkstyle.xml b/platform/android/checkstyle.xml deleted file mode 100644 index c73ada156..000000000 --- a/platform/android/checkstyle.xml +++ /dev/null @@ -1,226 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/platform/android/config.cmake b/platform/android/config.cmake deleted file mode 100644 index 98d18ca32..000000000 --- a/platform/android/config.cmake +++ /dev/null @@ -1,143 +0,0 @@ -set(USE_GLES2 ON) - -include(cmake/sqlite.cmake) - -# Build thin archives. -set(CMAKE_CXX_ARCHIVE_CREATE " cruT ") -set(CMAKE_C_ARCHIVE_CREATE " cruT ") -set(CMAKE_CXX_ARCHIVE_APPEND " ruT ") -set(CMAKE_C_ARCHIVE_APPEND " ruT ") - -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffunction-sections -fdata-sections") -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ffunction-sections -fdata-sections") - -if ((ANDROID_ABI STREQUAL "armeabi-v7a") OR (ANDROID_ABI STREQUAL "arm64-v8a") OR - (ANDROID_ABI STREQUAL "x86") OR (ANDROID_ABI STREQUAL "x86_64")) - # Use Identical Code Folding on platforms that support the gold linker. - set(CMAKE_EXE_LINKER_FLAGS "-fuse-ld=gold -Wl,--icf=safe ${CMAKE_EXE_LINKER_FLAGS}") - set(CMAKE_SHARED_LINKER_FLAGS "-fuse-ld=gold -Wl,--icf=safe ${CMAKE_SHARED_LINKER_FLAGS}") -endif() - -set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--gc-sections -Wl,--version-script=${CMAKE_SOURCE_DIR}/platform/android/version-script") -set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections -Wl,--version-script=${CMAKE_SOURCE_DIR}/platform/android/version-script") - -# Use LTO in Release builds. Due to a toolchain issue, -O2 is also required for the link step (https://github.com/android-ndk/ndk/issues/721) -set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -flto") -set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -flto") -set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -flto") -set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} -flto") -set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} -flto -O2") -set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -flto -O2") -set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} -flto -O2") -set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} -flto -O2") - -## mbgl core ## - -macro(mbgl_platform_core) - # Modify platform/android/core-files.json to change the source files for this target. - target_sources_from_file(mbgl-core PRIVATE platform/android/core-files.json) - - target_include_directories(mbgl-core - PUBLIC platform/default/include - PRIVATE platform/android/include - ) - - target_link_libraries(mbgl-core - PUBLIC Mapbox::Base::jni.hpp - PUBLIC -llog - PUBLIC -landroid - PUBLIC -ljnigraphics - PUBLIC -lEGL - PUBLIC -lGLESv2 - PUBLIC -latomic - PUBLIC -lz - ) -endmacro() - - -macro(mbgl_filesource) - # Modify platform/android/filesource-files.json to change the source files for this target. - target_sources_from_file(mbgl-filesource PRIVATE platform/android/filesource-files.json) - - target_link_libraries(mbgl-filesource - PUBLIC sqlite - PUBLIC Mapbox::Base::jni.hpp - PUBLIC -llog - PUBLIC -landroid - PUBLIC -latomic - ) -endmacro() - -## Shared library - -add_library(mapbox-gl SHARED - platform/android/src/main.cpp -) - -target_include_directories(mapbox-gl - PRIVATE src -) - -target_link_libraries(mapbox-gl - PRIVATE mbgl-core - PRIVATE mbgl-filesource -) - -## Test executable ## -macro(mbgl_platform_test) - target_sources(mbgl-test - PRIVATE platform/android/src/test/test_runner.cpp - PRIVATE platform/android/src/test/runtime.cpp - ) - - target_include_directories(mbgl-test - PRIVATE platform/android/include - ) - - set_target_properties(mbgl-test - PROPERTIES - LINK_FLAGS - "-fPIE -pie \ - -Wl,--export-dynamic \ - -Wl,--version-script=${CMAKE_SOURCE_DIR}/platform/android/src/test/version-script") - - target_link_libraries(mbgl-test - PRIVATE mbgl-filesource - ) -endmacro() - -## Benchmark ## -macro(mbgl_platform_benchmark) - target_sources(mbgl-benchmark - PRIVATE platform/android/src/test/benchmark_runner.cpp - PRIVATE platform/android/src/test/runtime.cpp - ) - - set_target_properties(mbgl-benchmark - PROPERTIES - LINK_FLAGS - "-fPIE -pie \ - -Wl,--export-dynamic \ - -Wl,--version-script=${CMAKE_SOURCE_DIR}/platform/android/src/test/version-script") - - target_link_libraries(mbgl-benchmark - PRIVATE mbgl-filesource - ) -endmacro() - - -## Custom layer example ## - -add_library(example-custom-layer SHARED - platform/android/src/example_custom_layer.cpp -) - -target_include_directories(example-custom-layer - PRIVATE include -) - -target_link_libraries(example-custom-layer PRIVATE - mapbox-base - -llog - -lGLESv2 -) diff --git a/platform/android/core-files.json b/platform/android/core-files.json deleted file mode 100644 index e21a586e2..000000000 --- a/platform/android/core-files.json +++ /dev/null @@ -1,195 +0,0 @@ -{ - "//": "This file can be edited manually and is the canonical source.", - "sources": [ - "platform/android/src/main.cpp", - "platform/android/src/android_renderer_backend.cpp", - "platform/android/src/android_renderer_frontend.cpp", - "platform/android/src/annotation/marker.cpp", - "platform/android/src/annotation/polygon.cpp", - "platform/android/src/annotation/polyline.cpp", - "platform/android/src/async_task.cpp", - "platform/android/src/attach_env.cpp", - "platform/android/src/bitmap.cpp", - "platform/android/src/bitmap_factory.cpp", - "platform/android/src/conversion/collection.cpp", - "platform/android/src/conversion/color.cpp", - "platform/android/src/conversion/constant.cpp", - "platform/android/src/geojson/feature.cpp", - "platform/android/src/geojson/feature_collection.cpp", - "platform/android/src/geojson/geometry.cpp", - "platform/android/src/geojson/geometry_collection.cpp", - "platform/android/src/geojson/line_string.cpp", - "platform/android/src/geojson/multi_line_string.cpp", - "platform/android/src/geojson/multi_point.cpp", - "platform/android/src/geojson/multi_polygon.cpp", - "platform/android/src/geojson/point.cpp", - "platform/android/src/geojson/polygon.cpp", - "platform/android/src/geometry/lat_lng.cpp", - "platform/android/src/geometry/lat_lng_bounds.cpp", - "platform/android/src/geometry/lat_lng_quad.cpp", - "platform/android/src/geometry/projected_meters.cpp", - "platform/android/src/graphics/pointf.cpp", - "platform/android/src/graphics/rectf.cpp", - "platform/android/src/gson/json_array.cpp", - "platform/android/src/gson/json_element.cpp", - "platform/android/src/gson/json_object.cpp", - "platform/android/src/gson/json_primitive.cpp", - "platform/android/src/i18n/collator.cpp", - "platform/android/src/i18n/number_format.cpp", - "platform/android/src/image.cpp", - "platform/android/src/java/util.cpp", - "platform/android/src/java_types.cpp", - "platform/android/src/jni.cpp", - "platform/android/src/jni_native.cpp", - "platform/android/src/logger.cpp", - "platform/android/src/logging_android.cpp", - "platform/android/src/mapbox.cpp", - "platform/android/src/map/camera_position.cpp", - "platform/android/src/map/image.cpp", - "platform/android/src/map_renderer.cpp", - "platform/android/src/map_renderer_runnable.cpp", - "platform/android/src/native_map_view.cpp", - "platform/android/src/run_loop.cpp", - "platform/android/src/snapshotter/map_snapshot.cpp", - "platform/android/src/snapshotter/map_snapshotter.cpp", - "platform/android/src/string_util.cpp", - "platform/android/src/style/conversion/filter.cpp", - "platform/android/src/style/conversion/position.cpp", - "platform/android/src/style/conversion/transition_options.cpp", - "platform/android/src/style/conversion/url_or_tileset.cpp", - "platform/android/src/style/formatted.cpp", - "platform/android/src/style/formatted_section.cpp", - "platform/android/src/style/layers/background_layer.cpp", - "platform/android/src/style/layers/circle_layer.cpp", - "platform/android/src/style/layers/custom_layer.cpp", - "platform/android/src/style/layers/fill_extrusion_layer.cpp", - "platform/android/src/style/layers/fill_layer.cpp", - "platform/android/src/style/layers/heatmap_layer.cpp", - "platform/android/src/style/layers/hillshade_layer.cpp", - "platform/android/src/style/layers/layer.cpp", - "platform/android/src/style/layers/layer_manager.cpp", - "platform/android/src/style/layers/line_layer.cpp", - "platform/android/src/style/layers/raster_layer.cpp", - "platform/android/src/style/layers/symbol_layer.cpp", - "platform/android/src/style/light.cpp", - "platform/android/src/style/position.cpp", - "platform/android/src/style/sources/custom_geometry_source.cpp", - "platform/android/src/style/sources/geojson_source.cpp", - "platform/android/src/style/sources/image_source.cpp", - "platform/android/src/style/sources/raster_dem_source.cpp", - "platform/android/src/style/sources/raster_source.cpp", - "platform/android/src/style/sources/source.cpp", - "platform/android/src/style/sources/unknown_source.cpp", - "platform/android/src/style/sources/vector_source.cpp", - "platform/android/src/style/transition_options.cpp", - "platform/android/src/style/value.cpp", - "platform/android/src/text/local_glyph_rasterizer.cpp", - "platform/android/src/gl_functions.cpp", - "platform/android/src/thread.cpp", - "platform/android/src/timer.cpp", - "platform/default/src/mbgl/gfx/headless_backend.cpp", - "platform/default/src/mbgl/gfx/headless_frontend.cpp", - "platform/default/src/mbgl/gl/headless_backend.cpp", - "platform/default/src/mbgl/map/map_snapshotter.cpp", - "platform/default/src/mbgl/text/bidi.cpp", - "platform/default/src/mbgl/util/compression.cpp", - "platform/default/src/mbgl/util/monotonic_timer.cpp", - "platform/default/src/mbgl/util/png_writer.cpp", - "platform/default/src/mbgl/util/thread_local.cpp", - "platform/default/src/mbgl/util/utf.cpp", - "platform/linux/src/headless_backend_egl.cpp" - ], - "public_headers": { - "jni/string_conversion.hpp": "platform/default/include/jni/string_conversion.hpp", - "mbgl/gfx/headless_backend.hpp": "platform/default/include/mbgl/gfx/headless_backend.hpp", - "mbgl/gfx/headless_frontend.hpp": "platform/default/include/mbgl/gfx/headless_frontend.hpp", - "mbgl/gl/headless_backend.hpp": "platform/default/include/mbgl/gl/headless_backend.hpp", - "mbgl/map/map_snapshotter.hpp": "platform/default/include/mbgl/map/map_snapshotter.hpp" - }, - "private_headers": { - "android_renderer_backend.hpp": "platform/android/src/android_renderer_backend.hpp", - "android_renderer_frontend.hpp": "platform/android/src/android_renderer_frontend.hpp", - "annotation/marker.hpp": "platform/android/src/annotation/marker.hpp", - "annotation/multi_point.hpp": "platform/android/src/annotation/multi_point.hpp", - "annotation/polygon.hpp": "platform/android/src/annotation/polygon.hpp", - "annotation/polyline.hpp": "platform/android/src/annotation/polyline.hpp", - "attach_env.hpp": "platform/android/src/attach_env.hpp", - "bitmap.hpp": "platform/android/src/bitmap.hpp", - "bitmap_factory.hpp": "platform/android/src/bitmap_factory.hpp", - "conversion/collection.hpp": "platform/android/src/conversion/collection.hpp", - "conversion/color.hpp": "platform/android/src/conversion/color.hpp", - "conversion/constant.hpp": "platform/android/src/conversion/constant.hpp", - "conversion/conversion.hpp": "platform/android/src/conversion/conversion.hpp", - "geojson/feature.hpp": "platform/android/src/geojson/feature.hpp", - "geojson/feature_collection.hpp": "platform/android/src/geojson/feature_collection.hpp", - "geojson/geometry.hpp": "platform/android/src/geojson/geometry.hpp", - "geojson/geometry_collection.hpp": "platform/android/src/geojson/geometry_collection.hpp", - "geojson/line_string.hpp": "platform/android/src/geojson/line_string.hpp", - "geojson/multi_line_string.hpp": "platform/android/src/geojson/multi_line_string.hpp", - "geojson/multi_point.hpp": "platform/android/src/geojson/multi_point.hpp", - "geojson/multi_polygon.hpp": "platform/android/src/geojson/multi_polygon.hpp", - "geojson/point.hpp": "platform/android/src/geojson/point.hpp", - "geojson/polygon.hpp": "platform/android/src/geojson/polygon.hpp", - "geojson/util.hpp": "platform/android/src/geojson/util.hpp", - "geometry/lat_lng.hpp": "platform/android/src/geometry/lat_lng.hpp", - "geometry/lat_lng_bounds.hpp": "platform/android/src/geometry/lat_lng_bounds.hpp", - "geometry/lat_lng_quad.hpp": "platform/android/src/geometry/lat_lng_quad.hpp", - "geometry/projected_meters.hpp": "platform/android/src/geometry/projected_meters.hpp", - "graphics/pointf.hpp": "platform/android/src/graphics/pointf.hpp", - "graphics/rectf.hpp": "platform/android/src/graphics/rectf.hpp", - "gson/json_array.hpp": "platform/android/src/gson/json_array.hpp", - "gson/json_element.hpp": "platform/android/src/gson/json_element.hpp", - "gson/json_object.hpp": "platform/android/src/gson/json_object.hpp", - "gson/json_primitive.hpp": "platform/android/src/gson/json_primitive.hpp", - "java/util.hpp": "platform/android/src/java/util.hpp", - "java_types.hpp": "platform/android/src/java_types.hpp", - "jni.hpp": "platform/android/src/jni.hpp", - "jni_native.hpp": "platform/android/src/jni_native.hpp", - "i18n/collator_jni.hpp": "platform/android/src/i18n/collator_jni.hpp", - "i18n/number_format_jni.hpp": "platform/android/src/i18n/number_format_jni.hpp", - "logger.hpp": "platform/android/src/logger.hpp", - "mapbox.hpp": "platform/android/src/mapbox.hpp", - "map/camera_position.hpp": "platform/android/src/map/camera_position.hpp", - "map/image.hpp": "platform/android/src/map/image.hpp", - "map_renderer.hpp": "platform/android/src/map_renderer.hpp", - "map_renderer_runnable.hpp": "platform/android/src/map_renderer_runnable.hpp", - "native_map_view.hpp": "platform/android/src/native_map_view.hpp", - "run_loop_impl.hpp": "platform/android/src/run_loop_impl.hpp", - "snapshotter/map_snapshot.hpp": "platform/android/src/snapshotter/map_snapshot.hpp", - "snapshotter/map_snapshotter.hpp": "platform/android/src/snapshotter/map_snapshotter.hpp", - "style/android_conversion.hpp": "platform/android/src/style/android_conversion.hpp", - "style/conversion/filter.hpp": "platform/android/src/style/conversion/filter.hpp", - "style/conversion/position.hpp": "platform/android/src/style/conversion/position.hpp", - "style/conversion/property_expression.hpp": "platform/android/src/style/conversion/property_expression.hpp", - "style/conversion/property_value.hpp": "platform/android/src/style/conversion/property_value.hpp", - "style/conversion/transition_options.hpp": "platform/android/src/style/conversion/transition_options.hpp", - "style/conversion/url_or_tileset.hpp": "platform/android/src/style/conversion/url_or_tileset.hpp", - "style/formatted.hpp": "platform/android/src/style/formatted.hpp", - "style/formatted_section.hpp": "platform/android/src/style/formatted_section.hpp", - "style/layers/background_layer.hpp": "platform/android/src/style/layers/background_layer.hpp", - "style/layers/circle_layer.hpp": "platform/android/src/style/layers/circle_layer.hpp", - "style/layers/custom_layer.hpp": "platform/android/src/style/layers/custom_layer.hpp", - "style/layers/fill_extrusion_layer.hpp": "platform/android/src/style/layers/fill_extrusion_layer.hpp", - "style/layers/fill_layer.hpp": "platform/android/src/style/layers/fill_layer.hpp", - "style/layers/heatmap_layer.hpp": "platform/android/src/style/layers/heatmap_layer.hpp", - "style/layers/hillshade_layer.hpp": "platform/android/src/style/layers/hillshade_layer.hpp", - "style/layers/layer.hpp": "platform/android/src/style/layers/layer.hpp", - "style/layers/layer_manager.hpp": "platform/android/src/style/layers/layer_manager.hpp", - "style/layers/line_layer.hpp": "platform/android/src/style/layers/line_layer.hpp", - "style/layers/raster_layer.hpp": "platform/android/src/style/layers/raster_layer.hpp", - "style/layers/symbol_layer.hpp": "platform/android/src/style/layers/symbol_layer.hpp", - "style/light.hpp": "platform/android/src/style/light.hpp", - "style/position.hpp": "platform/android/src/style/position.hpp", - "style/sources/custom_geometry_source.hpp": "platform/android/src/style/sources/custom_geometry_source.hpp", - "style/sources/geojson_source.hpp": "platform/android/src/style/sources/geojson_source.hpp", - "style/sources/image_source.hpp": "platform/android/src/style/sources/image_source.hpp", - "style/sources/raster_dem_source.hpp": "platform/android/src/style/sources/raster_dem_source.hpp", - "style/sources/raster_source.hpp": "platform/android/src/style/sources/raster_source.hpp", - "style/sources/source.hpp": "platform/android/src/style/sources/source.hpp", - "style/sources/unknown_source.hpp": "platform/android/src/style/sources/unknown_source.hpp", - "style/sources/vector_source.hpp": "platform/android/src/style/sources/vector_source.hpp", - "style/transition_options.hpp": "platform/android/src/style/transition_options.hpp", - "style/value.hpp": "platform/android/src/style/value.hpp", - "text/local_glyph_rasterizer_jni.hpp": "platform/android/src/text/local_glyph_rasterizer_jni.hpp" - } -} diff --git a/platform/android/filesource-files.json b/platform/android/filesource-files.json deleted file mode 100644 index ab92c2c32..000000000 --- a/platform/android/filesource-files.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "//": "This file can be edited manually and is the canonical source.", - "sources": [ - "platform/android/src/asset_manager_file_source.cpp", - "platform/android/src/connectivity_listener.cpp", - "platform/android/src/file_source.cpp", - "platform/android/src/http_file_source.cpp", - "platform/android/src/offline/offline_manager.cpp", - "platform/android/src/offline/offline_region.cpp", - "platform/android/src/offline/offline_region_definition.cpp", - "platform/android/src/offline/offline_region_error.cpp", - "platform/android/src/offline/offline_region_status.cpp", - "platform/default/src/mbgl/storage/sqlite3.cpp" - ], - "public_headers": {}, - "private_headers": { - "asset_manager.hpp": "platform/android/src/asset_manager.hpp", - "asset_manager_file_source.hpp": "platform/android/src/asset_manager_file_source.hpp", - "connectivity_listener.hpp": "platform/android/src/connectivity_listener.hpp", - "file_source.hpp": "platform/android/src/file_source.hpp", - "offline/offline_manager.hpp": "platform/android/src/offline/offline_manager.hpp", - "offline/offline_region.hpp": "platform/android/src/offline/offline_region.hpp", - "offline/offline_region_definition.hpp": "platform/android/src/offline/offline_region_definition.hpp", - "offline/offline_region_error.hpp": "platform/android/src/offline/offline_region_error.hpp", - "offline/offline_region_status.hpp": "platform/android/src/offline/offline_region_status.hpp" - } -} diff --git a/platform/android/gradle/android-nitpick.gradle b/platform/android/gradle/android-nitpick.gradle deleted file mode 100644 index 6db351967..000000000 --- a/platform/android/gradle/android-nitpick.gradle +++ /dev/null @@ -1,66 +0,0 @@ -apply from: "${rootDir}/gradle/dependencies.gradle" - -def MAPBOX_JAVA_DIR = 'mapbox-java' -def MAPBOX_JAVA_TAG_PREFIX = 'v' - -def MAPBOX_TELEMETRY_DIR = 'mapbox-events-android' -def MAPBOX_TELEMETRY_TAG_PREFIX = 'telem-' -def MAPBOX_CORE_TAG_PREFIX = '-core-' - -def MAPBOX_GESTURES_DIR = 'mapbox-gestures-android' -def MAPBOX_GESTURES_TAG_PREFIX = 'v' - -task androidNitpick { - doLast { - println "Running android nitpick script" - - println "Verify vendor submodule pins" - verifyVendorSubmodulePin(MAPBOX_JAVA_DIR, MAPBOX_JAVA_TAG_PREFIX, versions.mapboxServices) - verifyVendorSubmodulePin(MAPBOX_TELEMETRY_DIR, MAPBOX_TELEMETRY_TAG_PREFIX, - versions.mapboxTelemetry + MAPBOX_CORE_TAG_PREFIX + versions.mapboxCore) - verifyVendorSubmodulePin(MAPBOX_GESTURES_DIR, MAPBOX_GESTURES_TAG_PREFIX, versions.mapboxGestures) - - verifyLicenseGeneration() - } -} - -private def verifyVendorSubmodulePin(def dir, def prefix, def version) { - println "Verify vendor submodule pin: ${dir} (${prefix + version})" - exec { - workingDir = "${rootDir}/vendor/${dir}" - commandLine "git", "fetch", "-t" - } - - def output = new ByteArrayOutputStream() - exec { - workingDir = "${rootDir}/vendor/${dir}" - commandLine "git", "rev-list", "-n", "1", "tags/${prefix + version}" - standardOutput = output - } - def expectedCommit = output.toString().trim() - output.reset() - - exec { - workingDir = "${rootDir}/vendor/${dir}" - commandLine "git", "rev-parse", "HEAD" - standardOutput = output - } - def actualCommit = output.toString().trim() - - if (actualCommit != expectedCommit) { - throw new IllegalStateException("${dir} vendor repository is not checked out on the consumed binary's tag.\n" + - "Expected commit: " + expectedCommit + "(${prefix + version} tag).\n" + - "Actual commit: " + actualCommit + ".\n" + - "If you've updated the version in the dependencies.gradle file, make sure to bump the submodule pin in the platform/android/vendor/ directory to match the release tag.\n" + - "If you've bumped the pin, make sure to verify the version tag prefix in the android-nitpick.gradle file.") - } - output.close() -} - -private def verifyLicenseGeneration() { - println "Verify license generation with git diff..." - exec { - workingDir = "${rootDir}" - commandLine "python", "scripts/validate-license.py" - } -} \ No newline at end of file diff --git a/platform/android/gradle/artifact-settings.gradle b/platform/android/gradle/artifact-settings.gradle deleted file mode 100644 index acf29eeb8..000000000 --- a/platform/android/gradle/artifact-settings.gradle +++ /dev/null @@ -1,21 +0,0 @@ -ext { - mapboxArtifactGroupId = 'com.mapbox.mapboxsdk' - mapboxArtifactId = 'mapbox-android-sdk' - mapboxArtifactTitle = 'Mapbox Maps SDK for Android' - mapboxArtifactDescription = 'Mapbox Maps SDK for Android' - mapboxDeveloperName = 'Mapbox' - mapboxDeveloperId = 'mapbox' - mapboxArtifactUrl = 'https://github.com/mapbox/mapbox-gl-native' - mapboxArtifactVcsUrl = 'https://github.com/mapbox/mapbox-gl-native.git' - mapboxArtifactScmUrl = 'scm:git@github.com:mapbox/mapbox-gl-native.git' - mapboxArtifactLicenseName = 'BSD' - mapboxArtifactLicenseUrl = 'https://opensource.org/licenses/BSD-2-Clause' - versionName = project.hasProperty('VERSION_NAME') ? project.property('VERSION_NAME') : System.getenv('VERSION_NAME') - - mapboxBintrayUserOrg = 'mapbox' - mapboxBintrayRepoName = 'mapbox' - mapboxBintrayPackageName = 'com.mapbox.mapboxsdk:mapbox-android-sdk' - mapboxBintrayUser = project.hasProperty('BINTRAY_USER') ? project.property('BINTRAY_USER') : System.getenv('BINTRAY_USER') - mapboxBintrayApiKey = project.hasProperty('BINTRAY_API_KEY') ? project.property('BINTRAY_API_KEY') : System.getenv('BINTRAY_API_KEY') - mapboxGpgPassphrase = project.hasProperty('GPG_PASSPHRASE') ? project.property('GPG_PASSPHRASE') : System.getenv('GPG_PASSPHRASE') -} diff --git a/platform/android/gradle/dependencies.gradle b/platform/android/gradle/dependencies.gradle deleted file mode 100644 index 31633488e..000000000 --- a/platform/android/gradle/dependencies.gradle +++ /dev/null @@ -1,90 +0,0 @@ -ext { - - androidVersions = [ - minSdkVersion : 14, - targetSdkVersion : 28, - compileSdkVersion: 28, - ] - - versions = [ - mapboxServices : '4.9.0', - mapboxTelemetry : '4.5.1', - mapboxCore : '1.3.0', - mapboxGestures : '0.5.1', - mapboxAccounts : '0.2.0', - supportLib : '28.0.0', - constraintLayout: '1.1.2', - uiAutomator : '2.1.3', - espresso : '3.0.2', - testRunner : '1.0.2', - leakCanary : '1.6.3', - junit : '4.12', - mockito : '3.0.0', - mockk : '1.9.3', - robolectric : '4.3', - timber : '4.7.1', - okhttp : '3.12.3', - kotlin : '1.3.41', - licenses : '0.8.5', - bintray : '1.8.4', - artifactory : '4.9.3', - androidPublish : '3.6.2', - lint : '26.4.2', - gms : '16.0.0', - soLoader : '0.6.1', - jacoco : '0.8.4', - appcenter : '1.4', - ktlint : '0.34.0', - commonsIO : '2.6' - ] - - dependenciesList = [ - mapboxJavaGeoJSON : "com.mapbox.mapboxsdk:mapbox-sdk-geojson:${versions.mapboxServices}", - mapboxAndroidTelemetry : "com.mapbox.mapboxsdk:mapbox-android-telemetry:${versions.mapboxTelemetry}", - mapboxAndroidGestures : "com.mapbox.mapboxsdk:mapbox-android-gestures:${versions.mapboxGestures}", - mapboxAndroidAccounts : "com.mapbox.mapboxsdk:mapbox-android-accounts:${versions.mapboxAccounts}", - mapboxJavaTurf : "com.mapbox.mapboxsdk:mapbox-sdk-turf:${versions.mapboxServices}", - - junit : "junit:junit:${versions.junit}", - mockito : "org.mockito:mockito-core:${versions.mockito}", - mockk : "io.mockk:mockk:${versions.mockk}", - robolectric : "org.robolectric:robolectric:${versions.robolectric}", - - testRunner : "com.android.support.test:runner:${versions.testRunner}", - testRules : "com.android.support.test:rules:${versions.testRunner}", - testEspressoCore : "com.android.support.test.espresso:espresso-core:${versions.espresso}", - testEspressoIntents : "com.android.support.test.espresso:espresso-intents:${versions.espresso}", - testEspressoContrib : "com.android.support.test.espresso:espresso-contrib:${versions.espresso}", - testUiAutomator : "com.android.support.test.uiautomator:uiautomator-v18:${versions.uiAutomator}", - appCenter : "com.microsoft.appcenter:espresso-test-extension:${versions.appcenter}", - commonsIO : "commons-io:commons-io:${versions.commonsIO}", - supportAnnotations : "com.android.support:support-annotations:${versions.supportLib}", - supportAppcompatV7 : "com.android.support:appcompat-v7:${versions.supportLib}", - supportFragmentV4 : "com.android.support:support-fragment:${versions.supportLib}", - supportUtilV4 : "com.android.support:support-core-utils:${versions.supportLib}", - supportDesign : "com.android.support:design:${versions.supportLib}", - supportRecyclerView : "com.android.support:recyclerview-v7:${versions.supportLib}", - supportConstraintLayout: "com.android.support.constraint:constraint-layout:${versions.constraintLayout}", - - gmsLocation : "com.google.android.gms:play-services-location:${versions.gms}", - timber : "com.jakewharton.timber:timber:${versions.timber}", - okhttp3 : "com.squareup.okhttp3:okhttp:${versions.okhttp}", - leakCanaryDebug : "com.squareup.leakcanary:leakcanary-android:${versions.leakCanary}", - leakCanaryRelease : "com.squareup.leakcanary:leakcanary-android-no-op:${versions.leakCanary}", - soLoader : "com.facebook.soloader:soloader:${versions.soLoader}", - - kotlinLib : "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${versions.kotlin}", - kotlinPlugin : "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}", - licensesPlugin : "com.jaredsburrows:gradle-license-plugin:${versions.licenses}", - bintrayPlugin : "com.jfrog.bintray.gradle:gradle-bintray-plugin:${versions.bintray}", - artifactoryPlugin : "org.jfrog.buildinfo:build-info-extractor-gradle:${versions.artifactory}", - androidPublishPlugin : "digital.wup:android-maven-publish:${versions.androidPublish}", - jacocoPlugin : "org.jacoco:org.jacoco.core:${versions.jacoco}", - - lint : "com.android.tools.lint:lint:${versions.lint}", - lintApi : "com.android.tools.lint:lint-api:${versions.lint}", - lintChecks : "com.android.tools.lint:lint-checks:${versions.lint}", - lintTests : "com.android.tools.lint:lint-tests:${versions.lint}", - ktlint : "com.pinterest:ktlint:${versions.ktlint}" - ] -} diff --git a/platform/android/gradle/gradle-bintray.gradle b/platform/android/gradle/gradle-bintray.gradle deleted file mode 100644 index e8ace7359..000000000 --- a/platform/android/gradle/gradle-bintray.gradle +++ /dev/null @@ -1,117 +0,0 @@ -apply plugin: 'digital.wup.android-maven-publish' -apply plugin: 'maven-publish' -apply plugin: 'com.jfrog.bintray' -apply plugin: 'com.jfrog.artifactory' -apply from: file('../gradle/artifact-settings.gradle') - -version = project.ext.versionName -group = project.ext.mapboxArtifactGroupId - -publishing { - publications { - MapboxMapsSdkPublication(MavenPublication) { - from components.android - groupId this.group - artifactId project.ext.mapboxArtifactId - version this.version - - afterEvaluate { - artifact(androidSourcesJar) - artifact(androidJavadocsJar) - } - - pom.withXml { - final mainNode = asNode() - mainNode.appendNode('name', project.ext.mapboxArtifactTitle) - mainNode.appendNode('description', project.ext.mapboxArtifactTitle) - mainNode.appendNode('url', project.ext.mapboxArtifactUrl) - - final licenseNode = mainNode.appendNode('licenses').appendNode('license') - licenseNode.appendNode('name', project.ext.mapboxArtifactLicenseName) - licenseNode.appendNode('url', project.ext.mapboxArtifactLicenseUrl) - licenseNode.appendNode('distribution', "repo") - - final developerNode = mainNode.appendNode('developers').appendNode('developer') - developerNode.appendNode('id', project.ext.mapboxDeveloperId) - developerNode.appendNode('name', project.ext.mapboxDeveloperName) - - final scmNode = mainNode.appendNode("scm") - scmNode.appendNode("connection", project.ext.mapboxArtifactScmUrl) - scmNode.appendNode("developerConnection", project.ext.mapboxArtifactScmUrl) - scmNode.appendNode("url", project.ext.mapboxArtifactUrl) - } - } - } -} - -bintray { - user = mapboxBintrayUser - key = mapboxBintrayApiKey - publications('MapboxMapsSdkPublication') - pkg { - repo = project.ext.mapboxBintrayRepoName - name = project.ext.mapboxBintrayPackageName - userOrg = project.ext.mapboxBintrayUserOrg - licenses = [project.ext.mapboxArtifactLicenseName] - vcsUrl = project.ext.mapboxArtifactVcsUrl - publish = false - version { - name = project.ext.versionName - desc = project.ext.mapboxArtifactDescription - released = new Date() - gpg { - sign = true - passphrase = mapboxGpgPassphrase - } - mavenCentralSync { - sync = false - } - } - } -} - -artifactory { - contextUrl = 'http://oss.jfrog.org' - publish { - repository { - repoKey = 'oss-snapshot-local' - username = mapboxBintrayUser - password = mapboxBintrayApiKey - } - defaults { - publications('MapboxMapsSdkPublication') - } - } -} - -task androidJavadocs(type: Javadoc) { - source = android.sourceSets.main.java.sourceFiles - classpath = files(android.bootClasspath) - failOnError = false -} - -task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { - classifier = 'javadoc' - from androidJavadocs.destinationDir -} - -task androidSourcesJar(type: Jar) { - classifier = 'sources' - from android.sourceSets.main.java.sourceFiles -} - -tasks.withType(Javadoc) { - options.addStringOption('encoding', 'UTF-8') - options.addStringOption('docencoding', 'UTF-8') - options.addStringOption('charset', 'UTF-8') -} - -afterEvaluate { project -> - android.libraryVariants.all { variant -> - tasks.androidJavadocs.doFirst { - classpath += files(variant.javaCompile.classpath.files) - } - } -} - - diff --git a/platform/android/gradle/gradle-checkstyle.gradle b/platform/android/gradle/gradle-checkstyle.gradle deleted file mode 100644 index 8eb4baa85..000000000 --- a/platform/android/gradle/gradle-checkstyle.gradle +++ /dev/null @@ -1,26 +0,0 @@ -apply plugin: 'checkstyle' - -checkstyle { - toolVersion = "7.1.1" // 7.3 - configFile = "../checkstyle.xml" as File -} - -task checkstyle(type: Checkstyle) { - description 'Checks if the code adheres to coding standards' - group 'verification' - configFile file("../checkstyle.xml") - source 'src' - include '**/*.java' - exclude '**/gen/**' - exclude '**/style/*LayerTest.java' - exclude '**/style/LightTest.java' - exclude '**/style/layers/Property.java' - exclude '**/style/layers/PropertyFactory.java' - exclude '**/style/layers/*Layer.java' - exclude '**/style/light/Light.java' - exclude '**/log/LoggerDefinition.java' - exclude '**/log/Logger.java' - exclude '**/Expression.java' - classpath = files() - ignoreFailures = false -} diff --git a/platform/android/gradle/gradle-config.gradle b/platform/android/gradle/gradle-config.gradle deleted file mode 100644 index 834680663..000000000 --- a/platform/android/gradle/gradle-config.gradle +++ /dev/null @@ -1,23 +0,0 @@ -// -// Configuration file for gradle build execution. -// - -task accessToken { - def tokenFile = new File("${projectDir}/src/main/res/values/developer-config.xml") - if (!tokenFile.exists()) { - String mapboxAccessToken = "$System.env.MAPBOX_ACCESS_TOKEN" - if (mapboxAccessToken == "null") { - System.out.println("You should set the MAPBOX_ACCESS_TOKEN environment variable.") - mapboxAccessToken = "YOUR_MAPBOX_ACCESS_TOKEN_GOES_HERE" - } - String tokenFileContents = "\n" + - "\n" + - " " + mapboxAccessToken + "\n" + - "" - tokenFile.write(tokenFileContents) - } -} - -gradle.projectsEvaluated { - preBuild.dependsOn('accessToken') -} diff --git a/platform/android/gradle/gradle-dependencies-graph.gradle b/platform/android/gradle/gradle-dependencies-graph.gradle deleted file mode 100644 index 5cbc7b974..000000000 --- a/platform/android/gradle/gradle-dependencies-graph.gradle +++ /dev/null @@ -1,29 +0,0 @@ -buildscript { - repositories { - mavenCentral() - } - - dependencies { - classpath "com.vanniktech:gradle-dependency-graph-generator-plugin:0.3.0" - } -} - -import com.vanniktech.dependency.graph.generator.DependencyGraphGeneratorPlugin -import com.vanniktech.dependency.graph.generator.DependencyGraphGeneratorExtension.Generator -import com.vanniktech.dependency.graph.generator.dot.GraphFormattingOptions -import com.vanniktech.dependency.graph.generator.dot.Color -import com.vanniktech.dependency.graph.generator.dot.Shape -import com.vanniktech.dependency.graph.generator.dot.Style - -plugins.apply(DependencyGraphGeneratorPlugin) - -def mapboxGenerator = new Generator( - "mapboxLibraries", // Suffix for our Gradle task. - "", // Root suffix that we don't want in this case. - { dependency -> dependency.getModuleGroup().startsWith("com.mapbox.mapboxsdk") }, // Only want Mapbox libs. - { dependency -> true }, // Include transitive dependencies. -) - -dependencyGraphGenerator { - generators = [mapboxGenerator] -} diff --git a/platform/android/gradle/gradle-javadoc.gradle b/platform/android/gradle/gradle-javadoc.gradle deleted file mode 100644 index ba530a9b6..000000000 --- a/platform/android/gradle/gradle-javadoc.gradle +++ /dev/null @@ -1,18 +0,0 @@ -android.libraryVariants.all { variant -> - def name = variant.name - task "javadoc$name"(type: Javadoc) { - description = "Generates javadoc for build $name" - destinationDir = new File(destinationDir, variant.baseName) - source = variant.sourceSets.collect { it.java.sourceFiles }.inject { m, i -> m + i } - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) - options.windowTitle("Mapbox Maps SDK for Android $VERSION_NAME Reference") - options.docTitle("Mapbox Maps SDK for Android $VERSION_NAME") - options.header("Mapbox Maps SDK for Android $VERSION_NAME Reference") - options.bottom("© 2015–2019 Mapbox. All rights reserved.") - options.links("http://docs.oracle.com/javase/7/docs/api/") - options.linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference" - options.overview("src/main/java/overview.html") - options.group("Mapbox Android SDK", "com.mapbox.*") - exclude '**/R.java', '**/BuildConfig.java', '**/**.java.ejs', '**/**.html' - } -} \ No newline at end of file diff --git a/platform/android/gradle/gradle-lint.gradle b/platform/android/gradle/gradle-lint.gradle deleted file mode 100644 index cbebeaa74..000000000 --- a/platform/android/gradle/gradle-lint.gradle +++ /dev/null @@ -1,30 +0,0 @@ -task ciLint(type: Copy) { - if (isLocalBuild()) { - from "${projectDir}/lint/lint-baseline-local.xml" - into "${projectDir}" - rename { String fileName -> - fileName.replace("lint-baseline-local.xml", "lint-baseline.xml") - } - } else { - from "${projectDir}/lint/lint-baseline-ci.xml" - into "${projectDir}" - rename { String fileName -> - fileName.replace("lint-baseline-ci.xml", "lint-baseline.xml") - } - } -} - -def isLocalBuild() { - if (System.getenv('IS_LOCAL_DEVELOPMENT') != null) { - return System.getenv('IS_LOCAL_DEVELOPMENT').toBoolean() - } - return true -} - -lint.dependsOn ciLint - -tasks.whenTaskAdded { task -> - if (task.name == 'lintVitalRelease') { - task.dependsOn ciLint - } -} \ No newline at end of file diff --git a/platform/android/gradle/gradle-make.gradle b/platform/android/gradle/gradle-make.gradle deleted file mode 100644 index 65d971cc9..000000000 --- a/platform/android/gradle/gradle-make.gradle +++ /dev/null @@ -1,18 +0,0 @@ -// -// Contains GL-native make commands -// - -task makeClean(type: Exec) { - workingDir '../../' - commandLine 'make', 'clean' -} - -task makeAndroid(type: Exec) { - workingDir '../../' - commandLine 'make', 'android' -} - -task makeAndroidAll(type: Exec) { - workingDir '../../' - commandLine 'make', 'apackage' -} diff --git a/platform/android/gradle/gradle-update-vendor-modules.gradle b/platform/android/gradle/gradle-update-vendor-modules.gradle deleted file mode 100644 index e215450ec..000000000 --- a/platform/android/gradle/gradle-update-vendor-modules.gradle +++ /dev/null @@ -1,8 +0,0 @@ -task updateVendorSubmodules { - doLast { - exec { - workingDir = "${rootDir}" - commandLine "git", "submodule", "update", "--init", "vendor" - } - } -} \ No newline at end of file diff --git a/platform/android/gradle/jacoco-report.gradle b/platform/android/gradle/jacoco-report.gradle deleted file mode 100644 index 64c99e09f..000000000 --- a/platform/android/gradle/jacoco-report.gradle +++ /dev/null @@ -1,33 +0,0 @@ -apply plugin: 'jacoco' -apply from: "${rootDir}/gradle/dependencies.gradle" - -jacoco { - toolVersion = versions.jacoco -} - -task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) { - group = "Reporting" - description = "Combine code coverage to unified report." - - reports { - xml.enabled = true - html.enabled = true - } - - def fileExcludes = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*'] - def debugTree = fileTree(dir: "${project.buildDir}/intermediates/javac/debug/classes", excludes: fileExcludes) - def mainSrc = "${project.projectDir}/src/main/java" - println(mainSrc) - def ecSrc = fileTree(dir: "$project.buildDir", include: "**/*.ec") - def execSrc = fileTree(dir: "$project.buildDir", include: "**/*.exec") - - doFirst { - def files = files([ecSrc, execSrc]).files - println "Creating Jacoco Report for ${files.size()} coverage files" - files.each { file -> println file } - } - - sourceDirectories.from = files([mainSrc]) - classDirectories.from = files([debugTree]) - executionData.from = files([ecSrc, execSrc]) -} \ No newline at end of file diff --git a/platform/android/gradle/ktlint.gradle b/platform/android/gradle/ktlint.gradle deleted file mode 100644 index 31743ccd4..000000000 --- a/platform/android/gradle/ktlint.gradle +++ /dev/null @@ -1,27 +0,0 @@ -apply from: "${rootDir}/gradle/dependencies.gradle" - -repositories { - jcenter() -} - -configurations { - ktlint -} - -dependencies { - ktlint dependenciesList.ktlint -} - -task ktlint(type: JavaExec, group: "verification") { - description = "Check Kotlin code style." - classpath = configurations.ktlint - main = "com.pinterest.ktlint.Main" - args "src/**/*.kt" -} - -task ktlintFormat(type: JavaExec, group: "formatting") { - description = "Fix Kotlin code style deviations." - classpath = configurations.ktlint - main = "com.pinterest.ktlint.Main" - args "-F", "src/**/*.kt" -} \ No newline at end of file diff --git a/platform/android/gradle/native-build.gradle b/platform/android/gradle/native-build.gradle deleted file mode 100644 index 0c16c379d..000000000 --- a/platform/android/gradle/native-build.gradle +++ /dev/null @@ -1,70 +0,0 @@ -ext.nativeBuild = { nativeTargets -> - android { - defaultPublishConfig project.hasProperty("mapbox.buildtype") ? project.getProperty("mapbox.buildtype") : "debug" - - // We sometimes want to invoke Gradle without building a native dependency, e.g. when we just want - // to invoke the Java tests. When we explicitly specify an ABI of 'none', no native dependencies are - // added. When another ABI is specified explicitly, we're just going to build that ABI. In all other - // cases, all ABIs are built. - // - // When invoking from the command line or to override the device default, set `-Pmapbox.abis=...` to - // only build the desired architectures. - // - // When building from Android Studio, gradle.properties sets `android.buildOnlyTargetAbi=true` so that - // only the architecture for the device you're running on gets built. - def abi = 'all' - if (!project.hasProperty('android.injected.invoked.from.ide') || project.hasProperty("mapbox.abis")) { - // Errors when the user invokes Gradle from the command line and didn't set mapbox.abis - abi = project.getProperty("mapbox.abis") - } - - if (abi != 'none') { - externalNativeBuild { - cmake { - path "../../../CMakeLists.txt" - version "3.10.2" - } - } - } - - // Allow determining the C++ STL we're using when building Mapbox GL. - def stl = 'c++_static' - if (project.hasProperty("mapbox.stl")) { - stl = project.getProperty("mapbox.stl") - } - - defaultConfig { - if (abi != 'none') { - externalNativeBuild { - cmake { - arguments "-DANDROID_TOOLCHAIN=clang" - arguments "-DANDROID_STL=" + stl - arguments "-DANDROID_CPP_FEATURES=exceptions" - arguments "-DMBGL_PLATFORM=android" - arguments "-DMASON_PLATFORM=android" - arguments "-DNodeJS_EXECUTABLE=" + node - arguments "-Dnpm_EXECUTABLE=" + npm - - // Enable ccache if the user has installed it. - if (ccache?.trim()) { - arguments "-DANDROID_CCACHE=" + ccache - } - - cFlags "-Qunused-arguments" - cppFlags "-Qunused-arguments" - - for (target in nativeTargets) { - targets target - } - - if (abi != 'all') { - abiFilters abi.split(' ') - } else { - abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64" - } - } - } - } - } - } -} \ No newline at end of file diff --git a/platform/android/gradle/wrapper/gradle-wrapper.jar b/platform/android/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 51288f9c2..000000000 Binary files a/platform/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/platform/android/gradle/wrapper/gradle-wrapper.properties b/platform/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index efceced3c..000000000 --- a/platform/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Tue May 28 09:39:37 CEST 2019 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6-all.zip diff --git a/platform/android/gradlew b/platform/android/gradlew deleted file mode 100755 index 4453ccea3..000000000 --- a/platform/android/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save ( ) { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/platform/android/gradlew.bat b/platform/android/gradlew.bat deleted file mode 100644 index e95643d6a..000000000 --- a/platform/android/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/platform/android/resources/compass.svg b/platform/android/resources/compass.svg deleted file mode 100755 index fd27e73f2..000000000 --- a/platform/android/resources/compass.svg +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/platform/android/resources/direction-dot.svg b/platform/android/resources/direction-dot.svg deleted file mode 100755 index 14ce0bf7f..000000000 --- a/platform/android/resources/direction-dot.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/platform/android/resources/dot-arrow.svg b/platform/android/resources/dot-arrow.svg deleted file mode 100644 index 4c2841a54..000000000 --- a/platform/android/resources/dot-arrow.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - diff --git a/platform/android/resources/location-dot.svg b/platform/android/resources/location-dot.svg deleted file mode 100755 index 24addea3c..000000000 --- a/platform/android/resources/location-dot.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - diff --git a/platform/android/resources/location-static-dot.svg b/platform/android/resources/location-static-dot.svg deleted file mode 100755 index 18269bcdf..000000000 --- a/platform/android/resources/location-static-dot.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - diff --git a/platform/android/scripts/exclude-activity-gen.json b/platform/android/scripts/exclude-activity-gen.json deleted file mode 100644 index ab84957e3..000000000 --- a/platform/android/scripts/exclude-activity-gen.json +++ /dev/null @@ -1,53 +0,0 @@ -[ - "BaseLocationActivity", - "MapSnapshotterMarkerActivity", - "MapSnapshotterReuseActivity", - "MapSnapshotterLocalStyleActivity", - "LatLngBoundsActivity", - "BottomSheetActivity", - "MockLocationEngine", - "DeleteRegionActivity", - "RealTimeGeoJsonActivity", - "UpdateMetadataActivity", - "CarDrivingActivity", - "MyLocationTrackingModeActivity", - "MyLocationToggleActivity", - "MyLocationTintActivity", - "MyLocationDrawableActivity", - "DoubleMapActivity", - "LocationPickerActivity", - "GeoJsonClusteringActivity", - "RuntimeStyleTestActivity", - "AnimatedSymbolLayerActivity", - "ViewPagerActivity", - "MapFragmentActivity", - "SupportMapFragmentActivity", - "SnapshotActivity", - "NavigationDrawerActivity", - "QueryRenderedFeaturesBoxHighlightActivity", - "MultiMapActivity", - "MapInDialogActivity", - "ManualZoomActivity", - "MaxMinZoomActivity", - "ScrollByActivity", - "ZoomFunctionSymbolLayerActivity", - "SymbolGeneratorActivity", - "TextureViewTransparentBackgroundActivity", - "SimpleMapActivity", - "RenderTestActivity", - "SymbolLayerActivity", - "LocationFragmentActivity", - "MergeOfflineRegionsActivity", - "NestedViewPagerActivity", - "DebugModeActivity", - "TextureViewDebugModeActivity", - "RuntimeStyleActivity", - "GridSourceActivity", - "AnimatedImageSourceActivity", - "EspressoTestActivity", - "ChangeResourcesCachePathActivity", - "EspressoTestActivity", - "FragmentBackStackActivity", - "ChildFragmentMapInDialogActivity", - "PerformanceMeasurementActivity" -] diff --git a/platform/android/scripts/generate-license.py b/platform/android/scripts/generate-license.py deleted file mode 100644 index 9e59cb418..000000000 --- a/platform/android/scripts/generate-license.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/python - -import os -import json - -path = os.getcwd() + "/platform/android/" -with open(path + "LICENSE.md", 'w') as licenseFile: - licenseFile.write(" \n") - licenseFile.write("## Additional Mapbox GL licenses \n") - with open(path + "MapboxGLAndroidSDK/build/reports/licenses/licenseReleaseReport.json", 'r') as dataFile: - data = json.load(dataFile) - - gradleLicensePlugin =""" - { - "project": "Gradle License Plugin", - "url": "https://github.com/jaredsburrows/gradle-license-plugin", - "licenses": [ - { - "license": "The Apache Software License, Version 2.0", - "license_url": "http://www.apache.org/licenses/LICENSE-2.0.txt" - } - ] - } - """ - data.append(json.loads(gradleLicensePlugin)) - - licenseName = "" - licenseUrl = "" - for entry in data: - projectName = entry["project"] - projectUrl = entry["url"] - for license in entry["licenses"]: - licenseName = license["license"] - licenseUrl = license["license_url"] - - licenseFile.write("Mapbox GL uses portions of the %s. \n" % projectName + - ("URL: [%s](%s) \n" % (projectUrl, projectUrl) if projectUrl is not None else "") + - "License: [%s](%s)" % (licenseName, licenseUrl) + - "\n\n===========================================================================\n\n") diff --git a/platform/android/scripts/generate-style-code.js b/platform/android/scripts/generate-style-code.js deleted file mode 100755 index 3265c161e..000000000 --- a/platform/android/scripts/generate-style-code.js +++ /dev/null @@ -1,400 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -const fs = require('fs'); -const ejs = require('ejs'); -const spec = require('../../../scripts/style-spec'); -const _ = require('lodash'); - -// FIXME: https://github.com/mapbox/mapbox-gl-native/issues/15008 -delete spec.layout_circle["circle-sort-key"] -delete spec.layout_line["line-sort-key"] -delete spec.layout_fill["fill-sort-key"] - -require('../../../scripts/style-code'); - -// Specification parsing // -const lightProperties = Object.keys(spec[`light`]).reduce((memo, name) => { - var property = spec[`light`][name]; - property.name = name; - property['light-property'] = true; - property.doc = property.doc.replace(/°/g,'°'); - memo.push(property); - return memo; -}, []); - -// Collect layer types from spec -var layers = Object.keys(spec.layer.type.values).map((type) => { - const layoutProperties = Object.keys(spec[`layout_${type}`]).reduce((memo, name) => { - if (name !== 'visibility') { - spec[`layout_${type}`][name].name = name; - memo.push(spec[`layout_${type}`][name]); - } - return memo; - }, []); - - const paintProperties = Object.keys(spec[`paint_${type}`]).reduce((memo, name) => { - spec[`paint_${type}`][name].name = name; - memo.push(spec[`paint_${type}`][name]); - return memo; - }, []); - - return { - type: type, - doc: spec.layer.type.values[type].doc, - layoutProperties: layoutProperties, - paintProperties: paintProperties, - properties: layoutProperties.concat(paintProperties) - }; -}); - -// Process all layer properties -const uniqueArrayEnum = (prop, enums) => { - if (prop.value !== 'enum') return false; - const enumsEqual = (val1, val2) => val1.length === val1.length && val1.every((val, i) => val === val2[i]); - return enums.filter(e => enumsEqual(Object.keys(prop.values).sort(), Object.keys(e.values).sort())).length == 0; -}; - -const layoutProperties = _(layers).map('layoutProperties').flatten().value(); -const paintProperties = _(layers).map('paintProperties').flatten().value(); -const allProperties = _(layoutProperties).union(paintProperties).union(lightProperties).value(); -let allEnumProperties = _(allProperties).filter({'type': 'enum'}).value(); -const uniqueArrayEnumProperties = _(allProperties).filter({'type': 'array'}).filter(prop => uniqueArrayEnum(prop, allEnumProperties)).value(); -const enumProperties = _(allEnumProperties).union(uniqueArrayEnumProperties).value(); - - -global.propertyType = function propertyType(property) { - switch (property.type) { - case 'boolean': - return 'Boolean'; - case 'number': - return 'Float'; - case 'formatted': - return 'Formatted'; - case 'string': - case 'resolvedImage': - return 'String'; - case 'enum': - return 'String'; - case 'color': - return 'String'; - case 'array': - return `${propertyType({type:property.value})}[]`; - default: - throw new Error(`unknown type for ${property.name}`); - } -} - -global.propertyJavaType = function propertyType(property) { - switch (property.type) { - case 'boolean': - return 'boolean'; - case 'number': - return 'float'; - case 'formatted': - return 'Formatted'; - case 'string': - case 'resolvedImage': - return 'String'; - case 'enum': - return 'String'; - case 'color': - return 'String'; - case 'array': - return `${propertyJavaType({type:property.value})}[]`; - default: - throw new Error(`unknown type for ${property.name}`); - } - } - -global.propertyJNIType = function propertyJNIType(property) { - switch (property.type) { - case 'boolean': - return 'jboolean'; - case 'number': - return 'jfloat'; - case 'String': - return 'String'; - case 'enum': - return 'String'; - case 'color': - return 'String'; - case 'array': - return `jarray<${propertyType({type:property.value})}[]>`; - default: - return 'jobject*'; - } -} - -global.propertyNativeType = function (property) { - if (/-translate-anchor$/.test(property.name)) { - return 'TranslateAnchorType'; - } - if (/-(rotation|pitch|illumination)-alignment$/.test(property.name)) { - return 'AlignmentType'; - } - if (/^(text|icon)-anchor$/.test(property.name)) { - return 'SymbolAnchorType'; - } - switch (property.type) { - case 'boolean': - return 'bool'; - case 'number': - return 'float'; - case 'formatted': - case 'string': - case 'resolvedImage': // TODO: replace once we implement image expressions - return 'std::string'; - case 'enum': - if(property['light-property']){ - return `Light${camelize(property.name)}Type`; - } - return `${camelize(property.name)}Type`; - case 'color': - return `Color`; - case 'array': - if (property.length) { - return `std::array<${propertyType({type: property.value})}, ${property.length}>`; - } else { - return `std::vector<${propertyType({type: property.value})}>`; - } - default: throw new Error(`unknown type for ${property.name}`) - } -} - -global.propertyTypeAnnotation = function propertyTypeAnnotation(property) { - switch (property.type) { - case 'enum': - return `@Property.${snakeCaseUpper(property.name)}`; - default: - return ""; - } -}; - -global.defaultExpressionJava = function(property) { - switch (property.type) { - case 'boolean': - return 'boolean'; - case 'number': - return 'number'; - case 'formatted': - return 'format'; - case 'resolvedImage': - return "image"; - case 'string': - case 'enum': - return "string"; - case 'color': - return 'toColor'; - case 'array': - return "array"; - default: return "string"; - } -} - -global.defaultValueJava = function(property) { - if(property.name.endsWith("-pattern")) { - return '"pedestrian-polygon"'; - } - if(property.name.endsWith("-font")) { - return 'new String[]{"Open Sans Regular", "Arial Unicode MS Regular"}'; - } - switch (property.type) { - case 'boolean': - return 'true'; - case 'number': - return '0.3f'; - case 'formatted': - return 'new Formatted(new FormattedSection("default"))' - case 'string': - case 'resolvedImage': - return '"' + property['default'] + '"'; - case 'enum': - return snakeCaseUpper(property.name) + "_" + snakeCaseUpper(Object.keys(property.values)[0]); - case 'color': - return '"rgba(255,128,0,0.7)"'; - case 'array': - switch (property.value) { - case 'string': - case 'enum': - if (property['default'] !== undefined) { - return '[' + property['default'] + ']'; - } else { - return 'new String[0]'; - } - case 'number': - var result ='new Float[] {'; - for (var i = 0; i < property.length; i++) { - result += "0f"; - if (i +1 != property.length) { - result += ", "; - } - } - return result + "}"; - } - default: throw new Error(`unknown type for ${property.name}`) - } -} - -/** - * Produces documentation for property factory methods - */ -global.propertyFactoryMethodDoc = function (property) { - var replaceIfPixels = function (doc) { - return doc.replace('pixels', 'density-independent pixels') - } - let doc = replaceIfPixels(property.doc); - // Match other items in back ticks - doc = doc.replace(/`(.+?)`/g, function (m, symbol, offset, str) { - if (str.substr(offset - 4, 3) !== 'CSS' && symbol[0].toUpperCase() != symbol[0] && _(enumProperties).filter({'name': symbol}).value().length > 0) { - // Property 'enums' - symbol = snakeCaseUpper(symbol); - return '{@link Property.' + symbol + '}'; - } else if( _(allProperties).filter({'name': symbol}).value().length > 0) { - // Other properties - return '{@link PropertyFactory#' + camelizeWithLeadingLowercase(symbol) + '}'; - } else { - // Left overs - return '`' + symbol + '`'; - } - }); - return doc; -}; - -/** - * Produces documentation for property value constants - */ -global.propertyValueDoc = function (property, value) { - - // Match references to other property names & values. - // Requires the format 'When `foo` is set to `bar`,'. - let doc = property.values[value].doc.replace(/When `(.+?)` is set to `(.+?)`(?: or `([^`]+?)`)?,/g, function (m, peerPropertyName, propertyValue, secondPropertyValue, offset, str) { - let otherProperty = snakeCaseUpper(peerPropertyName); - let otherValue = snakeCaseUpper(peerPropertyName) + '_' + snakeCaseUpper(propertyValue); - const firstPropertyValue = 'When {@link ' + `${otherProperty}` + '} is set to {@link Property#' + `${otherValue}` + '}'; - if (secondPropertyValue) { - return firstPropertyValue + ` or {@link Property#${snakeCaseUpper(peerPropertyName) + '_' + snakeCaseUpper(secondPropertyValue)}},`; - } else { - return firstPropertyValue + ','; - } - }); - - // Match references to our own property values. - // Requires the format 'is equivalent to `bar`'. - doc = doc.replace(/is equivalent to `(.+?)`/g, function(m, propertyValue, offset, str) { - propertyValue = snakeCaseUpper(property.name) + '_' + snakeCaseUpper(propertyValue); - return 'is equivalent to {@link Property#' + propertyValue + '}'; - }); - - // Match other items in back ticks - doc = doc.replace(/`(.+?)`/g, function (m, symbol, offset, str) { - if ('values' in property && Object.keys(property.values).indexOf(symbol) !== -1) { - // Property values - propertyValue = snakeCaseUpper(property.name) + '_' + snakeCaseUpper(symbol); - console.log("Transforming", symbol, propertyValue); - return '{@link Property#' + `${propertyValue}` + '}'; - } else if (str.substr(offset - 4, 3) !== 'CSS' && symbol[0].toUpperCase() != symbol[0]) { - // Property 'enums' - if (symbol === 'symbol-sort-key') { - return 'symbol sort key'; - } - - symbol = snakeCaseUpper(symbol); - return '{@link ' + symbol + '}'; - } else { - // Left overs - return symbol - } - }); - return doc; -}; - -global.isLightProperty = function (property) { - return property['light-property'] === true; -}; - -global.propertyValueType = function (property) { - switch (property['property-type']) { - default: - return `PropertyValue<${evaluatedType(property)}>`; - } -}; - -global.evaluatedType = function (property) { - if (/-translate-anchor$/.test(property.name)) { - return 'TranslateAnchorType'; - } - if (/-(rotation|pitch|illumination)-alignment$/.test(property.name)) { - return 'AlignmentType'; - } - if (/^(text|icon)-anchor$/.test(property.name)) { - return 'SymbolAnchorType'; - } - if (/position/.test(property.name)) { - return 'Position'; - } - switch (property.type) { - case 'boolean': - return 'bool'; - case 'number': - return 'float'; - case 'formatted': - case 'string': - case 'image': - return 'std::string'; - case 'enum': - return (isLightProperty(property) ? 'Light' : '') + `${camelize(property.name)}Type`; - case 'color': - return `Color`; - case 'array': - if (property.length) { - return `std::array<${evaluatedType({type: property.value})}, ${property.length}>`; - } else { - return `std::vector<${evaluatedType({type: property.value})}>`; - } - default: throw new Error(`unknown type for ${property.name}`) - } -}; - -global.supportsZoomFunction = function (property) { - return property.expression && property.expression.parameters.indexOf('zoom') > -1; -}; - -global.supportsPropertyFunction = function (property) { - return property['property-type'] === 'data-driven' || property['property-type'] === 'cross-faded-data-driven'; -}; - -// Template processing // - -// Java + JNI Light (Peer model) -const lightJava = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/light.java.ejs', 'utf8'), {strict: true}); -const lightJavaUnitTests = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/style/light.junit.ejs', 'utf8'), {strict: true}); -writeIfModified(`platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/light/Light.java`, lightJava({properties: lightProperties})); -writeIfModified(`platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/style/LightTest.java`, lightJavaUnitTests({properties: lightProperties})); - -// Java + JNI Layers (Peer model) -const layerHpp = ejs.compile(fs.readFileSync('platform/android/src/style/layers/layer.hpp.ejs', 'utf8'), {strict: true}); -const layerCpp = ejs.compile(fs.readFileSync('platform/android/src/style/layers/layer.cpp.ejs', 'utf8'), {strict: true}); -const layerJava = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/layer.java.ejs', 'utf8'), {strict: true}); -const layerJavaUnitTests = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/style/layer.junit.ejs', 'utf8'), {strict: true}); - -for (const layer of layers) { - writeIfModified(`platform/android/src/style/layers/${layer.type.replace('-', '_')}_layer.hpp`, layerHpp(layer)); - writeIfModified(`platform/android/src/style/layers/${layer.type.replace('-', '_')}_layer.cpp`, layerCpp(layer)); - writeIfModified(`platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/${camelize(layer.type)}Layer.java`, layerJava(layer)); - writeIfModified(`platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/style/${camelize(layer.type)}LayerTest.java`, layerJavaUnitTests(layer)); -} - -// Java PropertyFactory -const propertiesTemplate = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property_factory.java.ejs', 'utf8'), {strict: true}); -writeIfModified( - `platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/PropertyFactory.java`, - propertiesTemplate({layoutProperties: layoutProperties, paintProperties: paintProperties}) -); - -// Java Property -const enumPropertyJavaTemplate = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/property.java.ejs', 'utf8'), {strict: true}); -writeIfModified( - `platform/android/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/style/layers/Property.java`, - enumPropertyJavaTemplate({properties: enumProperties}) -); diff --git a/platform/android/scripts/generate-test-code.js b/platform/android/scripts/generate-test-code.js deleted file mode 100644 index 64b38e5ac..000000000 --- a/platform/android/scripts/generate-test-code.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const ejs = require('ejs'); - -global.iff = function (condition, val) { - return condition() ? val : ""; -} - -global.camelize = function (str) { - return str.replace(/(?:^|-)(.)/g, function (_, x) { - return x.toUpperCase(); - }); -} - -const excludeClasses = JSON.parse(fs.readFileSync('platform/android/scripts/exclude-activity-gen.json', 'utf8')); -const appBasePath = 'platform/android/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxsdk/testapp/activity'; -const testBasePath = 'platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/activity/gen'; -const subPackages = fs.readdirSync(appBasePath); -const ejsConversionTask = ejs.compile(fs.readFileSync('platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/testapp/activity/activity.junit.ejs', 'utf8'), {strict: true}); - -if (!fs.existsSync(testBasePath)){ - fs.mkdirSync(testBasePath); -} - -console.log("\nGenerating test activities:\n"); -var generatedClasses = []; -var excludedClasses = []; -for(const subPackage of subPackages) { - if(!(subPackage.slice(-5) == '.java')) { - const activities = fs.readdirSync(appBasePath+'/'+subPackage); - - // create directories for package - if (!fs.existsSync(testBasePath+"/"+subPackage)){ - fs.mkdirSync(testBasePath+"/"+subPackage); - } - - for (const activity of activities) { - var activityName; - if (activity.slice(-5) === '.java') { - // .java file - activityName = activity.slice(0, -5); - } else { - // .kt file - activityName = activity.slice(0, -3); - } - - // create path for test file - const filePath = testBasePath+"/"+subPackage+"/"+activityName+'Test.java'; - - // try removing previous generated files - try { - fs.accessSync(filePath, fs.F_OK); - fs.unlinkSync(filePath); - } catch (e) { - } - - // only generate test file if not part of exclude list + if contains Activity in name - if ((!(excludeClasses.indexOf(activityName) > -1)) && activityName.includes("Activity")) { - fs.writeFileSync(filePath, ejsConversionTask([activityName, subPackage])); - generatedClasses.push(activityName); - }else{ - excludedClasses.push(activityName); - } - } - } -} - -for(const generatedClass of generatedClasses){ - console.log(generatedClass+"Test"); -} - -console.log("\nFinished generating " + generatedClasses.length + " activity sanity tests, excluded " + excludeClasses.length + " classes.\n"); \ No newline at end of file diff --git a/platform/android/scripts/metrics.sh b/platform/android/scripts/metrics.sh deleted file mode 100755 index cc33daf17..000000000 --- a/platform/android/scripts/metrics.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -o pipefail - -# Track individual architectures -scripts/check_binary_size.js "platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/release/jni/armeabi-v7a/libmapbox-gl.so" "Android arm-v7" -scripts/check_binary_size.js "platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/release/jni/arm64-v8a/libmapbox-gl.so" "Android arm-v8" -scripts/check_binary_size.js "platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/release/jni/x86/libmapbox-gl.so" "Android x86" -scripts/check_binary_size.js "platform/android/MapboxGLAndroidSDK/build/intermediates/intermediate-jars/release/jni/x86_64/libmapbox-gl.so" "Android x86_64" - -# Track overall library size -scripts/check_binary_size.js "platform/android/MapboxGLAndroidSDK/build/outputs/aar/MapboxGLAndroidSDK-release.aar" "Android AAR" - -if [[ $CIRCLE_BRANCH == master ]]; then - # Build source data for http://mapbox.github.io/mapbox-gl-native/metrics/binary-size/ - # and log binary sizes to metrics warehouse - scripts/publish_binary_size.js -fi diff --git a/platform/android/scripts/parse-jacoco-report.py b/platform/android/scripts/parse-jacoco-report.py deleted file mode 100755 index 4d06fda6c..000000000 --- a/platform/android/scripts/parse-jacoco-report.py +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/python - -import os -import re -from io import open - -reportPath = os.getcwd() + "/platform/android/MapboxGLAndroidSDK/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml" -with open(reportPath, 'r', encoding='utf-8') as jacocoReport: - line = jacocoReport.readline().strip() - - # find the last INSTRUCTION coverage report which is a sum of all separate ones - instructionIndex = line.rfind('type="INSTRUCTION"') - startIndex = line.find('missed', instructionIndex) - endIndex = line.find('/>', startIndex) - - # find the missed and covered lines counts - numbers = re.match(r'missed="(\d+)" covered="(\d+)"', line[startIndex:endIndex]) - missed = int(numbers.group(1)) - covered = int(numbers.group(2)) - - # calculate the code coverage percentage - percentage = round(covered * 100.0 / (missed + covered), 2) - print("Android tests code coverage: %s%%" % (str(percentage))) - - # invoke the script that send the data to s3 - testEnvironment = "LOCAL" - if os.environ.get('IS_LOCAL_DEVELOPMENT').lower()=='false': - testEnvironment = "CI" - - cmd = os.getcwd() + ("/scripts/code-coverage.sh %.2f %s %s" % (percentage, "Android", testEnvironment)) - os.system(cmd) diff --git a/platform/android/scripts/release.py b/platform/android/scripts/release.py deleted file mode 100644 index d0abd1eea..000000000 --- a/platform/android/scripts/release.py +++ /dev/null @@ -1,236 +0,0 @@ -''' -Utility to schedule SDK builds on CircleCI. - -Examples: - -- Publish a snapshot from master (release.py uses the current branch) - - $ git branch - * master - 1234-fix-crash - $ python release.py --stage snapshot - -- Publish a snapshot from a feature branch (same as before, just switch branchs with git): - - $ git branch - master - * 1234-fix-crash - $ python release.py --stage snapshot - -- Publish a beta from a pre-release branch: - - $ git branch - master - * release-android-420-beta1 - $ python release.py --stage beta --version 4.2.0-beta.1 - -- Publish a beta from a release branch: - - $ git branch - master - * release-android-420 - $ python release.py --stage final --version 4.2.0 - -TODO: - -- Add a flag to wait until the release has been built (CircleCI) and published (Maven). - -''' - -import click -import json -import os -import requests -import subprocess - -# Three stages, from less stable to more stable -ALLOWED_STAGES = ['snapshot', 'beta', 'final'] - -# Get the version from GRADLE_PROPERTIES_PATH below -CURRENT_VERSION_TAG = 'current' - -# You can add your API token on https://circleci.com/account/api -CIRCLECI_API_TOKEN_ENV_VAR = 'CIRCLECI_API_TOKEN' - -# In the future we might want to consider alpha, or rc. -ALLOWED_PRE_RELEASE = ['beta'] - -# We get the default version from here -MAPBOX_GL_ANDROID_SDK_PATH = '../MapboxGLAndroidSDK' -GRADLE_PROPERTIES_PATH = '%s/gradle.properties' % MAPBOX_GL_ANDROID_SDK_PATH -GRADLE_TOKEN = 'VERSION_NAME=' - -# Triggers a new build, returns a summary of the build -URL_CIRCLECI = 'https://circleci.com/api/v1.1/project/github/mapbox/mapbox-gl-native/tree/' # + :branch - -# We support three parameters: stage, branch, and version -@click.command() -@click.option('--stage', default=ALLOWED_STAGES[0], type=click.Choice(ALLOWED_STAGES), prompt='Set stage', help='The release stage.') -@click.option('--version', default=CURRENT_VERSION_TAG, prompt='Set version', help='The version you want to publish. E.g: 4.2.0-SNAPSHOT, 4.2.0-beta.1, or 4.2.0. If you set the version to "%s", the script will default to the current SNAPSHOT version.' % CURRENT_VERSION_TAG) -def release(stage, version): - # Validate params - final_stage = validate_stage(stage=stage) - final_branch = validate_branch(stage=final_stage) - final_version = validate_version(stage=final_stage, branch=final_branch, version=version) - - # Get user confirmation - click.echo('\n===== Build information =====') - click.echo('- Stage: %s' % final_stage) - click.echo('- Branch: %s' % final_branch) - click.echo('- Version: %s' % final_version) - click.confirm('\nDoes it look right?', abort=True) - - # Proceed - if (final_stage == 'snapshot'): - publish_snapshot(branch=final_branch, version=final_version) - elif (final_stage == 'beta'): - publish_beta(branch=final_branch, version=final_version) - elif (final_stage == 'final'): - publish_final(branch=final_branch, version=final_version) - -def validate_stage(stage): - if stage not in ALLOWED_STAGES: - abort_with_message('Invalid stage: %s' % stage) - return stage - -def validate_branch(stage): - branch = git_get_current_branch() - if not branch: - abort_with_message('The current folder is not a git repository.') - if branch == 'master' and stage != 'snapshot': - abort_with_message('You need to swtich to a release branch for a beta or a final release.') - return branch - -def validate_version(stage, branch, version): - if stage == 'snapshot' and branch == 'master' and version != CURRENT_VERSION_TAG: - abort_with_message('You cannot specify a custom version if you are building a snapshot from master.') - - if not version or version == CURRENT_VERSION_TAG: - version = get_current_version(file_path=GRADLE_PROPERTIES_PATH, file_var=GRADLE_TOKEN) - - if stage == 'snapshot': - if not 'SNAPSHOT' in version: - abort_with_message('Version should contain the word SNAPSHOT: %s' % version) - elif stage == 'beta': - if not ALLOWED_PRE_RELEASE[0] in version: - abort_with_message('Version should contain the word %s: %s' % (ALLOWED_PRE_RELEASE[0], version)) - elif stage == 'final': - if not version or 'SNAPSHOT' in version or ALLOWED_PRE_RELEASE[0] in version: - abort_with_message('Version cannot be empty, or contain the words SNAPSHOT or %s: %s' % (ALLOWED_PRE_RELEASE[0], version)) - - return version - -def publish_snapshot(branch, version): - click.echo('Publishing snapshot for branch: %s (version: %s).' % (branch, version)) - if branch != 'master': - dirty_gradle = update_current_version(file_path=GRADLE_PROPERTIES_PATH, file_var=GRADLE_TOKEN, version=version) - if dirty_gradle: - git_add(path=GRADLE_PROPERTIES_PATH) - git_commit_and_push(branch=branch, version=version) - do_circleci_request(branch=branch) - -def publish_beta(branch, version): - click.echo('Publishing beta from branch: %s (version: %s).' % (branch, version)) - dirty_gradle = update_current_version(file_path=GRADLE_PROPERTIES_PATH, file_var=GRADLE_TOKEN, version=version) - if dirty_gradle: - git_add(path=GRADLE_PROPERTIES_PATH) - git_commit_and_push(branch=branch, version=version) - do_circleci_request(branch=branch) - -def publish_final(branch, version): - click.echo('Publishing final release from branch: %s (version: %s).' % (branch, version)) - dirty_gradle = update_current_version(file_path=GRADLE_PROPERTIES_PATH, file_var=GRADLE_TOKEN, version=version) - if dirty_gradle: - git_add(path=GRADLE_PROPERTIES_PATH) - if dirty_gradle: - git_commit_and_push(branch=branch, version=version) - do_circleci_request(branch=branch) - -# -# Utils -# - -def abort_with_message(message): - click.echo(message) - click.get_current_context().abort() - -def execute_call(command): - click.echo('Executing: %s' % command) - result = subprocess.call(command, shell=True) - if result != 0: - abort_with_message('Command failed: %s' % command) - -# -# CircleCI -# - -def get_circleci_api_token(): - circleci_api_token = os.environ.get(CIRCLECI_API_TOKEN_ENV_VAR) - if not circleci_api_token: - abort_with_message('You need to set the CIRCLECI_API_TOKEN environment variable.') - click.echo('Found CircleCI API token.') - return circleci_api_token - -def do_circleci_request(branch): - url = URL_CIRCLECI + branch - params = {'circle-token': get_circleci_api_token()} - click.echo('CircleCI request to %s (params: %s)' % (url, json.dumps(params))) - click.confirm('\nDo you want to start a build?', abort=True) - - r = requests.post(url, params=params) - click.echo('- CircleCI response code: %s' % r.status_code) - -# -# Git -# - -def git_get_current_branch(): - return subprocess.check_output('git symbolic-ref --short HEAD'.split(' ')).strip() - -def git_add(path): - execute_call(command='git add %s' % path) - -def git_commit_and_push(branch, version): - message = '[android] [auto] Update properties to version %s in preparation for build.' % version - commands = [ - 'git commit -m "%s"' % message, - 'git push -u origin %s' % branch] - for command in commands: - execute_call(command=command) - -# -# Read and update properties files -# - -def get_current_version(file_path, file_var): - click.echo('Getting current version from %s.' % file_path) - with open(file_path, 'r') as f: - for line in f: - if line.startswith(file_var): - version_name = line[len(file_var):].strip() - click.echo('Current version is %s.' % version_name) - return version_name - return None - -def update_current_version(file_path, file_var, version): - dirty = False - click.echo('Updating file to version %s: %s.' % (version, file_path)) - with open(file_path, 'r') as f: - file_lines = f.readlines() - for line_number in range(len(file_lines)): - if file_lines[line_number].startswith(file_var): - content_old = file_lines[line_number] - content_new = '%s%s\n' % (file_var, version) - if (content_old != content_new): - click.echo('%s -> %s' % (content_old.strip(), content_new.strip())) - file_lines[line_number] = content_new - dirty = True - if dirty: - with open(file_path, 'w') as f: - f.writelines(file_lines) - else: - click.echo('File already has the right version.') - return dirty - -if __name__ == '__main__': - release() diff --git a/platform/android/scripts/run-render-test.py b/platform/android/scripts/run-render-test.py deleted file mode 100644 index 940ae7a3d..000000000 --- a/platform/android/scripts/run-render-test.py +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/python - -import os -import shutil - -catPath = os.getcwd() + "/platform/android/build/render-test/" -failCounter = 0 -testCounter = 0 -for cat in os.listdir(catPath): - testPath = catPath + cat + "/" - for test in os.listdir(testPath): - inputPath = os.getcwd() + "/mapbox-gl-js/test/integration/render-tests/" + cat + "/" + test - outputPath = testPath + test - - expected = outputPath + "/expected.png" - actual = outputPath + "/actual.png" - output = outputPath + "/output.png" - - shutil.copyfile(inputPath + "/expected.png", expected) - shutil.copyfile(inputPath + "/style.json", outputPath + "/style.json") - pixelmatchCommand = "node_modules/pixelmatch/bin/pixelmatch " + actual + " " + expected + " " + output + " 0.1" - - print "Pixel match " + cat + " " + test - - with os.popen(pixelmatchCommand) as f: - for line_terminated in f: - line = line_terminated.rstrip('\n') - pair = line.split(": ") - if pair[0] == "error": - testCounter += 1 - currentError = pair[1] - if currentError != "0%": - failCounter += 1 - # below deletes successful results - # print cat + " " + test + " " + currentError - # else: - # try: - # if os.path.isdir(outputPath): - # shutil.rmtree(outputPath) - # except OSError, e: - # print ("Error: %s - %s." % (e.filename, e.strerror)) -print -print str(failCounter) + "/" + str(testCounter) diff --git a/platform/android/scripts/validate-license.py b/platform/android/scripts/validate-license.py deleted file mode 100644 index 1c9a153b8..000000000 --- a/platform/android/scripts/validate-license.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/python - -from subprocess import call -from subprocess import Popen, PIPE -import sys - -## Run license generation -call('cd ../../ && make android-license', shell=True) - -## Git diff changes -p = Popen(['git', 'diff', '--name-only', 'LICENSE.md'], stdin=PIPE, stdout=PIPE, stderr=PIPE) -output, err = p.communicate(b"input data that is passed to subprocess' stdin") -if b"platform/android/LICENSE.md" in output: - raise ValueError("""An error ocurred while validating the license generation. - Changes were detected to the license generation output - but weren't commited. Run make android-license and - commit the changeset to make this validation pass.""") \ No newline at end of file diff --git a/platform/android/settings.gradle b/platform/android/settings.gradle deleted file mode 100644 index c0315fed0..000000000 --- a/platform/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -include ':MapboxGLAndroidSDK', ':MapboxGLAndroidSDKTestApp', ':MapboxGLAndroidSDKLint' \ No newline at end of file diff --git a/platform/android/tests/README.md b/platform/android/tests/README.md deleted file mode 100644 index 0d1eb7dea..000000000 --- a/platform/android/tests/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Mapbox GL Android Test documentation - -## Testing -We currently support the following types of testing on the Mapbox Maps SDK for Android: - - - [Unit tests](docs/UNIT_TESTS.md) using [JUnit](http://developer.android.com/tools/testing-support-library/index.html#AndroidJUnitRunner) - - [UI tests](docs/UI_TESTS.md) using [Espresso](http://developer.android.com/tools/testing-support-library/index.html#Espresso) - - [Exerciser](docs/EXERCISER_TESTS.md) tests using [Monkey](http://developer.android.com/tools/help/monkey.html) or [Build-in Fuzz test](http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-built-in-fuzz.html) - - [Performance tests](docs/PERFORMANCE_TESTS.md) using [Systrace](https://codelabs.developers.google.com/codelabs/android-perf-testing/index.html?index=..%2F..%2Fbabbq-2015&viewga=UA-68632703-1#0) - - [Core tests](docs/CORE_TESTS.md) using [Google Test](https://github.com/google/googletest) to run the unit tests written for the core rendering component of Mapbox GL \ No newline at end of file diff --git a/platform/android/tests/docs/ACTIVITY_SANITY_TEST.md b/platform/android/tests/docs/ACTIVITY_SANITY_TEST.md deleted file mode 100644 index 7422599c3..000000000 --- a/platform/android/tests/docs/ACTIVITY_SANITY_TEST.md +++ /dev/null @@ -1,17 +0,0 @@ -# Activity Sanity Tests - -This type of test checks if an Activity doesn't crash at start up. For this project this type of test is usefull since a lot of core crashes occurs at this point and are ideal to test regressions. The only run for 1 sec each so there are fast and fairly reliable. We are currently generating the test stack from every Activity found in the following package: - -> com.mapbox.mapboxsdk.testapp - -The generation is done by executing: - -> make test-code-android - -This command underneath executes the following js file found in: - -> node scripts/android-generate-test - -and uses the following ejs file as a template. - ->platform/android/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxsdk/activity/activity.junit.ejs diff --git a/platform/android/tests/docs/CORE_TESTS.md b/platform/android/tests/docs/CORE_TESTS.md deleted file mode 100644 index b9cd7bcc7..000000000 --- a/platform/android/tests/docs/CORE_TESTS.md +++ /dev/null @@ -1,21 +0,0 @@ -# Core Tests - -Core tests run the [unit tests](../../../../test) written for the core rendering component of Mapbox GL. - -## Running the tests - -To run the tests, connect a device to your computer, or launch a virtual device. Then run - -``` -$ make run-android-core-test-XXX -``` - -with `XXX` being the architecture of the device (one of `arm-v5`, `arm-v7`, `arm-v8`, `x86`, `x86-64`, or `mips`). This command first builds the library, creates a test program, zips up the assets required for the unit tests, deploys it on the device, runs the test and unpacks the results again on your computer. - -You can also run individual tests by specifying the name like this: - -``` -$ make run-android-core-test-XXX-TileCover.* -``` - -Everything after the last dash is passed as the [`--gtest_filter` argument](https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#running-a-subset-of-the-tests) to the Google Test binary. diff --git a/platform/android/tests/docs/EXERCISER_TESTS.md b/platform/android/tests/docs/EXERCISER_TESTS.md deleted file mode 100644 index 4de56912a..000000000 --- a/platform/android/tests/docs/EXERCISER_TESTS.md +++ /dev/null @@ -1,23 +0,0 @@ -#UI/Application Exerciser Tests - -UI/application exerciser tests are stress test using random generated users events. - -##Running Locally - -The Android SDK provides a test tool called [Monkey](http://developer.android.com/tools/help/monkey.html), -"a program that runs on your emulator or device and generates pseudo-random streams of user events -such as clicks, touches, or gestures, as well as a number of system-level events." - -To exercise Monkey on the test app, install the package on the device (e.g. via Android Studio) -and then: - -``` -$ adb shell monkey -p com.mapbox.mapboxgl.testapp -v 500 -``` - -##Running on AWS Device Farm - -Amazon Device farm supports a similar tool called `Built-in Fuzz Test`. -"The built-in fuzz test randomly sends user interface events to devices and then reports results." - -More information about [Built-in Fuzz Test](http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-built-in-fuzz.html) \ No newline at end of file diff --git a/platform/android/tests/docs/PERFORMANCE_TESTS.md b/platform/android/tests/docs/PERFORMANCE_TESTS.md deleted file mode 100644 index a182af826..000000000 --- a/platform/android/tests/docs/PERFORMANCE_TESTS.md +++ /dev/null @@ -1,69 +0,0 @@ -# Performance Tests - -## What is Systrace? - -From the [Android documentation](http://developer.android.com/tools/help/systrace.html): -"Systrace is a tool that will help you analyze the performance of your application by capturing and displaying execution times of your applications processes and other Android system processes." - -## What are we using it for? - -We’re using Systrace to look for performance issues in our SDK. When we run Systrace while using our app, -it will collect data from Android then format it into an html file we can view in a web browser. -When we open the Systrace results, we’re hoping it will be able to help us resolve some of the -underlying issues associated with our SDK. - -## Run systrace locally - -Execute following command in your terminal will run Systrace for 10 seconds: - -``` -python $ANDROID_HOME/platform-tools/systrace/systrace.py --time=10 -o ~/trace.html gfx view res -``` - -This command will output a file called `trace.html`. -More information how to interpret the values can be found [here](http://developer.android.com/tools/help/systrace.html). - -More information about this topic can be found [here](https://codelabs.developers.google.com/codelabs/android-perf-testing/index.html?index=..%2F..%2Fbabbq-2015&viewga=UA-68632703-1#0) - -## Automating Systrace with Espresso - -The following annotation is being used to isolate the tests and classes that should be included in the performance tests. - -```java -@PerfTest -``` - -You can optionally define extra rules to gather more data during a performance test: - -```java -@Rule -public EnableTestTracing mEnableTestTracing = new EnableTestTracing(); - -@Rule -public EnablePostTestDumpsys mEnablePostTestDumpsys = new EnablePostTestDumpsys(); - -@Rule -public EnableLogcatDump mEnableLogcatDump = new EnableLogcatDump(); - -@Rule -public EnableNetStatsDump mEnableNetStatsDump = new EnableNetStatsDump(); -``` - -## Automating Systrace with MonkeyRunner - -An example of such a script can be found [here](https://github.com/googlecodelabs/android-perf-testing/blob/master/run_perf_tests.py). -The script is following this structure: - -- Check environment variables -- Define functions -- Clear local data from previous runs -- Find an Android device -- Enable and clear graphics info dumpsys -- Start a systrace thread & test suite thread in parallel -- Wait for both threads to complete -- Download files from device -- Run analysis on downloaded files - -## Note -Testing on a device with minimum SDK 6.0 is preferred. -The tools above work on older versions of Android, but less data will be collected. \ No newline at end of file diff --git a/platform/android/tests/docs/UI_TESTS.md b/platform/android/tests/docs/UI_TESTS.md deleted file mode 100644 index 1014b5684..000000000 --- a/platform/android/tests/docs/UI_TESTS.md +++ /dev/null @@ -1,67 +0,0 @@ -#UI Tests -## Running Espresso tests locally - -This test project comes with all the required Android Testing Support Library dependencies -in the Gradle file. Tests are under the `app/src/androidTest` folder. - -Note that before running your tests, you might want to turn off animations on your test device. -It's a known issue that leaving system animations turned on in a test device -(window animation scale, transition animation scale, animator duration scale) -might cause unexpected results, or may lead tests to fail. - -To create a new run configuration: -* Click on Run -> Edit Configurations... -* Click on the plus sign and then on "Android Tests" -* Give a name to the configuration, e.g. `TestAppTests` -* Choose the `MapboxGLAndroidSDKTestApp` module -* Choose `android.support.test.runner.AndroidJUnitRunner` as the instrumentation runner -* Click OK to save the new configuration - -You can now run this configuration from the main toolbar dropdown menu. - -## Running Espresso tests on AWS Device Farm - -On a terminal, within `mapbox-gl-native/android/java`, -run the tests (`cC` stands for `connectedCheck`): - -``` -$ ./gradlew -Pmapbox.abis=all cC -p MapboxGLAndroidSDKTestApp -``` - -Then: -* Go to your AWS Console and choose Device Farm. -* Create a new project, e.g. `MapboxGLAndroidSDKTestApp` -* On step 1, upload the APK in `mapbox-gl-native/platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-unaligned.apk` -* On step 2, choose Instrumentation, test filter is `com.mapbox.mapboxgl.testapp.MainActivityTest` and upload the APK in `mapbox-gl-native/platform/android/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-androidTest-unaligned.apk` -* On step 3, choose a device pool. E.g. Top Devices -* On step 4, customize your device state (if needed) -* Finally, confirm the configuration and run the tests. - -On Step 2, you can also separate by commas different classes: `com.mapbox.mapboxgl.testapp.MainActivityTest,com.mapbox.mapboxgl.testapp.MainActivityScreenTest` - -If you have no tests for your app, or want to test some random user behavior, -you can just choose "Built-in: Fuzz" in step 2. - -### Code coverage -You can generate JaCoCo reports from espresso tests by - -- adding this to build.gradle: - - ```java - buildTypes { - debug { - // Run code coverage reports by default on debug builds. - testCoverageEnabled = true - } -} -``` - -- running the gradle task `createMockDebugCoverageReport` when executing tests. - -## Running Espresso test automatically on AWS Device Farm -To run tests on AWS device farm you need to execute `./gradlew -Pmapbox.abis=none devicefarmUpload`. -You can configure the different steps in the testapp `build.gradle`. -AWS credentials are found in CircleCI. - - - diff --git a/platform/android/tests/docs/UNIT_TESTS.md b/platform/android/tests/docs/UNIT_TESTS.md deleted file mode 100644 index 458e8869f..000000000 --- a/platform/android/tests/docs/UNIT_TESTS.md +++ /dev/null @@ -1,92 +0,0 @@ -# Unit tests -**Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation.** - -Our Unit tests are based on JUnit and are located under `/src/test/java/`. -We are using plain JUnit to test classes that aren't calling the Android API, -or are using Android's JUnit extensions to stub/mock Android components. - -## Writing unit tests -Unit tests for an Android project are located in the `test` folder: - -screen shot 2016-03-16 at 17 24 31 - -To add a test, right click the corresponding package and select create new `Java class`. Name the class appropriately by ending it with `Test` and start adding test methods by applying the `@Test` annotation: - -```java -package com.mapbox.mapboxsdk.annotations; - -import org.junit.Test; - -public class AwesomeSauceTest { - - @Test - public void simpleTest(){ - - } - -} - -``` - -you can add methods that are executed before and after each test: - -```java -package com.mapbox.mapboxsdk.annotations; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class AwesomeSauceTest { - - @Before - public void beforeEachTest(){ - - } - - @Test - public void simpleTest(){ - - } - - @After - public void afterEachTest(){ - - } - -} -``` - -## Running unit tests -You can run a test locally by right clicking and selecting run: - -screen shot 2016-03-16 at 17 46 09 - -If you like, you can also run with test coverage enabled. This will show you the following dialog: - -screen shot 2016-03-16 at 17 58 34 - -You can also run the tests from the command line with: - -``` -$ ./gradlew -Pmapbox.abis=none test -p MapboxGLAndroidSDKTestApp -``` - -## Running Unit tests on CI -The Unit tests are executed as part of the build process on our CI and are -automatically run for each new commit pushed to this repo. If a Unit tests -fails, this will fail and stop the build. - -You can find this gradle command in our [buildscript](https://github.com/mapbox/mapbox-gl-native/blob/master/circle.yml#L146-L215): - -``` -$ ./gradlew -Pmapbox.abis=none testReleaseUnitTest -``` - - -## Code Coverage -Showing code coverage directly in the IDE. -- Switch your Build Variant to the Unit Tests artifact -- Right click a unit test and select `Run test with coverage` -- Select `Add to active suites` //this will create a run configuration -- Edit the run configuration to include/exclude packages in the `Code coverage`-tab. diff --git a/platform/android/tests/skipped.txt b/platform/android/tests/skipped.txt deleted file mode 100644 index cf2865683..000000000 --- a/platform/android/tests/skipped.txt +++ /dev/null @@ -1,9 +0,0 @@ -# Flaky -# After map is rendered, main thread hangs in runloop::wake when data is written to pipe -# Issue: https://github.com/mapbox/mapbox-gl-native/issues/13711 -Memory.Raster -Memory.Vector - -# Exception is thrown when network status is changed to online -# Issue: https://github.com/mapbox/mapbox-gl-native/issues/13711 -Map.Offline diff --git a/platform/android/vendor/mapbox-events-android b/platform/android/vendor/mapbox-events-android deleted file mode 160000 index 58fbec16c..000000000 --- a/platform/android/vendor/mapbox-events-android +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 58fbec16cdedb909eb63c68e46708fe9268b6fed diff --git a/platform/android/vendor/mapbox-gestures-android b/platform/android/vendor/mapbox-gestures-android deleted file mode 160000 index ae08de82c..000000000 --- a/platform/android/vendor/mapbox-gestures-android +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ae08de82ca178dca7f005dfc8056554cf77124ad diff --git a/platform/android/vendor/mapbox-java b/platform/android/vendor/mapbox-java deleted file mode 160000 index f590c74df..000000000 --- a/platform/android/vendor/mapbox-java +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f590c74df50f1b1e8edf2a4cf4908701b85861f2 diff --git a/platform/android/version-script b/platform/android/version-script deleted file mode 100644 index 7c1e3d54a..000000000 --- a/platform/android/version-script +++ /dev/null @@ -1,4 +0,0 @@ -{ - global: JNI_OnLoad; - local: *; -}; \ No newline at end of file