diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 446114d..0c0918c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,9 +25,10 @@ on: jobs: lint: runs-on: ubuntu-latest + timeout-minutes: 30 steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup uses: ./.github/actions/setup @@ -38,11 +39,57 @@ jobs: - name: Typecheck files run: yarn test:types + check-objc-formatting: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install clang-format + run: sudo apt-get install clang-format + + - name: Check Objective-C formatting + run: ./scripts/format-objc.sh --check + + check-java-formatting: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install JDK + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '17' + java-package: 'jdk' + + - name: Download google-java-format + run: | + GOOGLE_JAVA_FORMAT_VERSION=1.23.0 + GOOGLE_JAVA_FORMAT_URL=https://github.com/google/google-java-format/releases/download/v${GOOGLE_JAVA_FORMAT_VERSION}/google-java-format-${GOOGLE_JAVA_FORMAT_VERSION}-all-deps.jar + mkdir -p $HOME/google-java-format + curl -L -o $HOME/google-java-format/google-java-format.jar $GOOGLE_JAVA_FORMAT_URL + + - name: Create google-java-format wrapper script + run: | + cat << 'EOF' > /usr/local/bin/google-java-format + #!/bin/sh + exec java -jar "$HOME/google-java-format/google-java-format.jar" "$@" + EOF + chmod +x /usr/local/bin/google-java-format + + - name: Check Java formatting + run: ./scripts/format-java.sh --check + test: runs-on: ubuntu-latest + timeout-minutes: 30 steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup uses: ./.github/actions/setup @@ -52,9 +99,10 @@ jobs: build-library: runs-on: ubuntu-latest + timeout-minutes: 30 steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup uses: ./.github/actions/setup @@ -64,11 +112,12 @@ jobs: build-android: runs-on: ubuntu-latest + timeout-minutes: 30 env: TURBO_CACHE_DIR: .turbo/android steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup uses: ./.github/actions/setup @@ -122,11 +171,12 @@ jobs: build-ios: runs-on: macos-14 + timeout-minutes: 30 env: TURBO_CACHE_DIR: .turbo/ios steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup uses: ./.github/actions/setup diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c86dc13..6c3d2b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,8 @@ This project follows - [git](https://git-scm.com) (used for source version control). - An IDE such as [Android Studio](https://developer.android.com/studio) or [Visual Studio Code](https://code.visualstudio.com/). - [addlicense](https://github.com/google/addlicense) +- [google-java-format Version 1.23.0](https://github.com/google/google-java-format) (used to format Java code). +- [clang-format](https://clang.llvm.org/docs/ClangFormat.html) (used to format Objective-C code). ## 2. Forking & cloning the repository @@ -44,22 +46,6 @@ This project follows fetch from the master repository, not your clone, when running `git fetch` et al.) -## 3. Test your changes - -- Make sure to test your changes before sending them for review. To do so, update and run the [Sample app](./example/) at `./example`. - -### Code reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. Consult -[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more -information on using pull requests. - -Please peruse the -[Typescript style guide](https://google.github.io/styleguide/tsguide.html), [Java style guide](https://google.github.io/styleguide/javaguide.html), and [Objective-C style guide](https://google.github.io/styleguide/objcguide.html) before -working on anything non-trivial. These guidelines are intended to -keep the code consistent and avoid common pitfalls. - #### Create branch 1. `git fetch upstream` @@ -84,3 +70,42 @@ keep the code consistent and avoid common pitfalls. 1. `git pull-request` (if you are using [Hub](http://github.com/github/hub/)) or go to `https://github.com/googlemaps/react-native-navigation-sdk` and click the "Compare & pull request" button + +## 3. Test your changes + +Make sure to test your changes before sending them for review. To do so, update and run the [Sample app](./example/) at `./example`. + +## 4. Code Formatting + +### Objective-C and Java Code Formatting + +This project enforces code formatting for Objective-C and Java files to follow Google's style guidelines. The formatting is automatically checked before commits and during continuous integration (CI) using Lefthook and GitHub Actions. + +#### Running Formatters Locally + +Before committing your changes, you should run the formatters manually to ensure your code adheres to the required style: + +**Objective-C:** +```bash +./scripts/format-objc.sh +``` +This script will format all Objective-C files under the /ios and /example/ios directories according to Google's Objective-C style guide. + +**Java:** +```bash +./scripts/format-java.sh +``` +This script will format all Java files under the /android and /example/android directories according to Google's Java style guide. + + +## 5. Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +Please peruse the +[Typescript style guide](https://google.github.io/styleguide/tsguide.html), [Java style guide](https://google.github.io/styleguide/javaguide.html), and [Objective-C style guide](https://google.github.io/styleguide/objcguide.html) before +working on anything non-trivial. These guidelines are intended to +keep the code consistent and avoid common pitfalls. diff --git a/android/src/main/java/com/google/android/react/navsdk/Command.java b/android/src/main/java/com/google/android/react/navsdk/Command.java index 0bd814c..8ddac24 100644 --- a/android/src/main/java/com/google/android/react/navsdk/Command.java +++ b/android/src/main/java/com/google/android/react/navsdk/Command.java @@ -33,7 +33,8 @@ public enum Command { SET_MY_LOCATION_BUTTON_ENABLED(15, "setMyLocationButtonEnabled"), SET_ROTATE_GESTURES_ENABLED(16, "setRotateGesturesEnabled"), SET_SCROLL_GESTURES_ENABLED(17, "setScrollGesturesEnabled"), - SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM(18, "setScrollGesturesEnabledDuringRotateOrZoom"), + SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM( + 18, "setScrollGesturesEnabledDuringRotateOrZoom"), SET_TILT_GESTURES_ENABLED(19, "setTiltGesturesEnabled"), SET_ZOOM_GESTURES_ENABLED(20, "setZoomGestures"), SET_BUILDINGS_ENABLED(21, "setBuildingsEnabled"), diff --git a/android/src/main/java/com/google/android/react/navsdk/EnumTranslationUtil.java b/android/src/main/java/com/google/android/react/navsdk/EnumTranslationUtil.java index 3181fa8..1ae3867 100644 --- a/android/src/main/java/com/google/android/react/navsdk/EnumTranslationUtil.java +++ b/android/src/main/java/com/google/android/react/navsdk/EnumTranslationUtil.java @@ -13,11 +13,11 @@ */ package com.google.android.react.navsdk; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.GoogleMap.CameraPerspective; import com.google.android.libraries.navigation.AlternateRoutesStrategy; -import com.google.android.libraries.navigation.Navigator; import com.google.android.libraries.navigation.ForceNightMode; -import com.google.android.gms.maps.GoogleMap.CameraPerspective; -import com.google.android.gms.maps.GoogleMap; +import com.google.android.libraries.navigation.Navigator; public class EnumTranslationUtil { public static AlternateRoutesStrategy getAlternateRoutesStrategyFromJsValue(int jsValue) { diff --git a/android/src/main/java/com/google/android/react/navsdk/INavigationCallback.java b/android/src/main/java/com/google/android/react/navsdk/INavigationCallback.java index 6b235e7..69c2a15 100644 --- a/android/src/main/java/com/google/android/react/navsdk/INavigationCallback.java +++ b/android/src/main/java/com/google/android/react/navsdk/INavigationCallback.java @@ -13,17 +13,6 @@ */ package com.google.android.react.navsdk; -import android.location.Location; -import com.google.android.gms.maps.model.Circle; -import com.google.android.gms.maps.model.GroundOverlay; -import com.google.android.gms.maps.model.LatLng; -import com.google.android.gms.maps.model.Marker; -import com.google.android.gms.maps.model.Polygon; -import com.google.android.gms.maps.model.Polyline; -import com.google.android.libraries.mapsplatform.turnbyturn.model.NavInfo; -import com.google.android.libraries.navigation.ArrivalEvent; -import com.google.android.libraries.navigation.Navigator; - public interface INavigationCallback { void logDebugInfo(String info); } diff --git a/android/src/main/java/com/google/android/react/navsdk/NavForwardingManager.java b/android/src/main/java/com/google/android/react/navsdk/NavForwardingManager.java index cf1c3fe..734069f 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavForwardingManager.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavForwardingManager.java @@ -14,7 +14,6 @@ package com.google.android.react.navsdk; import android.content.Context; - import com.google.android.libraries.navigation.Navigator; /** Starts and stops the forwarding of turn-by-turn nav info from Nav SDK. */ diff --git a/android/src/main/java/com/google/android/react/navsdk/NavInfoReceivingService.java b/android/src/main/java/com/google/android/react/navsdk/NavInfoReceivingService.java index e8d15c0..359d6b9 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavInfoReceivingService.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavInfoReceivingService.java @@ -22,11 +22,9 @@ import android.os.Message; import android.os.Messenger; import android.os.Process; - import androidx.annotation.Nullable; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; - import com.google.android.libraries.mapsplatform.turnbyturn.TurnByTurnManager; import com.google.android.libraries.mapsplatform.turnbyturn.model.NavInfo; diff --git a/android/src/main/java/com/google/android/react/navsdk/NavModule.java b/android/src/main/java/com/google/android/react/navsdk/NavModule.java index bc96335..31ca456 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavModule.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavModule.java @@ -17,7 +17,6 @@ import androidx.annotation.Nullable; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.Observer; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.Promise; @@ -32,27 +31,26 @@ import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeArray; import com.google.android.gms.maps.model.LatLng; -import com.google.android.libraries.navigation.Navigator; -import com.google.android.libraries.navigation.RouteSegment; -import com.google.android.libraries.navigation.TimeAndDistance; -import com.google.android.libraries.navigation.ArrivalEvent; import com.google.android.libraries.mapsplatform.turnbyturn.model.NavInfo; import com.google.android.libraries.mapsplatform.turnbyturn.model.StepInfo; -import com.google.android.libraries.navigation.Waypoint; +import com.google.android.libraries.navigation.ArrivalEvent; import com.google.android.libraries.navigation.ListenableResultFuture; import com.google.android.libraries.navigation.NavigationApi; import com.google.android.libraries.navigation.NavigationApi.OnTermsResponseListener; +import com.google.android.libraries.navigation.Navigator; import com.google.android.libraries.navigation.RoadSnappedLocationProvider; import com.google.android.libraries.navigation.RoadSnappedLocationProvider.LocationListener; +import com.google.android.libraries.navigation.RouteSegment; import com.google.android.libraries.navigation.SimulationOptions; import com.google.android.libraries.navigation.SpeedAlertOptions; import com.google.android.libraries.navigation.SpeedAlertSeverity; import com.google.android.libraries.navigation.TermsAndConditionsCheckOption; - +import com.google.android.libraries.navigation.TimeAndDistance; +import com.google.android.libraries.navigation.Waypoint; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.ArrayList; /** * This exposes a series of methods that can be called diretly from the React Native code. They have @@ -108,7 +106,8 @@ public void onArrival(ArrivalEvent arrivalEvent) { CatalystInstance catalystInstance = reactContext.getCatalystInstance(); WritableMap map = Arguments.createMap(); - map.putMap("waypoint", ObjectTranslationUtil.getMapFromWaypoint(arrivalEvent.getWaypoint())); + map.putMap( + "waypoint", ObjectTranslationUtil.getMapFromWaypoint(arrivalEvent.getWaypoint())); map.putBoolean("isFinalDestination", arrivalEvent.isFinalDestination()); WritableNativeArray params = new WritableNativeArray(); @@ -138,7 +137,8 @@ public void onRawLocationUpdate(final Location location) { WritableNativeArray params = new WritableNativeArray(); params.pushMap(ObjectTranslationUtil.getMapFromLocation(location)); - catalystInstance.callFunction(Constants.NAV_JAVASCRIPT_FLAG, "onRawLocationChanged", params); + catalystInstance.callFunction( + Constants.NAV_JAVASCRIPT_FLAG, "onRawLocationChanged", params); } }; @@ -154,7 +154,7 @@ public void onRouteChanged() { new Navigator.TrafficUpdatedListener() { @Override public void onTrafficUpdated() { - sendCommandToReactNative("onTrafficUpdated", null); + sendCommandToReactNative("onTrafficUpdated", null); } }; @@ -162,7 +162,7 @@ public void onTrafficUpdated() { new Navigator.ReroutingListener() { @Override public void onReroutingRequestedByOffRoute() { - sendCommandToReactNative("onReroutingRequestedByOffRoute", null); + sendCommandToReactNative("onReroutingRequestedByOffRoute", null); } }; @@ -170,7 +170,7 @@ public void onReroutingRequestedByOffRoute() { new Navigator.RemainingTimeOrDistanceChangedListener() { @Override public void onRemainingTimeOrDistanceChanged() { - sendCommandToReactNative("onRemainingTimeOrDistanceChanged", null); + sendCommandToReactNative("onRemainingTimeOrDistanceChanged", null); } }; @@ -183,13 +183,14 @@ private void cleanup() { mNavigator.removeRouteChangedListener(mRouteChangedListener); mNavigator.removeTrafficUpdatedListener(mTrafficUpdatedListener); mNavigator.removeRemainingTimeOrDistanceChangedListener( - mRemainingTimeOrDistanceChangedListener); + mRemainingTimeOrDistanceChangedListener); mWaypoints.clear(); - UiThreadUtil.runOnUiThread(() -> { - mNavigator.clearDestinations(); - mNavigator.cleanup(); - }); + UiThreadUtil.runOnUiThread( + () -> { + mNavigator.clearDestinations(); + mNavigator.cleanup(); + }); } @ReactMethod @@ -205,13 +206,12 @@ public void initializeNavigator(@Nullable ReadableMap tocParams) { Observer navInfoObserver = this::showNavInfo; UiThreadUtil.runOnUiThread( - () -> { - NavInfoReceivingService.getNavInfoLiveData() - .observe((LifecycleOwner) getCurrentActivity(), navInfoObserver); - }); + () -> { + NavInfoReceivingService.getNavInfoLiveData() + .observe((LifecycleOwner) getCurrentActivity(), navInfoObserver); + }); } - private void onNavigationReady() { mNavViewManager.applyStylingOptions(); @@ -228,7 +228,7 @@ private void onNavigationInitError(int errorCode) { /** Starts the Navigation API, saving a reference to the ready Navigator instance. */ private void initializeNavigationApi() { NavigationApi.getNavigator( - getCurrentActivity().getApplication(), + getCurrentActivity().getApplication(), new NavigationApi.NavigatorListener() { @Override public void onNavigatorReady(Navigator navigator) { @@ -305,7 +305,6 @@ private void removeNavigationListeners() { mRemainingTimeOrDistanceChangedListener); } - private void createWaypoint(Map map) { String placeId = CollectionUtil.getString("placeId", map); String title = CollectionUtil.getString("title", map); @@ -355,7 +354,8 @@ public void setDestination(ReadableMap waypoint, @Nullable ReadableMap routingOp if (routingOptions != null) { pendingRoute = mNavigator.setDestination( - mWaypoints.get(0), ObjectTranslationUtil.getRoutingOptionsFromMap(routingOptions.toHashMap())); + mWaypoints.get(0), + ObjectTranslationUtil.getRoutingOptionsFromMap(routingOptions.toHashMap())); } else { pendingRoute = mNavigator.setDestination(mWaypoints.get(0)); } @@ -364,7 +364,7 @@ public void setDestination(ReadableMap waypoint, @Nullable ReadableMap routingOp new IRouteStatusResult() { @Override public void onResult(Navigator.RouteStatus code) { - sendCommandToReactNative("onRouteStatusResult", code.toString()); + sendCommandToReactNative("onRouteStatusResult", code.toString()); } }); } @@ -388,7 +388,8 @@ public void setDestinations(ReadableArray waypoints, @Nullable ReadableMap routi if (routingOptions != null) { pendingRoute = mNavigator.setDestinations( - mWaypoints, ObjectTranslationUtil.getRoutingOptionsFromMap(routingOptions.toHashMap())); + mWaypoints, + ObjectTranslationUtil.getRoutingOptionsFromMap(routingOptions.toHashMap())); } else { pendingRoute = mNavigator.setDestinations(mWaypoints); } @@ -508,9 +509,10 @@ public void setSpeedAlertOptions(@Nullable ReadableMap options) { .setSeverityUpgradeDurationSeconds(severityUpgradeDurationSeconds) .build(); - UiThreadUtil.runOnUiThread(() -> { - mNavigator.setSpeedAlertOptions(alertOptions); - }); + UiThreadUtil.runOnUiThread( + () -> { + mNavigator.setSpeedAlertOptions(alertOptions); + }); } @ReactMethod @@ -519,9 +521,10 @@ public void setAudioGuidanceType(int jsValue) { return; } - UiThreadUtil.runOnUiThread(() -> { - mNavigator.setAudioGuidance(EnumTranslationUtil.getAudioGuidanceFromJsValue(jsValue)); - }); + UiThreadUtil.runOnUiThread( + () -> { + mNavigator.setAudioGuidance(EnumTranslationUtil.getAudioGuidanceFromJsValue(jsValue)); + }); } @ReactMethod @@ -595,7 +598,6 @@ public void getTraveledPath(final Promise promise) { promise.resolve(arr); } - private void sendCommandToReactNative(String functionName, String args) { ReactContext reactContext = getReactApplicationContext(); @@ -657,14 +659,13 @@ public void onTermsResponse(boolean areTermsAccepted) { @ReactMethod public void areTermsAccepted(final Promise promise) { - promise.resolve(getTermsAccepted()); + promise.resolve(getTermsAccepted()); } public Boolean getTermsAccepted() { return NavigationApi.areTermsAccepted(getCurrentActivity().getApplication()); } - @ReactMethod public void getNavSDKVersion(final Promise promise) { promise.resolve(NavigationApi.getNavSDKVersion()); @@ -689,40 +690,38 @@ private void showNavInfo(NavInfo navInfo) { if (navInfo == null || reactContext == null) { return; } - CatalystInstance catalystInstance = reactContext.getCatalystInstance(); + CatalystInstance catalystInstance = reactContext.getCatalystInstance(); - WritableMap map = Arguments.createMap(); - - map.putInt("navState", navInfo.getNavState()); - map.putBoolean("routeChanged", navInfo.getRouteChanged()); - if (navInfo.getDistanceToCurrentStepMeters() != null) - map.putInt("distanceToCurrentStepMeters", navInfo.getDistanceToCurrentStepMeters()); - if (navInfo.getDistanceToFinalDestinationMeters() != null) - map.putInt( - "distanceToFinalDestinationMeters", navInfo.getDistanceToFinalDestinationMeters()); - if (navInfo.getDistanceToNextDestinationMeters() != null) - map.putInt("distanceToNextDestinationMeters", navInfo.getDistanceToNextDestinationMeters()); - if (navInfo.getTimeToCurrentStepSeconds() != null) - map.putInt("timeToCurrentStepSeconds", navInfo.getTimeToCurrentStepSeconds()); - if (navInfo.getTimeToFinalDestinationSeconds() != null) - map.putInt("timeToFinalDestinationSeconds", navInfo.getTimeToFinalDestinationSeconds()); - if (navInfo.getTimeToNextDestinationSeconds() != null) - map.putInt("timeToNextDestinationSeconds", navInfo.getTimeToNextDestinationSeconds()); - if (navInfo.getCurrentStep() != null) - map.putMap( - "currentStep", ObjectTranslationUtil.getMapFromStepInfo(navInfo.getCurrentStep())); - - WritableArray remainingSteps = Arguments.createArray(); - if (navInfo.getRemainingSteps() != null) { - for (StepInfo info : navInfo.getRemainingSteps()) { - remainingSteps.pushMap(ObjectTranslationUtil.getMapFromStepInfo(info)); - } + WritableMap map = Arguments.createMap(); + + map.putInt("navState", navInfo.getNavState()); + map.putBoolean("routeChanged", navInfo.getRouteChanged()); + if (navInfo.getDistanceToCurrentStepMeters() != null) + map.putInt("distanceToCurrentStepMeters", navInfo.getDistanceToCurrentStepMeters()); + if (navInfo.getDistanceToFinalDestinationMeters() != null) + map.putInt("distanceToFinalDestinationMeters", navInfo.getDistanceToFinalDestinationMeters()); + if (navInfo.getDistanceToNextDestinationMeters() != null) + map.putInt("distanceToNextDestinationMeters", navInfo.getDistanceToNextDestinationMeters()); + if (navInfo.getTimeToCurrentStepSeconds() != null) + map.putInt("timeToCurrentStepSeconds", navInfo.getTimeToCurrentStepSeconds()); + if (navInfo.getTimeToFinalDestinationSeconds() != null) + map.putInt("timeToFinalDestinationSeconds", navInfo.getTimeToFinalDestinationSeconds()); + if (navInfo.getTimeToNextDestinationSeconds() != null) + map.putInt("timeToNextDestinationSeconds", navInfo.getTimeToNextDestinationSeconds()); + if (navInfo.getCurrentStep() != null) + map.putMap("currentStep", ObjectTranslationUtil.getMapFromStepInfo(navInfo.getCurrentStep())); + + WritableArray remainingSteps = Arguments.createArray(); + if (navInfo.getRemainingSteps() != null) { + for (StepInfo info : navInfo.getRemainingSteps()) { + remainingSteps.pushMap(ObjectTranslationUtil.getMapFromStepInfo(info)); } - map.putArray("getRemainingSteps", remainingSteps); + } + map.putArray("getRemainingSteps", remainingSteps); - WritableNativeArray params = new WritableNativeArray(); - params.pushMap(map); - catalystInstance.callFunction(Constants.NAV_JAVASCRIPT_FLAG, "onTurnByTurn", params); + WritableNativeArray params = new WritableNativeArray(); + params.pushMap(map); + catalystInstance.callFunction(Constants.NAV_JAVASCRIPT_FLAG, "onTurnByTurn", params); } @Override diff --git a/android/src/main/java/com/google/android/react/navsdk/NavViewFragment.java b/android/src/main/java/com/google/android/react/navsdk/NavViewFragment.java index c5f6141..a6aab44 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavViewFragment.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavViewFragment.java @@ -19,18 +19,16 @@ import android.graphics.Color; import android.os.Bundle; import android.view.View; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; - import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.UIManagerHelper; -import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.uimanager.events.Event; +import com.facebook.react.uimanager.events.EventDispatcher; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; @@ -52,7 +50,6 @@ import com.google.android.libraries.navigation.NavigationView; import com.google.android.libraries.navigation.StylingOptions; import com.google.android.libraries.navigation.SupportNavigationFragment; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -86,12 +83,13 @@ public NavViewFragment(ReactApplicationContext reactContext, int viewTag) { this.viewTag = viewTag; } - private NavigationView.OnRecenterButtonClickedListener onRecenterButtonClickedListener = new NavigationView.OnRecenterButtonClickedListener() { - @Override - public void onRecenterButtonClick() { - emitEvent("onRecenterButtonClick", null); - } - }; + private NavigationView.OnRecenterButtonClickedListener onRecenterButtonClickedListener = + new NavigationView.OnRecenterButtonClickedListener() { + @Override + public void onRecenterButtonClick() { + emitEvent("onRecenterButtonClick", null); + } + }; private String style = ""; @@ -102,67 +100,85 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat setNavigationUiEnabled(NavModule.getInstance().getNavigator() != null); - getMapAsync(new OnMapReadyCallback() { - public void onMapReady(GoogleMap googleMap) { - mGoogleMap = googleMap; - - emitEvent("onMapReady", null); - - setNavigationUiEnabled(NavModule.getInstance().getNavigator() != null); - - mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { - @Override - public boolean onMarkerClick(Marker marker) { - emitEvent("onMarkerClick", ObjectTranslationUtil.getMapFromMarker(marker)); - return false; - } - }); - mGoogleMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() { - @Override - public void onPolylineClick(Polyline polyline) { - emitEvent("onPolylineClick", ObjectTranslationUtil.getMapFromPolyline(polyline)); - } - }); - mGoogleMap.setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() { - @Override - public void onPolygonClick(Polygon polygon) { - emitEvent("onPolygonClick", ObjectTranslationUtil.getMapFromPolygon(polygon)); - } - }); - mGoogleMap.setOnCircleClickListener(new GoogleMap.OnCircleClickListener() { - @Override - public void onCircleClick(Circle circle) { - emitEvent("onCircleClick", ObjectTranslationUtil.getMapFromCircle(circle)); - } - }); - mGoogleMap.setOnGroundOverlayClickListener(new GoogleMap.OnGroundOverlayClickListener() { - @Override - public void onGroundOverlayClick(GroundOverlay groundOverlay) { - emitEvent("onGroundOverlayClick", ObjectTranslationUtil.getMapFromGroundOverlay(groundOverlay)); - } - }); - - mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { - @Override - public void onInfoWindowClick(Marker marker) { - emitEvent("onMarkerInfoWindowTapped", ObjectTranslationUtil.getMapFromMarker(marker)); + getMapAsync( + new OnMapReadyCallback() { + public void onMapReady(GoogleMap googleMap) { + mGoogleMap = googleMap; + + emitEvent("onMapReady", null); + + setNavigationUiEnabled(NavModule.getInstance().getNavigator() != null); + + mGoogleMap.setOnMarkerClickListener( + new GoogleMap.OnMarkerClickListener() { + @Override + public boolean onMarkerClick(Marker marker) { + emitEvent("onMarkerClick", ObjectTranslationUtil.getMapFromMarker(marker)); + return false; + } + }); + mGoogleMap.setOnPolylineClickListener( + new GoogleMap.OnPolylineClickListener() { + @Override + public void onPolylineClick(Polyline polyline) { + emitEvent( + "onPolylineClick", ObjectTranslationUtil.getMapFromPolyline(polyline)); + } + }); + mGoogleMap.setOnPolygonClickListener( + new GoogleMap.OnPolygonClickListener() { + @Override + public void onPolygonClick(Polygon polygon) { + emitEvent("onPolygonClick", ObjectTranslationUtil.getMapFromPolygon(polygon)); + } + }); + mGoogleMap.setOnCircleClickListener( + new GoogleMap.OnCircleClickListener() { + @Override + public void onCircleClick(Circle circle) { + emitEvent("onCircleClick", ObjectTranslationUtil.getMapFromCircle(circle)); + } + }); + mGoogleMap.setOnGroundOverlayClickListener( + new GoogleMap.OnGroundOverlayClickListener() { + @Override + public void onGroundOverlayClick(GroundOverlay groundOverlay) { + emitEvent( + "onGroundOverlayClick", + ObjectTranslationUtil.getMapFromGroundOverlay(groundOverlay)); + } + }); + + mGoogleMap.setOnInfoWindowClickListener( + new GoogleMap.OnInfoWindowClickListener() { + @Override + public void onInfoWindowClick(Marker marker) { + emitEvent( + "onMarkerInfoWindowTapped", ObjectTranslationUtil.getMapFromMarker(marker)); + } + }); + + mGoogleMap.setOnMapClickListener( + new GoogleMap.OnMapClickListener() { + @Override + public void onMapClick(LatLng latLng) { + emitEvent("onMapClick", ObjectTranslationUtil.getMapFromLatLng(latLng)); + } + }); } }); - mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { - @Override - public void onMapClick(LatLng latLng) { - emitEvent("onMapClick", ObjectTranslationUtil.getMapFromLatLng(latLng)); - } - }); - } - }); - - Executors.newSingleThreadExecutor().execute(() -> { - requireActivity().runOnUiThread((Runnable) () -> { - super.addOnRecenterButtonClickedListener(onRecenterButtonClickedListener); - }); - }); + Executors.newSingleThreadExecutor() + .execute( + () -> { + requireActivity() + .runOnUiThread( + (Runnable) + () -> { + super.addOnRecenterButtonClickedListener( + onRecenterButtonClickedListener); + }); + }); } public void applyStylingOptions() { @@ -241,7 +257,8 @@ public Circle addCircle(Map optionsMap) { CircleOptions options = new CircleOptions(); - float strokeWidth = Double.valueOf(CollectionUtil.getDouble("strokeWidth", optionsMap, 0)).floatValue(); + float strokeWidth = + Double.valueOf(CollectionUtil.getDouble("strokeWidth", optionsMap, 0)).floatValue(); options.strokeWidth(strokeWidth); double radius = CollectionUtil.getDouble("radius", optionsMap, 0.0); @@ -280,7 +297,8 @@ public Marker addMarker(Map optionsMap) { String title = CollectionUtil.getString("title", optionsMap); String snippet = CollectionUtil.getString("snippet", optionsMap); float alpha = Double.valueOf(CollectionUtil.getDouble("alpha", optionsMap, 1)).floatValue(); - float rotation = Double.valueOf(CollectionUtil.getDouble("rotation", optionsMap, 0)).floatValue(); + float rotation = + Double.valueOf(CollectionUtil.getDouble("rotation", optionsMap, 0)).floatValue(); boolean draggable = CollectionUtil.getBool("draggable", optionsMap, false); boolean flat = CollectionUtil.getBool("flat", optionsMap, false); boolean visible = CollectionUtil.getBool("visible", optionsMap, true); @@ -354,7 +372,8 @@ public Polygon addPolygon(Map optionsMap) { String strokeColor = CollectionUtil.getString("strokeColor", optionsMap); String fillColor = CollectionUtil.getString("fillColor", optionsMap); - float strokeWidth = Double.valueOf(CollectionUtil.getDouble("strokeWidth", optionsMap, 0)).floatValue(); + float strokeWidth = + Double.valueOf(CollectionUtil.getDouble("strokeWidth", optionsMap, 0)).floatValue(); boolean clickable = CollectionUtil.getBool("clickable", optionsMap, false); boolean geodesic = CollectionUtil.getBool("geodesic", optionsMap, false); boolean visible = CollectionUtil.getBool("visible", optionsMap, true); @@ -405,15 +424,16 @@ public Polygon addPolygon(Map optionsMap) { } public void removeMarker(String id) { - UiThreadUtil.runOnUiThread(() -> { - for (Marker m : markerList) { - if (m.getId().equals(id)) { - m.remove(); - markerList.remove(m); - return; - } - } - }); + UiThreadUtil.runOnUiThread( + () -> { + for (Marker m : markerList) { + if (m.getId().equals(id)) { + m.remove(); + markerList.remove(m); + return; + } + } + }); } public void removePolyline(String id) { @@ -475,7 +495,8 @@ public GroundOverlay addGroundOverlay(Map map) { String imagePath = CollectionUtil.getString("imgPath", map); float width = Double.valueOf(CollectionUtil.getDouble("width", map, 0)).floatValue(); float height = Double.valueOf(CollectionUtil.getDouble("height", map, 0)).floatValue(); - float transparency = Double.valueOf(CollectionUtil.getDouble("transparency", map, 0)).floatValue(); + float transparency = + Double.valueOf(CollectionUtil.getDouble("transparency", map, 0)).floatValue(); boolean clickable = CollectionUtil.getBool("clickable", map, false); boolean visible = CollectionUtil.getBool("visible", map, true); @@ -502,17 +523,22 @@ public GroundOverlay addGroundOverlay(Map map) { } public void setMapStyle(String url) { - Executors.newSingleThreadExecutor().execute(() -> { - try { - style = fetchJsonFromUrl(url); - } catch (IOException e) { - throw new RuntimeException(e); - } - requireActivity().runOnUiThread((Runnable) () -> { - MapStyleOptions options = new MapStyleOptions(style); - mGoogleMap.setMapStyle(options); - }); - }); + Executors.newSingleThreadExecutor() + .execute( + () -> { + try { + style = fetchJsonFromUrl(url); + } catch (IOException e) { + throw new RuntimeException(e); + } + requireActivity() + .runOnUiThread( + (Runnable) + () -> { + MapStyleOptions options = new MapStyleOptions(style); + mGoogleMap.setMapStyle(options); + }); + }); } public String fetchJsonFromUrl(String urlString) throws IOException { @@ -538,10 +564,7 @@ public String fetchJsonFromUrl(String urlString) throws IOException { } } - - /** - * Moves the position of the camera to hover over Melbourne. - */ + /** Moves the position of the camera to hover over Melbourne. */ public void moveCamera(Map map) { LatLng latLng = ObjectTranslationUtil.getLatLngFromMap((Map) map.get("target")); @@ -549,7 +572,8 @@ public void moveCamera(Map map) { float tilt = (float) CollectionUtil.getDouble("tilt", map, 0); float bearing = (float) CollectionUtil.getDouble("bearing", map, 0); - CameraPosition cameraPosition = CameraPosition.builder().target(latLng).zoom(zoom).tilt(tilt).bearing(bearing).build(); + CameraPosition cameraPosition = + CameraPosition.builder().target(latLng).zoom(zoom).tilt(tilt).bearing(bearing).build(); mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } @@ -637,17 +661,16 @@ public void setMapToolbarEnabled(boolean isOn) { } } - /** - * Toggles whether the location marker is enabled. - */ + /** Toggles whether the location marker is enabled. */ public void setMyLocationButtonEnabled(boolean isOn) { if (mGoogleMap == null) { return; } - UiThreadUtil.runOnUiThread(() -> { - mGoogleMap.getUiSettings().setMyLocationButtonEnabled(isOn); - }); + UiThreadUtil.runOnUiThread( + () -> { + mGoogleMap.getUiSettings().setMyLocationButtonEnabled(isOn); + }); } @Override @@ -672,7 +695,8 @@ private void cleanup() { private void emitEvent(String eventName, @Nullable WritableMap data) { if (reactContext != null) { - EventDispatcher dispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, viewTag); + EventDispatcher dispatcher = + UIManagerHelper.getEventDispatcherForReactTag(reactContext, viewTag); if (dispatcher != null) { int surfaceId = UIManagerHelper.getSurfaceId(reactContext); @@ -685,7 +709,8 @@ public class NavViewEvent extends Event { private String eventName; private @Nullable WritableMap eventData; - public NavViewEvent(int surfaceId, int viewTag, String eventName, @Nullable WritableMap eventData) { + public NavViewEvent( + int surfaceId, int viewTag, String eventName, @Nullable WritableMap eventData) { super(surfaceId, viewTag); this.eventName = eventName; this.eventData = eventData; @@ -705,4 +730,3 @@ public WritableMap getEventData() { } } } - diff --git a/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java b/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java index 326c7ae..738111d 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavViewManager.java @@ -19,19 +19,15 @@ import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; - import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.google.android.gms.maps.GoogleMap; - import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; @@ -65,18 +61,13 @@ public void setReactContext(ReactApplicationContext reactContext) { this.reactContext = reactContext; } - - /** - * Return a FrameLayout which will later hold the Fragment - */ + /** Return a FrameLayout which will later hold the Fragment */ @Override public FrameLayout createViewInstance(ThemedReactContext reactContext) { return new FrameLayout(reactContext); } - /** - * Map the "create" command to an integer - */ + /** Map the "create" command to an integer */ @Nullable @Override public Map getCommandsMap() { @@ -98,7 +89,9 @@ public Map getCommandsMap() { map.put(SET_MY_LOCATION_ENABLED.toString(), SET_MY_LOCATION_ENABLED.getValue()); map.put(SET_ROTATE_GESTURES_ENABLED.toString(), SET_ROTATE_GESTURES_ENABLED.getValue()); map.put(SET_SCROLL_GESTURES_ENABLED.toString(), SET_SCROLL_GESTURES_ENABLED.getValue()); - map.put(SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM.toString(),SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM.getValue()); + map.put( + SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM.toString(), + SET_SCROLL_GESTURES_ENABLED_DURING_ROTATE_OR_ZOOM.getValue()); map.put(SET_ZOOM_CONTROLS_ENABLED.toString(), SET_ZOOM_CONTROLS_ENABLED.getValue()); map.put(SET_TILT_GESTURES_ENABLED.toString(), SET_TILT_GESTURES_ENABLED.getValue()); map.put(SET_ZOOM_GESTURES_ENABLED.toString(), SET_ZOOM_GESTURES_ENABLED.getValue()); @@ -109,7 +102,9 @@ public Map getCommandsMap() { map.put(RESET_MIN_MAX_ZOOM_LEVEL.toString(), RESET_MIN_MAX_ZOOM_LEVEL.getValue()); map.put(SET_MAP_STYLE.toString(), SET_MAP_STYLE.getValue()); map.put(ANIMATE_CAMERA.toString(), ANIMATE_CAMERA.getValue()); - map.put(SET_TRAFFIC_INCIDENT_CARDS_ENABLED.toString(), SET_TRAFFIC_INCIDENT_CARDS_ENABLED.getValue()); + map.put( + SET_TRAFFIC_INCIDENT_CARDS_ENABLED.toString(), + SET_TRAFFIC_INCIDENT_CARDS_ENABLED.getValue()); map.put(SET_RECENTER_BUTTON_ENABLED.toString(), SET_RECENTER_BUTTON_ENABLED.getValue()); map.put(SHOW_ROUTE_OVERVIEW.toString(), SHOW_ROUTE_OVERVIEW.getValue()); map.put(REMOVE_MARKER.toString(), REMOVE_MARKER.getValue()); @@ -152,7 +147,8 @@ public void applyStylingOptions() { } @Override - public void receiveCommand(@NonNull FrameLayout root, String commandId, @Nullable ReadableArray args) { + public void receiveCommand( + @NonNull FrameLayout root, String commandId, @Nullable ReadableArray args) { super.receiveCommand(root, commandId, args); int commandIdInt = Integer.parseInt(commandId); @@ -166,10 +162,10 @@ public void receiveCommand(@NonNull FrameLayout root, String commandId, @Nullabl int viewId = root.getId(); FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity(); activity - .getSupportFragmentManager() - .beginTransaction() - .remove(Objects.requireNonNull(fragmentMap.remove(viewId)).get()) - .commitNowAllowingStateLoss(); + .getSupportFragmentManager() + .beginTransaction() + .remove(Objects.requireNonNull(fragmentMap.remove(viewId)).get()) + .commitNowAllowingStateLoss(); } catch (Exception ignored) { } break; @@ -288,27 +284,33 @@ public void receiveCommand(@NonNull FrameLayout root, String commandId, @Nullabl @Override public Map getExportedCustomDirectEventTypeConstants() { Map baseEventTypeConstants = super.getExportedCustomDirectEventTypeConstants(); - Map eventTypeConstants = baseEventTypeConstants != null ? baseEventTypeConstants : new HashMap<>(); - - ((Map) eventTypeConstants).putAll(MapBuilder.builder() - .put("onRecenterButtonClick", MapBuilder.of("registrationName", "onRecenterButtonClick")) - .put("onMapReady", MapBuilder.of("registrationName", "onMapReady")) - .put("onMapClick", MapBuilder.of("registrationName", "onMapClick")) - .put("onMarkerClick", MapBuilder.of("registrationName", "onMarkerClick")) - .put("onPolylineClick", MapBuilder.of("registrationName", "onPolylineClick")) - .put("onPolygonClick", MapBuilder.of("registrationName", "onPolygonClick")) - .put("onCircleClick", MapBuilder.of("registrationName", "onCircleClick")) - .put("onGroundOverlayClick", MapBuilder.of("registrationName", "onGroundOverlayClick")) - .put("onMarkerInfoWindowTapped", MapBuilder.of("registrationName", "onMarkerInfoWindowTapped")) - .build()); + Map eventTypeConstants = + baseEventTypeConstants != null ? baseEventTypeConstants : new HashMap<>(); + + ((Map) eventTypeConstants) + .putAll( + MapBuilder.builder() + .put( + "onRecenterButtonClick", + MapBuilder.of("registrationName", "onRecenterButtonClick")) + .put("onMapReady", MapBuilder.of("registrationName", "onMapReady")) + .put("onMapClick", MapBuilder.of("registrationName", "onMapClick")) + .put("onMarkerClick", MapBuilder.of("registrationName", "onMarkerClick")) + .put("onPolylineClick", MapBuilder.of("registrationName", "onPolylineClick")) + .put("onPolygonClick", MapBuilder.of("registrationName", "onPolygonClick")) + .put("onCircleClick", MapBuilder.of("registrationName", "onCircleClick")) + .put( + "onGroundOverlayClick", + MapBuilder.of("registrationName", "onGroundOverlayClick")) + .put( + "onMarkerInfoWindowTapped", + MapBuilder.of("registrationName", "onMarkerInfoWindowTapped")) + .build()); return (Map) eventTypeConstants; } - /** - * Replace your React Native view with a custom fragment - */ - public void createFragment( - FrameLayout root, Map stylingOptions) { + /** Replace your React Native view with a custom fragment */ + public void createFragment(FrameLayout root, Map stylingOptions) { setupLayout(root); FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity(); @@ -321,40 +323,40 @@ public void createFragment( fragment.setStylingOptions(stylingOptions); } - activity.getSupportFragmentManager() - .beginTransaction() - .replace(viewId, fragment, String.valueOf(viewId)) - .commit(); + activity + .getSupportFragmentManager() + .beginTransaction() + .replace(viewId, fragment, String.valueOf(viewId)) + .commit(); } } /** - * Set up the layout for each frame. This official RN way to do this, but a bit hacky, - * and should be changed when better solution is found. + * Set up the layout for each frame. This official RN way to do this, but a bit hacky, and should + * be changed when better solution is found. */ public void setupLayout(FrameLayout view) { - Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() { - @Override - public void doFrame(long frameTimeNanos) { - manuallyLayoutChildren(view); - view.getViewTreeObserver().dispatchOnGlobalLayout(); - Choreographer.getInstance().postFrameCallback(this); - } - }); + Choreographer.getInstance() + .postFrameCallback( + new Choreographer.FrameCallback() { + @Override + public void doFrame(long frameTimeNanos) { + manuallyLayoutChildren(view); + view.getViewTreeObserver().dispatchOnGlobalLayout(); + Choreographer.getInstance().postFrameCallback(this); + } + }); } - /** - * Layout all children properly - */ + /** Layout all children properly */ public void manuallyLayoutChildren(FrameLayout view) { NavViewFragment fragment = getFragmentForRoot(view); if (fragment.isAdded()) { View childView = fragment.getView(); if (childView != null) { childView.measure( - View.MeasureSpec.makeMeasureSpec(view.getMeasuredWidth(), View.MeasureSpec.EXACTLY), - View.MeasureSpec.makeMeasureSpec(view.getMeasuredHeight(), View.MeasureSpec.EXACTLY) - ); + View.MeasureSpec.makeMeasureSpec(view.getMeasuredWidth(), View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(view.getMeasuredHeight(), View.MeasureSpec.EXACTLY)); childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight()); } } @@ -367,5 +369,4 @@ public GoogleMap getGoogleMap(int viewId) { return null; } } - } diff --git a/android/src/main/java/com/google/android/react/navsdk/NavViewModule.java b/android/src/main/java/com/google/android/react/navsdk/NavViewModule.java index 1bda68c..e58d953 100644 --- a/android/src/main/java/com/google/android/react/navsdk/NavViewModule.java +++ b/android/src/main/java/com/google/android/react/navsdk/NavViewModule.java @@ -14,22 +14,14 @@ package com.google.android.react.navsdk; import android.location.Location; -import android.util.Log; -import android.widget.Toast; - import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; -import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; -import com.facebook.react.bridge.WritableNativeArray; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; @@ -38,13 +30,7 @@ import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.Polyline; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import java.util.HashMap; -import java.util.List; import java.util.Map; /** @@ -176,7 +162,9 @@ public void addMarker(int viewId, ReadableMap markerOptionsMap, final Promise pr () -> { if (mNavViewManager.getGoogleMap(viewId) != null) { Marker marker = - mNavViewManager.getFragmentForViewId(viewId).addMarker(markerOptionsMap.toHashMap()); + mNavViewManager + .getFragmentForViewId(viewId) + .addMarker(markerOptionsMap.toHashMap()); promise.resolve(ObjectTranslationUtil.getMapFromMarker(marker)); } @@ -192,7 +180,9 @@ public void addPolyline(int viewId, ReadableMap polylineOptionsMap, final Promis return; } Polyline polyline = - mNavViewManager.getFragmentForViewId(viewId).addPolyline(polylineOptionsMap.toHashMap()); + mNavViewManager + .getFragmentForViewId(viewId) + .addPolyline(polylineOptionsMap.toHashMap()); promise.resolve(ObjectTranslationUtil.getMapFromPolyline(polyline)); }); @@ -207,7 +197,9 @@ public void addPolygon(int viewId, ReadableMap polygonOptionsMap, final Promise return; } Polygon polygon = - mNavViewManager.getFragmentForViewId(viewId).addPolygon(polygonOptionsMap.toHashMap()); + mNavViewManager + .getFragmentForViewId(viewId) + .addPolygon(polygonOptionsMap.toHashMap()); promise.resolve(ObjectTranslationUtil.getMapFromPolygon(polygon)); }); @@ -237,7 +229,9 @@ public void addGroundOverlay(int viewId, ReadableMap overlayOptionsMap, final Pr return; } GroundOverlay overlay = - mNavViewManager.getFragmentForViewId(viewId).addGroundOverlay(overlayOptionsMap.toHashMap()); + mNavViewManager + .getFragmentForViewId(viewId) + .addGroundOverlay(overlayOptionsMap.toHashMap()); promise.resolve(ObjectTranslationUtil.getMapFromGroundOverlay(overlay)); }); diff --git a/android/src/main/java/com/google/android/react/navsdk/ObjectTranslationUtil.java b/android/src/main/java/com/google/android/react/navsdk/ObjectTranslationUtil.java index 41119cd..fe46ee9 100644 --- a/android/src/main/java/com/google/android/react/navsdk/ObjectTranslationUtil.java +++ b/android/src/main/java/com/google/android/react/navsdk/ObjectTranslationUtil.java @@ -13,27 +13,25 @@ */ package com.google.android.react.navsdk; -import java.util.HashMap; -import java.util.Map; -import com.facebook.react.bridge.Arguments; -import com.google.android.libraries.navigation.RouteSegment; -import com.facebook.react.bridge.WritableMap; -import com.google.android.libraries.navigation.NavigationRoadStretchRenderingData; -import com.google.android.gms.maps.model.LatLng; -import com.google.android.libraries.navigation.Waypoint; -import com.facebook.react.bridge.WritableArray; import android.location.Location; import android.os.Build; - -import com.google.android.libraries.navigation.AlternateRoutesStrategy; -import com.google.android.libraries.navigation.RoutingOptions; -import com.google.android.libraries.mapsplatform.turnbyturn.model.StepInfo; +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.WritableArray; +import com.facebook.react.bridge.WritableMap; import com.google.android.gms.maps.model.Circle; +import com.google.android.gms.maps.model.GroundOverlay; +import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.Polyline; -import com.google.android.gms.maps.model.GroundOverlay; +import com.google.android.libraries.mapsplatform.turnbyturn.model.StepInfo; +import com.google.android.libraries.navigation.AlternateRoutesStrategy; +import com.google.android.libraries.navigation.NavigationRoadStretchRenderingData; +import com.google.android.libraries.navigation.RouteSegment; +import com.google.android.libraries.navigation.RoutingOptions; +import com.google.android.libraries.navigation.Waypoint; import java.util.List; +import java.util.Map; public class ObjectTranslationUtil { public static WritableMap getMapFromRouteSegment(RouteSegment routeSegment) { diff --git a/android/src/main/java/com/google/android/react/navsdk/Package.java b/android/src/main/java/com/google/android/react/navsdk/Package.java index 6aea4c8..dbb40b0 100644 --- a/android/src/main/java/com/google/android/react/navsdk/Package.java +++ b/android/src/main/java/com/google/android/react/navsdk/Package.java @@ -17,7 +17,6 @@ import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; diff --git a/android/src/main/java/com/google/android/react/navsdk/StylingOptionsBuilder.java b/android/src/main/java/com/google/android/react/navsdk/StylingOptionsBuilder.java index 4c8dfce..7ff59d5 100644 --- a/android/src/main/java/com/google/android/react/navsdk/StylingOptionsBuilder.java +++ b/android/src/main/java/com/google/android/react/navsdk/StylingOptionsBuilder.java @@ -14,9 +14,7 @@ package com.google.android.react.navsdk; import android.graphics.Color; - import com.google.android.libraries.navigation.StylingOptions; - import java.util.Map; public class StylingOptionsBuilder { diff --git a/example/ios/SampleApp/main.m b/example/ios/SampleApp/main.m index 7219371..3465d6b 100644 --- a/example/ios/SampleApp/main.m +++ b/example/ios/SampleApp/main.m @@ -16,8 +16,7 @@ #import "AppDelegate.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } diff --git a/ios/react-native-navigation-sdk/INavigationCallback.h b/ios/react-native-navigation-sdk/INavigationCallback.h index eefc3a4..5af6e68 100644 --- a/ios/react-native-navigation-sdk/INavigationCallback.h +++ b/ios/react-native-navigation-sdk/INavigationCallback.h @@ -29,7 +29,9 @@ NS_ASSUME_NONNULL_BEGIN - (void)onRouteChanged; - (void)onArrival:(NSDictionary *)waypoint; - (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo; -- (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo distanceToNextDestinationMeters:(double)distanceToNextDestinationMeters timeToNextDestinationSeconds:(double)timeToNextDestinationSeconds; +- (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo + distanceToNextDestinationMeters:(double)distanceToNextDestinationMeters + timeToNextDestinationSeconds:(double)timeToNextDestinationSeconds; - (void)onNavigationReady; - (void)onNavigationInitError:(NSNumber *)errorCode; - (void)onStartGuidance; diff --git a/ios/react-native-navigation-sdk/NavEventDispatcher.m b/ios/react-native-navigation-sdk/NavEventDispatcher.m index 95bbc4f..f755518 100644 --- a/ios/react-native-navigation-sdk/NavEventDispatcher.m +++ b/ios/react-native-navigation-sdk/NavEventDispatcher.m @@ -17,62 +17,61 @@ #import "NavEventDispatcher.h" @implementation NavEventDispatcher { - bool hasListeners; + bool hasListeners; } RCT_EXPORT_MODULE(NavEventDispatcher); + (id)allocWithZone:(NSZone *)zone { - static NavEventDispatcher *sharedInstance = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sharedInstance = [super allocWithZone:zone]; - }); - return sharedInstance; + static NavEventDispatcher *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [super allocWithZone:zone]; + }); + return sharedInstance; } - (NSArray *)supportedEvents { - return @[ - @"onRemainingTimeOrDistanceChanged", - @"onRouteChanged", - @"onTrafficUpdated", - @"onArrival", - @"onTurnByTurn", - @"onNavigationReady", - @"onNavigationInitError", - @"onStartGuidance", - @"onRecenterButtonClick", - @"onRouteStatusResult", - @"onReroutingRequestedByOffRoute", - @"onLocationChanged", - @"onRawLocationChanged", - @"logDebugInfo", - ]; + return @[ + @"onRemainingTimeOrDistanceChanged", + @"onRouteChanged", + @"onTrafficUpdated", + @"onArrival", + @"onTurnByTurn", + @"onNavigationReady", + @"onNavigationInitError", + @"onStartGuidance", + @"onRecenterButtonClick", + @"onRouteStatusResult", + @"onReroutingRequestedByOffRoute", + @"onLocationChanged", + @"onRawLocationChanged", + @"logDebugInfo", + ]; } // Will be called when this module's first listener is added. - (void)startObserving { - hasListeners = YES; - // Set up any upstream listeners or background tasks as necessary + hasListeners = YES; + // Set up any upstream listeners or background tasks as necessary } // Will be called when this module's last listener is removed, or on dealloc. - (void)stopObserving { - hasListeners = NO; - // Remove upstream listeners, stop unnecessary background tasks + hasListeners = NO; + // Remove upstream listeners, stop unnecessary background tasks } - (bool)hasListeners { - return hasListeners; + return hasListeners; } - (void)sendEventName:(NSString *)eventName body:(id)body { - if (hasListeners) { - [self sendEventWithName:eventName body:body]; - } else { - NSLog(@"NavEventDispatcher sendEventName called without listeners: %@", - eventName); - } + if (hasListeners) { + [self sendEventWithName:eventName body:body]; + } else { + NSLog(@"NavEventDispatcher sendEventName called without listeners: %@", eventName); + } } @end diff --git a/ios/react-native-navigation-sdk/NavModule.h b/ios/react-native-navigation-sdk/NavModule.h index 87f5c23..17fa066 100644 --- a/ios/react-native-navigation-sdk/NavModule.h +++ b/ios/react-native-navigation-sdk/NavModule.h @@ -23,7 +23,10 @@ NS_ASSUME_NONNULL_BEGIN -@interface NavModule : NSObject +@interface NavModule : NSObject @property BOOL enableUpdateInfo; diff --git a/ios/react-native-navigation-sdk/NavModule.m b/ios/react-native-navigation-sdk/NavModule.m index 14b5a51..96ddd53 100644 --- a/ios/react-native-navigation-sdk/NavModule.m +++ b/ios/react-native-navigation-sdk/NavModule.m @@ -66,8 +66,7 @@ - (GMSNavigator *)getNavigatorWithError:(NSString **)error { return self->_session.navigator; } -- (BOOL)checkNavigatorWithError:(RCTPromiseRejectBlock)reject - navigator:(GMSNavigator **)navigator { +- (BOOL)checkNavigatorWithError:(RCTPromiseRejectBlock)reject navigator:(GMSNavigator **)navigator { NSString *error = nil; *navigator = [self getNavigatorWithError:&error]; @@ -81,18 +80,16 @@ - (BOOL)checkNavigatorWithError:(RCTPromiseRejectBlock)reject - (void)initializeSession { // Try to create a navigation session. if (self->_session == nil && self->_session.navigator == nil) { - GMSNavigationSession *session = - [GMSNavigationServices createNavigationSession]; + GMSNavigationSession *session = [GMSNavigationServices createNavigationSession]; if (session == nil) { // According to the API documentation, the only reason a nil session is // ever returned is due to terms and conditions not having been accepted // yet. // // At this point, this should not happen due to the earlier check. - @throw [NSException - exceptionWithName:@"GoogleMapsNavigationSessionManagerError" - reason:@"Terms not accepted" - userInfo:nil]; + @throw [NSException exceptionWithName:@"GoogleMapsNavigationSessionManagerError" + reason:@"Terms not accepted" + userInfo:nil]; } self->_session = session; } @@ -115,25 +112,23 @@ - (void)initializeSession { } - (void)showTermsAndConditionsDialog { - BOOL showAwareness = _tosParams[@"showOnlyDisclaimer"] != nil && - [_tosParams[@"showOnlyDisclaimer"] boolValue]; + BOOL showAwareness = + _tosParams[@"showOnlyDisclaimer"] != nil && [_tosParams[@"showOnlyDisclaimer"] boolValue]; - [GMSNavigationServices - setShouldOnlyShowDriverAwarenesssDisclaimer:showAwareness]; + [GMSNavigationServices setShouldOnlyShowDriverAwarenesssDisclaimer:showAwareness]; NSString *companyName = [_tosParams valueForKey:@"companyName"]; NSString *titleHead = [_tosParams valueForKey:@"title"]; - [GMSNavigationServices - showTermsAndConditionsDialogIfNeededWithTitle:titleHead - companyName:companyName - callback:^(BOOL termsAccepted) { - if (termsAccepted) { - [self initializeSession]; - } else { - [self onNavigationInitError:@2]; - } - }]; + [GMSNavigationServices showTermsAndConditionsDialogIfNeededWithTitle:titleHead + companyName:companyName + callback:^(BOOL termsAccepted) { + if (termsAccepted) { + [self initializeSession]; + } else { + [self onNavigationInitError:@2]; + } + }]; } RCT_EXPORT_METHOD(initializeNavigator : (NSDictionary *)options) { @@ -148,8 +143,7 @@ - (void)showTermsAndConditionsDialog { : (RCTPromiseRejectBlock)reject) { dispatch_async(dispatch_get_main_queue(), ^{ if (self->_session == nil) { - reject(@"session_not_initialized", @"Navigation session not initialized", - nil); + reject(@"session_not_initialized", @"Navigation session not initialized", nil); return; } @@ -193,16 +187,11 @@ - (void)showTermsAndConditionsDialog { return; } - GMSNavigationDelayCategory severity = - navigator.delayCategoryToNextDestination; + GMSNavigationDelayCategory severity = navigator.delayCategoryToNextDestination; NSTimeInterval time = navigator.timeToNextDestination; CLLocationDistance distance = navigator.distanceToNextDestination; - resolve(@{ - @"delaySeverity" : @(severity), - @"meters" : @(distance), - @"seconds" : @(time) - }); + resolve(@{@"delaySeverity" : @(severity), @"meters" : @(distance), @"seconds" : @(time)}); }); } @@ -262,12 +251,10 @@ - (void)showTermsAndConditionsDialog { }); } -RCT_EXPORT_METHOD(simulateLocationsAlongExistingRoute - : (nonnull NSNumber *)speedMultiplier) { +RCT_EXPORT_METHOD(simulateLocationsAlongExistingRoute : (nonnull NSNumber *)speedMultiplier) { dispatch_async(dispatch_get_main_queue(), ^{ if (self->_destinations != nil && self->_session != nil) { - [self->_session.locationSimulator - setSpeedMultiplier:[speedMultiplier floatValue]]; + [self->_session.locationSimulator setSpeedMultiplier:[speedMultiplier floatValue]]; [self->_session.locationSimulator simulateLocationsAlongExistingRoute]; } }); @@ -316,10 +303,7 @@ - (void)showTermsAndConditionsDialog { : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject) { NSArray *waypoints = @[ waypoint ]; - [self setDestinations:waypoints - routingOptions:routingOptions - resolve:resolve - rejecter:reject]; + [self setDestinations:waypoints routingOptions:routingOptions resolve:resolve rejecter:reject]; } RCT_EXPORT_METHOD(setDestinations @@ -348,12 +332,10 @@ - (void)showTermsAndConditionsDialog { NSString *placeId = wp[@"placeId"]; if (placeId && ![placeId isEqual:@""]) { - w = [[GMSNavigationMutableWaypoint alloc] initWithPlaceID:placeId - title:wp[@"title"]]; + w = [[GMSNavigationMutableWaypoint alloc] initWithPlaceID:placeId title:wp[@"title"]]; } else if (wp[@"position"]) { w = [[GMSNavigationMutableWaypoint alloc] - initWithLocation:[ObjectTranslationUtil - getLocationCoordinateFrom:wp[@"position"]] + initWithLocation:[ObjectTranslationUtil getLocationCoordinateFrom:wp[@"position"]] title:wp[@"title"]]; } else { continue; @@ -374,47 +356,39 @@ - (void)showTermsAndConditionsDialog { [strongSelf->_destinations addObject:w]; } - void (^routeStatusCallback)(GMSRouteStatus) = - ^(GMSRouteStatus routeStatus) { - __strong typeof(weakSelf) strongSelf = weakSelf; - if (!strongSelf) - return; - [strongSelf onRouteStatusResult:routeStatus]; - resolve(@(YES)); - }; + void (^routeStatusCallback)(GMSRouteStatus) = ^(GMSRouteStatus routeStatus) { + __strong typeof(weakSelf) strongSelf = weakSelf; + if (!strongSelf) return; + [strongSelf onRouteStatusResult:routeStatus]; + resolve(@(YES)); + }; if (routingOptions != NULL) { - [strongSelf configureNavigator:navigator - withRoutingOptions:routingOptions]; + [strongSelf configureNavigator:navigator withRoutingOptions:routingOptions]; [navigator setDestinations:strongSelf->_destinations routingOptions:[NavModule getRoutingOptions:routingOptions] callback:routeStatusCallback]; } else { - [navigator setDestinations:strongSelf->_destinations - callback:routeStatusCallback]; + [navigator setDestinations:strongSelf->_destinations callback:routeStatusCallback]; } }); } + (GMSNavigationRoutingOptions *)getRoutingOptions:(NSDictionary *)options { - GMSNavigationMutableRoutingOptions *routingOptions = - [[GMSNavigationMutableRoutingOptions alloc] - initWithRoutingStrategy:(GMSNavigationRoutingStrategy) - [options[@"routingStrategy"] intValue]]; + GMSNavigationMutableRoutingOptions *routingOptions = [[GMSNavigationMutableRoutingOptions alloc] + initWithRoutingStrategy:(GMSNavigationRoutingStrategy)[options[@"routingStrategy"] intValue]]; - [routingOptions setAlternateRoutesStrategy: - (GMSNavigationAlternateRoutesStrategy) - [options[@"alternateRoutesStrategy"] intValue]]; + [routingOptions setAlternateRoutesStrategy:(GMSNavigationAlternateRoutesStrategy) + [options[@"alternateRoutesStrategy"] intValue]]; return routingOptions; } - (void)configureNavigator:(GMSNavigator *)navigator withRoutingOptions:(NSDictionary *)routingOptions { - if (routingOptions[@"travelMode"] != nil) { NavViewModule *navViewModule = [NavViewModule sharedInstance]; - [navViewModule setTravelMode:(GMSNavigationTravelMode)[routingOptions[@"travelMode"]intValue]]; + [navViewModule setTravelMode:(GMSNavigationTravelMode)[routingOptions[@"travelMode"] intValue]]; } if (routingOptions[@"avoidTolls"] != nil) { @@ -432,8 +406,7 @@ - (void)configureNavigator:(GMSNavigator *)navigator RCT_EXPORT_METHOD(setBackgroundLocationUpdatesEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ - self->_session.roadSnappedLocationProvider.allowsBackgroundLocationUpdates = - isEnabled; + self->_session.roadSnappedLocationProvider.allowsBackgroundLocationUpdates = isEnabled; }); } @@ -456,10 +429,8 @@ - (void)configureNavigator:(GMSNavigator *)navigator @"destinationLatLng" : [ObjectTranslationUtil transformCoordinateToDictionary:currentSegment.destinationCoordinate], @"destinationWaypoint" : [ObjectTranslationUtil - transformNavigationWaypointToDictionary:currentSegment - .destinationWaypoint], - @"segmentLatLngList" : - [ObjectTranslationUtil transformGMSPathToArray:currentSegment.path] + transformNavigationWaypointToDictionary:currentSegment.destinationWaypoint], + @"segmentLatLngList" : [ObjectTranslationUtil transformGMSPathToArray:currentSegment.path] }); }); } @@ -482,9 +453,7 @@ - (void)configureNavigator:(GMSNavigator *)navigator NSMutableArray *arr = [[NSMutableArray alloc] init]; for (int i = 0; i < routeSegmentList.count; i++) { - [arr - addObject:[ObjectTranslationUtil - transformRouteSegmentToDictionary:routeSegmentList[i]]]; + [arr addObject:[ObjectTranslationUtil transformRouteSegmentToDictionary:routeSegmentList[i]]]; } resolve(arr); @@ -522,8 +491,7 @@ - (void)configureNavigator:(GMSNavigator *)navigator double minor = [thresholds[@"minorSpeedAlertPercentThreshold"] doubleValue]; double major = [thresholds[@"majorSpeedAlertPercentThreshold"] doubleValue]; - double severity = - [thresholds[@"severityUpgradeDurationSeconds"] doubleValue]; + double severity = [thresholds[@"severityUpgradeDurationSeconds"] doubleValue]; CGFloat minorSpeedAlertThresholdPercentage = minor; CGFloat majorSpeedAlertThresholdPercentage = major; @@ -538,8 +506,7 @@ - (void)configureNavigator:(GMSNavigator *)navigator [mutableSpeedAlertOptions setSpeedAlertThresholdPercentage:majorSpeedAlertThresholdPercentage forSpeedAlertSeverity:GMSNavigationSpeedAlertSeverityMajor]; - [mutableSpeedAlertOptions - setSeverityUpgradeDurationSeconds:severityUpgradeDurationSeconds]; + [mutableSpeedAlertOptions setSeverityUpgradeDurationSeconds:severityUpgradeDurationSeconds]; // Set SpeedAlertOptions to Navigator navigator.speedAlertOptions = mutableSpeedAlertOptions; @@ -551,8 +518,8 @@ - (void)configureNavigator:(GMSNavigator *)navigator dispatch_async(dispatch_get_main_queue(), ^{ if (self->_session != nil) { [self->_session.locationSimulator - simulateLocationAtCoordinate: - [ObjectTranslationUtil getLocationCoordinateFrom:coordinates]]; + simulateLocationAtCoordinate:[ObjectTranslationUtil + getLocationCoordinateFrom:coordinates]]; } }); } @@ -636,19 +603,15 @@ - (void)sendCommandToReactNative:(NSString *)command args:(NSObject *)args { // Listener for continuous location updates. - (void)locationProvider:(GMSRoadSnappedLocationProvider *)locationProvider didUpdateLocation:(CLLocation *)location { - [self onLocationChanged:[ObjectTranslationUtil - transformCLLocationToDictionary:location]]; + [self onLocationChanged:[ObjectTranslationUtil transformCLLocationToDictionary:location]]; } // Listener to handle arrival events. -- (void)navigator:(GMSNavigator *)navigator - didArriveAtWaypoint:(GMSNavigationWaypoint *)waypoint { +- (void)navigator:(GMSNavigator *)navigator didArriveAtWaypoint:(GMSNavigationWaypoint *)waypoint { NSMutableDictionary *eventMap = [[NSMutableDictionary alloc] init]; - eventMap[@"waypoint"] = - [ObjectTranslationUtil transformNavigationWaypointToDictionary:waypoint]; - eventMap[@"isFinalDestination"] = - @(navigator.routeLegs != nil && navigator.routeLegs.count == 1); + eventMap[@"waypoint"] = [ObjectTranslationUtil transformNavigationWaypointToDictionary:waypoint]; + eventMap[@"isFinalDestination"] = @(navigator.routeLegs != nil && navigator.routeLegs.count == 1); [self onArrival:eventMap]; } @@ -659,8 +622,7 @@ - (void)navigatorDidChangeRoute:(GMSNavigator *)navigator { } // Listener for time to next destination. -- (void)navigator:(GMSNavigator *)navigator - didUpdateRemainingTime:(NSTimeInterval)time { +- (void)navigator:(GMSNavigator *)navigator didUpdateRemainingTime:(NSTimeInterval)time { [self onRemainingTimeOrDistanceChanged]; } @@ -670,10 +632,8 @@ - (void)navigator:(GMSNavigator *)navigator [self onRemainingTimeOrDistanceChanged]; } -- (void)navigator:(GMSNavigator *)navigator - didUpdateNavInfo:(GMSNavigationNavInfo *)navInfo { - if (self.enableUpdateInfo == TRUE && - navInfo.navState == GMSNavigationNavStateEnroute) { +- (void)navigator:(GMSNavigator *)navigator didUpdateNavInfo:(GMSNavigationNavInfo *)navInfo { + if (self.enableUpdateInfo == TRUE && navInfo.navState == GMSNavigationNavStateEnroute) { [self onTurnByTurn:navInfo distanceToNextDestinationMeters:navigator.distanceToNextDestination timeToNextDestinationSeconds:navigator.timeToNextDestination]; @@ -716,41 +676,39 @@ - (void)onStartGuidance { - (void)onRouteStatusResult:(GMSRouteStatus)routeStatus { NSString *status = @""; switch (routeStatus) { - case GMSRouteStatusOK: - status = @"OK"; - break; - case GMSRouteStatusNetworkError: - status = @"NETWORK_ERROR"; - break; - case GMSRouteStatusNoRouteFound: - status = @"NO_ROUTE_FOUND"; - break; - case GMSRouteStatusQuotaExceeded: - status = @"QUOTA_CHECK_FAILED"; - break; - case GMSRouteStatusCanceled: - status = @"ROUTE_CANCELED"; - break; - case GMSRouteStatusLocationUnavailable: - status = @"LOCATION_DISABLED"; - break; - case GMSRouteStatusNoWaypointsError: - status = @"WAYPOINT_ERROR"; - break; - case GMSRouteStatusWaypointError: - status = @"WAYPOINT_ERROR"; - break; - default: - status = @""; - break; + case GMSRouteStatusOK: + status = @"OK"; + break; + case GMSRouteStatusNetworkError: + status = @"NETWORK_ERROR"; + break; + case GMSRouteStatusNoRouteFound: + status = @"NO_ROUTE_FOUND"; + break; + case GMSRouteStatusQuotaExceeded: + status = @"QUOTA_CHECK_FAILED"; + break; + case GMSRouteStatusCanceled: + status = @"ROUTE_CANCELED"; + break; + case GMSRouteStatusLocationUnavailable: + status = @"LOCATION_DISABLED"; + break; + case GMSRouteStatusNoWaypointsError: + status = @"WAYPOINT_ERROR"; + break; + case GMSRouteStatusWaypointError: + status = @"WAYPOINT_ERROR"; + break; + default: + status = @""; + break; } [self sendCommandToReactNative:@"onRouteStatusResult" args:status]; } - (void)onTurnByTurn:(nonnull GMSNavigationNavInfo *)navInfo { - [self onTurnByTurn:navInfo - distanceToNextDestinationMeters:0 - timeToNextDestinationSeconds:0]; + [self onTurnByTurn:navInfo distanceToNextDestinationMeters:0 timeToNextDestinationSeconds:0]; } - (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo @@ -759,16 +717,14 @@ - (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo NSMutableDictionary *obj = [[NSMutableDictionary alloc] init]; [obj setValue:[NSNumber numberWithLong:navInfo.navState] forKey:@"navState"]; - [obj setValue:[NSNumber numberWithBool:navInfo.routeChanged] - forKey:@"routeChanged"]; + [obj setValue:[NSNumber numberWithBool:navInfo.routeChanged] forKey:@"routeChanged"]; if (navInfo.distanceToCurrentStepMeters) { [obj setValue:[NSNumber numberWithLong:navInfo.distanceToCurrentStepMeters] forKey:@"distanceToCurrentStepMeters"]; } if (navInfo.distanceToFinalDestinationMeters) { - [obj setValue:[NSNumber - numberWithLong:navInfo.distanceToFinalDestinationMeters] + [obj setValue:[NSNumber numberWithLong:navInfo.distanceToFinalDestinationMeters] forKey:@"distanceToFinalDestinationMeters"]; } if (navInfo.timeToCurrentStepSeconds) { @@ -787,14 +743,12 @@ - (void)onTurnByTurn:(GMSNavigationNavInfo *)navInfo } if (navInfo.timeToFinalDestinationSeconds) { - [obj - setValue:[NSNumber numberWithLong:navInfo.timeToFinalDestinationSeconds] - forKey:@"timeToFinalDestinationSeconds"]; + [obj setValue:[NSNumber numberWithLong:navInfo.timeToFinalDestinationSeconds] + forKey:@"timeToFinalDestinationSeconds"]; } if (navInfo.currentStep != NULL) { - [obj setObject:[self getStepInfo:navInfo.currentStep] - forKey:@"currentStep"]; + [obj setObject:[self getStepInfo:navInfo.currentStep] forKey:@"currentStep"]; } NSMutableArray *steps = [[NSMutableArray alloc] init]; @@ -822,12 +776,9 @@ - (NSDictionary *)getStepInfo:(GMSNavigationStepInfo *)stepInfo { forKey:@"distanceFromPrevStepMeters"]; [obj setValue:[NSNumber numberWithInteger:stepInfo.timeFromPrevStepSeconds] forKey:@"timeFromPrevStepSeconds"]; - [obj setValue:[NSNumber numberWithInteger:stepInfo.drivingSide] - forKey:@"drivingSide"]; - [obj setValue:[NSNumber numberWithInteger:stepInfo.stepNumber] - forKey:@"stepNumber"]; - [obj setValue:[NSNumber numberWithInteger:stepInfo.maneuver] - forKey:@"maneuver"]; + [obj setValue:[NSNumber numberWithInteger:stepInfo.drivingSide] forKey:@"drivingSide"]; + [obj setValue:[NSNumber numberWithInteger:stepInfo.stepNumber] forKey:@"stepNumber"]; + [obj setValue:[NSNumber numberWithInteger:stepInfo.maneuver] forKey:@"maneuver"]; [obj setValue:stepInfo.exitNumber forKey:@"exitNumber"]; [obj setValue:stepInfo.fullRoadName forKey:@"fullRoadName"]; [obj setValue:stepInfo.fullInstructionText forKey:@"instruction"]; diff --git a/ios/react-native-navigation-sdk/NavView.h b/ios/react-native-navigation-sdk/NavView.h index 20c3b8d..3de7da9 100644 --- a/ios/react-native-navigation-sdk/NavView.h +++ b/ios/react-native-navigation-sdk/NavView.h @@ -14,10 +14,10 @@ * limitations under the License. */ -#import "INavigationViewCallback.h" #import #import #import +#import "INavigationViewCallback.h" @class NavViewController; diff --git a/ios/react-native-navigation-sdk/NavView.m b/ios/react-native-navigation-sdk/NavView.m index 69bae6e..9f8162f 100644 --- a/ios/react-native-navigation-sdk/NavView.m +++ b/ios/react-native-navigation-sdk/NavView.m @@ -26,7 +26,7 @@ @implementation NavView - (void)layoutSubviews { [super layoutSubviews]; if (self.superview) { - self.translatesAutoresizingMaskIntoConstraints = NO; // Disable auto-resizing mask + self.translatesAutoresizingMaskIntoConstraints = NO; // Disable auto-resizing mask [NSLayoutConstraint activateConstraints:@[ [self.leadingAnchor constraintEqualToAnchor:self.superview.leadingAnchor], [self.trailingAnchor constraintEqualToAnchor:self.superview.trailingAnchor], @@ -52,7 +52,7 @@ - (NavViewController *)initializeViewControllerWithStylingOptions:(NSDictionary [_viewController.view.topAnchor constraintEqualToAnchor:self.topAnchor], [_viewController.view.bottomAnchor constraintEqualToAnchor:self.bottomAnchor] ]]; - + return _viewController; } @@ -80,43 +80,38 @@ - (void)handleMapClick:(NSDictionary *)latLngMap { - (void)handleMarkerInfoWindowTapped:(GMSMarker *)marker { if (self.onMarkerInfoWindowTapped) { - self.onMarkerInfoWindowTapped( - [ObjectTranslationUtil transformMarkerToDictionary:marker]); + self.onMarkerInfoWindowTapped([ObjectTranslationUtil transformMarkerToDictionary:marker]); } } - (void)handleMarkerClick:(GMSMarker *)marker { if (self.onMarkerClick) { - self.onMarkerClick( - [ObjectTranslationUtil transformMarkerToDictionary:marker]); + self.onMarkerClick([ObjectTranslationUtil transformMarkerToDictionary:marker]); } } - (void)handlePolylineClick:(GMSPolyline *)polyline { if (self.onPolylineClick) { - self.onPolylineClick( - [ObjectTranslationUtil transformPolylineToDictionary:polyline]); + self.onPolylineClick([ObjectTranslationUtil transformPolylineToDictionary:polyline]); } } - (void)handlePolygonClick:(GMSPolygon *)polygon { if (self.onPolygonClick) { - self.onPolygonClick( - [ObjectTranslationUtil transformPolygonToDictionary:polygon]); + self.onPolygonClick([ObjectTranslationUtil transformPolygonToDictionary:polygon]); } } - (void)handleCircleClick:(GMSCircle *)circle { if (self.onCircleClick) { - self.onCircleClick( - [ObjectTranslationUtil transformCircleToDictionary:circle]); + self.onCircleClick([ObjectTranslationUtil transformCircleToDictionary:circle]); } } - (void)handleGroundOverlayClick:(GMSGroundOverlay *)groundOverlay { if (self.onGroundOverlayClick) { - self.onGroundOverlayClick([ObjectTranslationUtil - transformGroundOverlayToDictionary:groundOverlay]); + self.onGroundOverlayClick( + [ObjectTranslationUtil transformGroundOverlayToDictionary:groundOverlay]); } } diff --git a/ios/react-native-navigation-sdk/NavViewController.h b/ios/react-native-navigation-sdk/NavViewController.h index 406ba67..96a4978 100644 --- a/ios/react-native-navigation-sdk/NavViewController.h +++ b/ios/react-native-navigation-sdk/NavViewController.h @@ -14,15 +14,14 @@ * limitations under the License. */ +#import #import "INavigationViewCallback.h" #import "ObjectTranslationUtil.h" -#import @import GoogleNavigation; NS_ASSUME_NONNULL_BEGIN -@interface NavViewController - : UIViewController +@interface NavViewController : UIViewController @property(weak, nonatomic) id callbacks; typedef void (^RouteStatusCallback)(GMSRouteStatus routeStatus); @@ -66,16 +65,11 @@ typedef void (^OnArrayResult)(NSArray *_Nullable result); - (void)setMapStyle:(GMSMapStyle *)mapStyle; - (void)setMapType:(GMSMapViewType)mapType; - (void)clearMapView; -- (void)addGroundOverlay:(NSDictionary *)overlayOptions - result:(OnDictionaryResult)completionBlock; -- (void)addCircle:(NSDictionary *)circleOptions - result:(OnDictionaryResult)completionBlock; -- (void)addMarker:(NSDictionary *)markerOptions - result:(OnDictionaryResult)completionBlock; -- (void)addPolygon:(NSDictionary *)polygonOptions - result:(OnDictionaryResult)completionBlock; -- (void)addPolyline:(NSDictionary *)options - result:(OnDictionaryResult)completionBlock; +- (void)addGroundOverlay:(NSDictionary *)overlayOptions result:(OnDictionaryResult)completionBlock; +- (void)addCircle:(NSDictionary *)circleOptions result:(OnDictionaryResult)completionBlock; +- (void)addMarker:(NSDictionary *)markerOptions result:(OnDictionaryResult)completionBlock; +- (void)addPolygon:(NSDictionary *)polygonOptions result:(OnDictionaryResult)completionBlock; +- (void)addPolyline:(NSDictionary *)options result:(OnDictionaryResult)completionBlock; - (GMSMapView *)mapView; - (void)showRouteOverview; - (void)removeMarker:(NSString *)markerId; diff --git a/ios/react-native-navigation-sdk/NavViewController.m b/ios/react-native-navigation-sdk/NavViewController.m index baf55a1..6669380 100644 --- a/ios/react-native-navigation-sdk/NavViewController.m +++ b/ios/react-native-navigation-sdk/NavViewController.m @@ -15,10 +15,10 @@ */ #import "NavViewController.h" +#import #import "NavModule.h" #import "ObjectTranslationUtil.h" #import "UIColor+Util.h" -#import @import GoogleNavigation; @import UserNotifications; @@ -63,16 +63,13 @@ - (void)mapViewDidTapRecenterButton:(GMSMapView *)mapView { [self.callbacks handleRecenterButtonClick]; } -- (void)mapView:(GMSMapView *)mapView - didTapInfoWindowOfMarker:(GMSMarker *)marker { +- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker { [self.callbacks handleMarkerInfoWindowTapped:marker]; } -- (void)mapView:(GMSMapView *)mapView - didTapAtCoordinate:(CLLocationCoordinate2D)coordinate { +- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate { [self.callbacks - handleMapClick:[ObjectTranslationUtil - transformCoordinateToDictionary:coordinate]]; + handleMapClick:[ObjectTranslationUtil transformCoordinateToDictionary:coordinate]]; } - (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker { @@ -104,79 +101,66 @@ - (void)setStylingOptions:(nonnull NSDictionary *)stylingOptions { - (void)applyStylingOptions { if (_stylingOptions) { if (_stylingOptions[@"navigationHeaderPrimaryBackgroundColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderPrimaryBackgroundColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderPrimaryBackgroundColor"]; _mapView.settings.navigationHeaderPrimaryBackgroundColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderSecondaryBackgroundColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderSecondaryBackgroundColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderSecondaryBackgroundColor"]; _mapView.settings.navigationHeaderSecondaryBackgroundColor = [UIColor colorWithHexString:hexString]; } - if (_stylingOptions[@"navigationHeaderPrimaryBackgroundColorNightMode"] != - nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderPrimaryBackgroundColorNightMode"]; + if (_stylingOptions[@"navigationHeaderPrimaryBackgroundColorNightMode"] != nil) { + NSString *hexString = _stylingOptions[@"navigationHeaderPrimaryBackgroundColorNightMode"]; _mapView.settings.navigationHeaderPrimaryBackgroundColorNightMode = [UIColor colorWithHexString:hexString]; } - if (_stylingOptions[@"navigationHeaderSecondaryBackgroundColorNightMode"] != - nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderSecondaryBackgroundColorNightMode"]; + if (_stylingOptions[@"navigationHeaderSecondaryBackgroundColorNightMode"] != nil) { + NSString *hexString = _stylingOptions[@"navigationHeaderSecondaryBackgroundColorNightMode"]; _mapView.settings.navigationHeaderSecondaryBackgroundColorNightMode = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderLargeManeuverIconColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderLargeManeuverIconColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderLargeManeuverIconColor"]; _mapView.settings.navigationHeaderLargeManeuverIconColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderSmallManeuverIconColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderSmallManeuverIconColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderSmallManeuverIconColor"]; _mapView.settings.navigationHeaderSmallManeuverIconColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderGuidanceRecommendedLaneColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderGuidanceRecommendedLaneColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderGuidanceRecommendedLaneColor"]; _mapView.settings.navigationHeaderGuidanceRecommendedLaneColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderNextStepTextColor"] != nil) { NSString *hexString = _stylingOptions[@"navigationHeaderNextStepTextColor"]; - _mapView.settings.navigationHeaderNextStepTextColor = - [UIColor colorWithHexString:hexString]; + _mapView.settings.navigationHeaderNextStepTextColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderDistanceValueTextColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderDistanceValueTextColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderDistanceValueTextColor"]; _mapView.settings.navigationHeaderDistanceValueTextColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderDistanceUnitsTextColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderDistanceUnitsTextColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderDistanceUnitsTextColor"]; _mapView.settings.navigationHeaderDistanceUnitsTextColor = [UIColor colorWithHexString:hexString]; } if (_stylingOptions[@"navigationHeaderInstructionsTextColor"] != nil) { - NSString *hexString = - _stylingOptions[@"navigationHeaderInstructionsTextColor"]; + NSString *hexString = _stylingOptions[@"navigationHeaderInstructionsTextColor"]; _mapView.settings.navigationHeaderInstructionsTextColor = [UIColor colorWithHexString:hexString]; } @@ -184,10 +168,10 @@ - (void)applyStylingOptions { } - (void)setZoomLevel:(nonnull NSNumber *)level { - _mapView.camera = [GMSMutableCameraPosition - cameraWithLatitude:_mapView.myLocation.coordinate.latitude - longitude:_mapView.myLocation.coordinate.longitude - zoom:[level floatValue]]; + _mapView.camera = + [GMSMutableCameraPosition cameraWithLatitude:_mapView.myLocation.coordinate.latitude + longitude:_mapView.myLocation.coordinate.longitude + zoom:[level floatValue]]; } - (void)setNavigationUIEnabled:(BOOL)isEnabled { @@ -203,10 +187,7 @@ - (void)getCameraPosition:(OnDictionaryResult)completionBlock { map[@"tilt"] = @(cam.viewingAngle); map[@"zoom"] = @(cam.zoom); - map[@"target"] = @{ - @"lat" : @(cameraPosition.latitude), - @"lng" : @(cameraPosition.longitude) - }; + map[@"target"] = @{@"lat" : @(cameraPosition.latitude), @"lng" : @(cameraPosition.longitude)}; completionBlock(map); } @@ -215,8 +196,7 @@ - (void)getMyLocation:(OnDictionaryResult)completionBlock { CLLocation *userLocation = _mapView.myLocation; if (userLocation != nil) { - completionBlock( - [ObjectTranslationUtil transformCLLocationToDictionary:userLocation]); + completionBlock([ObjectTranslationUtil transformCLLocationToDictionary:userLocation]); } else { completionBlock(nil); } @@ -244,8 +224,7 @@ - (void)isMyLocationEnabled:(OnBooleanResult)completionBlock { - (void)moveCamera:(NSDictionary *)map { GMSMutableCameraPosition *position = [[GMSMutableCameraPosition alloc] init]; - position.target = - [ObjectTranslationUtil getLocationCoordinateFrom:map[@"target"]]; + position.target = [ObjectTranslationUtil getLocationCoordinateFrom:map[@"target"]]; position.zoom = [[map objectForKey:@"zoom"] floatValue]; position.bearing = [[map objectForKey:@"bearing"] doubleValue]; position.viewingAngle = [[map objectForKey:@"tilt"] doubleValue]; @@ -281,11 +260,9 @@ - (void)setMyLocationEnabled:(BOOL)isEnabled { - (void)setFollowingPerspective:(NSNumber *)index { if ([index isEqual:@1]) { - [_mapView - setFollowingPerspective:GMSNavigationCameraPerspectiveTopDownNorthUp]; + [_mapView setFollowingPerspective:GMSNavigationCameraPerspectiveTopDownNorthUp]; } else if ([index isEqual:@2]) { - [_mapView - setFollowingPerspective:GMSNavigationCameraPerspectiveTopDownHeadingUp]; + [_mapView setFollowingPerspective:GMSNavigationCameraPerspectiveTopDownHeadingUp]; } else { [_mapView setFollowingPerspective:GMSNavigationCameraPerspectiveTilted]; } @@ -314,8 +291,7 @@ - (void)preferredContentSizeDidChangeForChildContentContainer: } - (void)viewWillTransitionToSize:(CGSize)size - withTransitionCoordinator: - (nonnull id)coordinator { + withTransitionCoordinator:(nonnull id)coordinator { } - (void)setNavigationCallbacks:(nonnull id)fn { @@ -406,7 +382,7 @@ - (void)clearMapView { - (UIColor *)colorFromHexString:(NSString *)hexString { unsigned rgb = 0; NSScanner *scanner = [NSScanner scannerWithString:hexString]; - [scanner setScanLocation:1]; // bypass '#' character + [scanner setScanLocation:1]; // bypass '#' character [scanner scanHexInt:&rgb]; return [UIColor colorWithRed:((rgb & 0xFF0000) >> 16) / 255.0 green:((rgb & 0xFF00) >> 8) / 255.0 @@ -414,36 +390,28 @@ - (UIColor *)colorFromHexString:(NSString *)hexString { alpha:1.0]; } -- (void)addGroundOverlay:(NSDictionary *)overlayOptions - result:(OnDictionaryResult)completionBlock { +- (void)addGroundOverlay:(NSDictionary *)overlayOptions result:(OnDictionaryResult)completionBlock { NSDictionary *latLng = [overlayOptions objectForKey:@"location"]; - CLLocationCoordinate2D position = - [ObjectTranslationUtil getLocationCoordinateFrom:latLng]; + CLLocationCoordinate2D position = [ObjectTranslationUtil getLocationCoordinateFrom:latLng]; NSString *imgPath = [overlayOptions objectForKey:@"imgPath"]; - UIImage *icon = [UIImage imageNamed:imgPath]; // Assuming local asset + UIImage *icon = [UIImage imageNamed:imgPath]; // Assuming local asset CGFloat widthInMeters = [[overlayOptions objectForKey:@"width"] doubleValue]; - CGFloat heightInMeters = - [[overlayOptions objectForKey:@"height"] doubleValue]; + CGFloat heightInMeters = [[overlayOptions objectForKey:@"height"] doubleValue]; CLLocationCoordinate2D northeast = CLLocationCoordinate2DMake( position.latitude + (heightInMeters / 111111.0), - position.longitude + - (widthInMeters / (111111.0 * cos(position.latitude * M_PI / 180.0)))); + position.longitude + (widthInMeters / (111111.0 * cos(position.latitude * M_PI / 180.0)))); CLLocationCoordinate2D southwest = CLLocationCoordinate2DMake( position.latitude - (heightInMeters / 111111.0), - position.longitude - - (widthInMeters / (111111.0 * cos(position.latitude * M_PI / 180.0)))); - - GMSCoordinateBounds *overlayBounds = - [[GMSCoordinateBounds alloc] initWithCoordinate:southwest - coordinate:northeast]; - GMSGroundOverlay *overlay = - [GMSGroundOverlay groundOverlayWithBounds:overlayBounds icon:icon]; + position.longitude - (widthInMeters / (111111.0 * cos(position.latitude * M_PI / 180.0)))); + + GMSCoordinateBounds *overlayBounds = [[GMSCoordinateBounds alloc] initWithCoordinate:southwest + coordinate:northeast]; + GMSGroundOverlay *overlay = [GMSGroundOverlay groundOverlayWithBounds:overlayBounds icon:icon]; overlay.bearing = [[overlayOptions objectForKey:@"bearing"] floatValue]; - overlay.opacity = - 1.0 - [[overlayOptions objectForKey:@"transparency"] floatValue]; + overlay.opacity = 1.0 - [[overlayOptions objectForKey:@"transparency"] floatValue]; overlay.tappable = [[overlayOptions objectForKey:@"clickable"] boolValue]; overlay.userData = @[ [[NSUUID UUID] UUIDString] ]; @@ -457,26 +425,22 @@ - (void)addGroundOverlay:(NSDictionary *)overlayOptions [_groundOverlayList addObject:overlay]; - completionBlock( - [ObjectTranslationUtil transformGroundOverlayToDictionary:overlay]); + completionBlock([ObjectTranslationUtil transformGroundOverlayToDictionary:overlay]); } -- (void)addCircle:(NSDictionary *)circleOptions - result:(OnDictionaryResult)completionBlock { +- (void)addCircle:(NSDictionary *)circleOptions result:(OnDictionaryResult)completionBlock { NSDictionary *latLng = [circleOptions objectForKey:@"center"]; - CLLocationCoordinate2D center = - [ObjectTranslationUtil getLocationCoordinateFrom:latLng]; + CLLocationCoordinate2D center = [ObjectTranslationUtil getLocationCoordinateFrom:latLng]; - GMSCircle *circle = [GMSCircle - circleWithPosition:center - radius:[[circleOptions objectForKey:@"radius"] doubleValue]]; + GMSCircle *circle = + [GMSCircle circleWithPosition:center + radius:[[circleOptions objectForKey:@"radius"] doubleValue]]; circle.strokeWidth = [[circleOptions objectForKey:@"strokeWidth"] floatValue]; if (circleOptions[@"strokeColor"] != nil) { // Assuming strokeColor is a hex string - circle.strokeColor = - [self colorFromHexString:[circleOptions objectForKey:@"strokeColor"]]; + circle.strokeColor = [self colorFromHexString:[circleOptions objectForKey:@"strokeColor"]]; } NSString *fillColor = [circleOptions objectForKey:@"fillColor"]; @@ -500,8 +464,7 @@ - (void)addCircle:(NSDictionary *)circleOptions completionBlock([ObjectTranslationUtil transformCircleToDictionary:circle]); } -- (void)addMarker:(NSDictionary *)markerOptions - result:(OnDictionaryResult)completionBlock { +- (void)addMarker:(NSDictionary *)markerOptions result:(OnDictionaryResult)completionBlock { NSDictionary *position = [markerOptions objectForKey:@"position"]; CLLocationCoordinate2D coordinatePosition = [ObjectTranslationUtil getLocationCoordinateFrom:position]; @@ -523,18 +486,17 @@ - (void)addMarker:(NSDictionary *)markerOptions marker.map = _mapView; - if ([[markerOptions objectForKey:@"imgPath"] - isKindOfClass:[NSString class]]) { + if ([[markerOptions objectForKey:@"imgPath"] isKindOfClass:[NSString class]]) { NSString *imgPath = [markerOptions objectForKey:@"imgPath"]; if (imgPath) { - UIImage *icon = [UIImage imageNamed:imgPath]; // Assuming local asset + UIImage *icon = [UIImage imageNamed:imgPath]; // Assuming local asset marker.icon = icon; } } BOOL visible = [[markerOptions objectForKey:@"visible"] boolValue]; if (!visible) { - marker.map = nil; // Setting map to nil hides the marker + marker.map = nil; // Setting map to nil hides the marker } [_markerList addObject:marker]; @@ -542,10 +504,8 @@ - (void)addMarker:(NSDictionary *)markerOptions completionBlock([ObjectTranslationUtil transformMarkerToDictionary:marker]); } -- (void)addPolygon:(NSDictionary *)polygonOptions - result:(OnDictionaryResult)completionBlock { - GMSPath *path = - [ObjectTranslationUtil transformToPath:polygonOptions[@"points"]]; +- (void)addPolygon:(NSDictionary *)polygonOptions result:(OnDictionaryResult)completionBlock { + GMSPath *path = [ObjectTranslationUtil transformToPath:polygonOptions[@"points"]]; GMSPolygon *polygon = [GMSPolygon polygonWithPath:path]; @@ -572,8 +532,7 @@ - (void)addPolygon:(NSDictionary *)polygonOptions } if ([polygonOptions objectForKey:@"strokeWidth"]) { - polygon.strokeWidth = - [[polygonOptions objectForKey:@"strokeWidth"] floatValue]; + polygon.strokeWidth = [[polygonOptions objectForKey:@"strokeWidth"] floatValue]; } if ([polygonOptions objectForKey:@"geodesic"]) { @@ -596,21 +555,19 @@ - (void)addPolygon:(NSDictionary *)polygonOptions completionBlock([ObjectTranslationUtil transformPolygonToDictionary:polygon]); } -- (void)addPolyline:(NSDictionary *)options - result:(OnDictionaryResult)completionBlock { +- (void)addPolyline:(NSDictionary *)options result:(OnDictionaryResult)completionBlock { GMSPath *path = [ObjectTranslationUtil transformToPath:options[@"points"]]; GMSPolyline *polyline = [GMSPolyline polylineWithPath:path]; polyline.strokeWidth = [[options objectForKey:@"width"] floatValue]; - polyline.strokeColor = [self - colorFromHexString:[options objectForKey:@"color"]]; // Assuming color is + polyline.strokeColor = + [self colorFromHexString:[options objectForKey:@"color"]]; // Assuming color is // a hex string polyline.tappable = [[options objectForKey:@"clickable"] boolValue]; polyline.userData = @[ [[NSUUID UUID] UUIDString] ]; - if ([options objectForKey:@"visible"] != nil && - [[options objectForKey:@"visible"] boolValue]) { + if ([options objectForKey:@"visible"] != nil && [[options objectForKey:@"visible"] boolValue]) { polyline.map = _mapView; } else { polyline.map = nil; @@ -618,8 +575,7 @@ - (void)addPolyline:(NSDictionary *)options [_polylineList addObject:polyline]; - completionBlock( - [ObjectTranslationUtil transformPolylineToDictionary:polyline]); + completionBlock([ObjectTranslationUtil transformPolylineToDictionary:polyline]); } - (void)removeMarker:(NSString *)markerId { diff --git a/ios/react-native-navigation-sdk/NavViewModule.h b/ios/react-native-navigation-sdk/NavViewModule.h index 3252733..6894294 100644 --- a/ios/react-native-navigation-sdk/NavViewModule.h +++ b/ios/react-native-navigation-sdk/NavViewModule.h @@ -14,14 +14,13 @@ * limitations under the License. */ -#import "NavViewController.h" #import +#import "NavViewController.h" NS_ASSUME_NONNULL_BEGIN @interface NavViewModule : NSObject -@property(nonatomic, strong) - NSMutableDictionary *viewControllers; +@property(nonatomic, strong) NSMutableDictionary *viewControllers; - (void)attachViewsToNavigationSession:(GMSNavigationSession *)session; - (void)setTravelMode:(GMSNavigationTravelMode)travelMode; diff --git a/ios/react-native-navigation-sdk/NavViewModule.m b/ios/react-native-navigation-sdk/NavViewModule.m index b3831a0..e8bc85c 100644 --- a/ios/react-native-navigation-sdk/NavViewModule.m +++ b/ios/react-native-navigation-sdk/NavViewModule.m @@ -58,16 +58,16 @@ - (NavViewController *)getViewControllerForTag:(NSNumber *)reactTag { : (nonnull NSNumber *)reactTag resolver : (RCTPromiseResolveBlock)resolve rejecter : (RCTPromiseRejectBlock)reject) { - dispatch_async(dispatch_get_main_queue(), ^{ - NavViewController *viewController = [self getViewControllerForTag:reactTag]; - if (viewController) { - [viewController getCameraPosition:^(NSDictionary *result) { - resolve(result); - }]; - } else { - reject(@"no_view_controller", @"No viewController found", nil); - } - }); + dispatch_async(dispatch_get_main_queue(), ^{ + NavViewController *viewController = [self getViewControllerForTag:reactTag]; + if (viewController) { + [viewController getCameraPosition:^(NSDictionary *result) { + resolve(result); + }]; + } else { + reject(@"no_view_controller", @"No viewController found", nil); + } + }); } RCT_EXPORT_METHOD(getMyLocation diff --git a/ios/react-native-navigation-sdk/ObjectTranslationUtil.m b/ios/react-native-navigation-sdk/ObjectTranslationUtil.m index 4605ce4..940a279 100644 --- a/ios/react-native-navigation-sdk/ObjectTranslationUtil.m +++ b/ios/react-native-navigation-sdk/ObjectTranslationUtil.m @@ -19,30 +19,30 @@ @implementation ObjectTranslationUtil + (NSDictionary *)transformCoordinateToDictionary:(CLLocationCoordinate2D)coordinate { - return @{ - @"lat" : @(coordinate.latitude), - @"lng" : @(coordinate.longitude), - }; + return @{ + @"lat" : @(coordinate.latitude), + @"lng" : @(coordinate.longitude), + }; } + (NSDictionary *)transformNavigationWaypointToDictionary:(GMSNavigationWaypoint *)waypoint { - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"position"] = - [ObjectTranslationUtil transformCoordinateToDictionary:waypoint.coordinate]; - dictionary[@"preferredHeading"] = @(waypoint.preferredHeading); - dictionary[@"vehicleStopover"] = @(waypoint.vehicleStopover); - dictionary[@"preferSameSideOfRoad"] = @(waypoint.preferSameSideOfRoad); - - if (waypoint.title != nil) { - dictionary[@"title"] = waypoint.title; - } - - if (waypoint.placeID != nil) { - dictionary[@"placeId"] = waypoint.placeID; - } - - return dictionary; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"position"] = + [ObjectTranslationUtil transformCoordinateToDictionary:waypoint.coordinate]; + dictionary[@"preferredHeading"] = @(waypoint.preferredHeading); + dictionary[@"vehicleStopover"] = @(waypoint.vehicleStopover); + dictionary[@"preferSameSideOfRoad"] = @(waypoint.preferSameSideOfRoad); + + if (waypoint.title != nil) { + dictionary[@"title"] = waypoint.title; + } + + if (waypoint.placeID != nil) { + dictionary[@"placeId"] = waypoint.placeID; + } + + return dictionary; } + (NSDictionary *)transformCLLocationToDictionary:(CLLocation *)location { @@ -73,174 +73,174 @@ + (NSDictionary *)transformCLLocationToDictionary:(CLLocation *)location { } + (NSDictionary *)transformRouteSegmentToDictionary:(GMSRouteLeg *)routeLeg { - return @{ - @"destinationLatLng" : - [ObjectTranslationUtil transformCoordinateToDictionary:routeLeg.destinationCoordinate], - @"destinationWaypoint" : [ObjectTranslationUtil - transformNavigationWaypointToDictionary:routeLeg.destinationWaypoint], - @"segmentLatLngList" : [ObjectTranslationUtil transformGMSPathToArray:routeLeg.path], - }; + return @{ + @"destinationLatLng" : + [ObjectTranslationUtil transformCoordinateToDictionary:routeLeg.destinationCoordinate], + @"destinationWaypoint" : [ObjectTranslationUtil + transformNavigationWaypointToDictionary:routeLeg.destinationWaypoint], + @"segmentLatLngList" : [ObjectTranslationUtil transformGMSPathToArray:routeLeg.path], + }; } + (NSDictionary *)transformMarkerToDictionary:(GMSMarker *)marker { - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"position"] = [ObjectTranslationUtil transformCoordinateToDictionary:marker.position]; - dictionary[@"alpha"] = @(marker.opacity); - dictionary[@"rotation"] = @(marker.rotation); - dictionary[@"snippet"] = marker.snippet; - dictionary[@"zIndex"] = @(marker.zIndex); - - if (marker.title != nil) { - dictionary[@"title"] = marker.title; - } - - if ([ObjectTranslationUtil isIdOnUserData: marker.userData]) { - dictionary[@"id"] = marker.userData[0]; - } - - return dictionary; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"position"] = [ObjectTranslationUtil transformCoordinateToDictionary:marker.position]; + dictionary[@"alpha"] = @(marker.opacity); + dictionary[@"rotation"] = @(marker.rotation); + dictionary[@"snippet"] = marker.snippet; + dictionary[@"zIndex"] = @(marker.zIndex); + + if (marker.title != nil) { + dictionary[@"title"] = marker.title; + } + + if ([ObjectTranslationUtil isIdOnUserData:marker.userData]) { + dictionary[@"id"] = marker.userData[0]; + } + + return dictionary; } + (NSDictionary *)transformPolylineToDictionary:(GMSPolyline *)polyline { - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"points"] = [ObjectTranslationUtil transformGMSPathToArray:polyline.path]; - dictionary[@"width"] = @(polyline.strokeWidth); - dictionary[@"zIndex"] = @(polyline.zIndex); - - if (polyline.strokeColor != nil) { - dictionary[@"color"] = polyline.strokeColor; - } - - if ([ObjectTranslationUtil isIdOnUserData: polyline.userData]) { - dictionary[@"id"] = polyline.userData[0]; - } - - return dictionary; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"points"] = [ObjectTranslationUtil transformGMSPathToArray:polyline.path]; + dictionary[@"width"] = @(polyline.strokeWidth); + dictionary[@"zIndex"] = @(polyline.zIndex); + + if (polyline.strokeColor != nil) { + dictionary[@"color"] = polyline.strokeColor; + } + + if ([ObjectTranslationUtil isIdOnUserData:polyline.userData]) { + dictionary[@"id"] = polyline.userData[0]; + } + + return dictionary; } + (NSArray *)transformGMSPathToArray:(GMSPath *)path { - NSMutableArray *array = [[NSMutableArray alloc] init]; - - for (int j = 0; j < path.count; j++) { - CLLocationCoordinate2D coordinate = [path coordinateAtIndex:j]; - [array addObject:[ObjectTranslationUtil transformCoordinateToDictionary:coordinate]]; - } - - return array; + NSMutableArray *array = [[NSMutableArray alloc] init]; + + for (int j = 0; j < path.count; j++) { + CLLocationCoordinate2D coordinate = [path coordinateAtIndex:j]; + [array addObject:[ObjectTranslationUtil transformCoordinateToDictionary:coordinate]]; + } + + return array; } + (NSDictionary *)transformPolygonToDictionary:(GMSPolygon *)polygon { - NSMutableArray *holesArray = [[NSMutableArray alloc] init]; - // Each hole is a GMSPath (which is an array of coordinates), the output should be an array of - // arrays. - for (int j = 0; j < polygon.holes.count; j++) { - GMSPath *hole = polygon.holes[j]; - - [holesArray addObject:[ObjectTranslationUtil transformGMSPathToArray:hole]]; - } - - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"points"] = [ObjectTranslationUtil transformGMSPathToArray:polygon.path]; - dictionary[@"holes"] = holesArray; - dictionary[@"strokeWidth"] = @(polygon.strokeWidth); - dictionary[@"zIndex"] = @(polygon.zIndex); - - if ([ObjectTranslationUtil isIdOnUserData: polygon.userData]) { - dictionary[@"id"] = polygon.userData[0]; - } - - if (polygon.fillColor != nil) { - dictionary[@"fillColor"] = polygon.fillColor; - } - - if (polygon.strokeColor != nil) { - dictionary[@"strokeColor"] = polygon.strokeColor; - } - - dictionary[@"geodesic"] = @(polygon.geodesic); - - return dictionary; + NSMutableArray *holesArray = [[NSMutableArray alloc] init]; + // Each hole is a GMSPath (which is an array of coordinates), the output should be an array of + // arrays. + for (int j = 0; j < polygon.holes.count; j++) { + GMSPath *hole = polygon.holes[j]; + + [holesArray addObject:[ObjectTranslationUtil transformGMSPathToArray:hole]]; + } + + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"points"] = [ObjectTranslationUtil transformGMSPathToArray:polygon.path]; + dictionary[@"holes"] = holesArray; + dictionary[@"strokeWidth"] = @(polygon.strokeWidth); + dictionary[@"zIndex"] = @(polygon.zIndex); + + if ([ObjectTranslationUtil isIdOnUserData:polygon.userData]) { + dictionary[@"id"] = polygon.userData[0]; + } + + if (polygon.fillColor != nil) { + dictionary[@"fillColor"] = polygon.fillColor; + } + + if (polygon.strokeColor != nil) { + dictionary[@"strokeColor"] = polygon.strokeColor; + } + + dictionary[@"geodesic"] = @(polygon.geodesic); + + return dictionary; } + (NSDictionary *)transformCircleToDictionary:(GMSCircle *)circle { - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"center"] = [ObjectTranslationUtil transformCoordinateToDictionary:circle.position]; - dictionary[@"strokeWidth"] = @(circle.strokeWidth); - dictionary[@"radius"] = @(circle.radius); - dictionary[@"zIndex"] = @(circle.zIndex); - - if (circle.strokeColor != nil) { - dictionary[@"strokeColor"] = circle.strokeColor; - } - - if (circle.fillColor != nil) { - dictionary[@"fillColor"] = circle.fillColor; - } - - if ([ObjectTranslationUtil isIdOnUserData: circle.userData]) { - dictionary[@"id"] = circle.userData[0]; - } - - return dictionary; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"center"] = [ObjectTranslationUtil transformCoordinateToDictionary:circle.position]; + dictionary[@"strokeWidth"] = @(circle.strokeWidth); + dictionary[@"radius"] = @(circle.radius); + dictionary[@"zIndex"] = @(circle.zIndex); + + if (circle.strokeColor != nil) { + dictionary[@"strokeColor"] = circle.strokeColor; + } + + if (circle.fillColor != nil) { + dictionary[@"fillColor"] = circle.fillColor; + } + + if ([ObjectTranslationUtil isIdOnUserData:circle.userData]) { + dictionary[@"id"] = circle.userData[0]; + } + + return dictionary; } + (NSDictionary *)transformGroundOverlayToDictionary:(GMSGroundOverlay *)overlay { - NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; - - dictionary[@"position"] = - [ObjectTranslationUtil transformCoordinateToDictionary:overlay.position]; - dictionary[@"bounds"] = @{ - @"northEast" : [ObjectTranslationUtil transformCoordinateToDictionary:overlay.bounds.northEast], - @"southWest" : [ObjectTranslationUtil transformCoordinateToDictionary:overlay.bounds.southWest], - }; - - dictionary[@"bearing"] = @(overlay.bearing); - dictionary[@"transparency"] = @(overlay.opacity); - dictionary[@"zIndex"] = @(overlay.zIndex); - - if ([ObjectTranslationUtil isIdOnUserData: overlay.userData]) { - dictionary[@"id"] = overlay.userData[0]; - } - - return dictionary; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + + dictionary[@"position"] = + [ObjectTranslationUtil transformCoordinateToDictionary:overlay.position]; + dictionary[@"bounds"] = @{ + @"northEast" : [ObjectTranslationUtil transformCoordinateToDictionary:overlay.bounds.northEast], + @"southWest" : [ObjectTranslationUtil transformCoordinateToDictionary:overlay.bounds.southWest], + }; + + dictionary[@"bearing"] = @(overlay.bearing); + dictionary[@"transparency"] = @(overlay.opacity); + dictionary[@"zIndex"] = @(overlay.zIndex); + + if ([ObjectTranslationUtil isIdOnUserData:overlay.userData]) { + dictionary[@"id"] = overlay.userData[0]; + } + + return dictionary; } /** Converts an array of NSDictionary objects representing a LatLng into GMSPath. */ + (GMSPath *)transformToPath:(NSArray *)latLngs { - GMSMutablePath *path = [GMSMutablePath path]; - - for (NSDictionary *latLngDictionary in latLngs) { - [path addCoordinate:[ObjectTranslationUtil getLocationCoordinateFrom:latLngDictionary]]; - } - - return path; + GMSMutablePath *path = [GMSMutablePath path]; + + for (NSDictionary *latLngDictionary in latLngs) { + [path addCoordinate:[ObjectTranslationUtil getLocationCoordinateFrom:latLngDictionary]]; + } + + return path; } + (CLLocationCoordinate2D)getLocationCoordinateFrom:(NSDictionary *)latLngMap { - double latitude = [[latLngMap objectForKey:@"lat"] doubleValue]; - double longitude = [[latLngMap objectForKey:@"lng"] doubleValue]; - - return CLLocationCoordinate2DMake(latitude, longitude); + double latitude = [[latLngMap objectForKey:@"lat"] doubleValue]; + double longitude = [[latLngMap objectForKey:@"lng"] doubleValue]; + + return CLLocationCoordinate2DMake(latitude, longitude); } + (BOOL)isIdOnUserData:(nullable id)userData { - if (userData == nil) { - return NO; - } - - if (![userData isKindOfClass:[NSArray class]]) { - return NO; - } - - if (userData[0] == nil || ![userData[0] isKindOfClass:[NSString class]]) { - return NO; - } - - return YES; + if (userData == nil) { + return NO; + } + + if (![userData isKindOfClass:[NSArray class]]) { + return NO; + } + + if (userData[0] == nil || ![userData[0] isKindOfClass:[NSString class]]) { + return NO; + } + + return YES; } @end diff --git a/ios/react-native-navigation-sdk/RCTNavViewManager.m b/ios/react-native-navigation-sdk/RCTNavViewManager.m index 07062da..e869822 100644 --- a/ios/react-native-navigation-sdk/RCTNavViewManager.m +++ b/ios/react-native-navigation-sdk/RCTNavViewManager.m @@ -15,11 +15,11 @@ */ #import "RCTNavViewManager.h" +#import #import "NavView.h" #import "NavViewController.h" #import "NavViewModule.h" #import "ObjectTranslationUtil.h" -#import @implementation RCTNavViewManager static NSMutableDictionary *_viewControllers; @@ -58,8 +58,7 @@ - (NavViewController *)getViewControllerForTag:(NSNumber *)reactTag { return _viewControllers[reactTag]; } -- (void)registerViewController:(NavViewController *)viewController - forTag:(NSNumber *)reactTag { +- (void)registerViewController:(NavViewController *)viewController forTag:(NSNumber *)reactTag { @synchronized(_viewControllers) { _viewControllers[reactTag] = viewController; } @@ -75,8 +74,7 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { : (nonnull NSNumber *)reactTag stylingOptions : (NSDictionary *)stylingOptions) { [self.bridge.uiManager - addUIBlock:^(RCTUIManager *uiManager, - NSDictionary *viewRegistry) { + addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { NavView *view = (NavView *)viewRegistry[reactTag]; if (!view || ![view isKindOfClass:[NavView class]]) { RCTLogError(@"Cannot find NativeView with tag #%@", reactTag); @@ -92,16 +90,14 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { RCT_EXPORT_METHOD(deleteFragment : (nonnull NSNumber *)reactTag) { [self.bridge.uiManager - addUIBlock:^(RCTUIManager *uiManager, - NSDictionary *viewRegistry) { + addUIBlock:^(RCTUIManager *uiManager, NSDictionary *viewRegistry) { NavView *view = (NavView *)viewRegistry[reactTag]; if (!view || ![view isKindOfClass:[NavView class]]) { RCTLogError(@"Cannot find NativeView with tag #%@", reactTag); return; } - NavViewController *viewController = - [self getViewControllerForTag:reactTag]; + NavViewController *viewController = [self getViewControllerForTag:reactTag]; if (viewController) { [view removeReactSubview:viewController.view]; [self unregisterViewControllerForTag:reactTag]; @@ -145,9 +141,7 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setNightMode - : (nonnull NSNumber *)reactTag index - : (nonnull NSNumber *)index) { +RCT_EXPORT_METHOD(setNightMode : (nonnull NSNumber *)reactTag index : (nonnull NSNumber *)index) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setNightMode:index]; @@ -181,45 +175,35 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setZoomLevel - : (nonnull NSNumber *)reactTag level - : (nonnull NSNumber *)level) { +RCT_EXPORT_METHOD(setZoomLevel : (nonnull NSNumber *)reactTag level : (nonnull NSNumber *)level) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setZoomLevel:level]; }); } -RCT_EXPORT_METHOD(removeMarker - : (nonnull NSNumber *)reactTag params - : (NSString *)markerId) { +RCT_EXPORT_METHOD(removeMarker : (nonnull NSNumber *)reactTag params : (NSString *)markerId) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController removeMarker:markerId]; }); } -RCT_EXPORT_METHOD(removePolyline - : (nonnull NSNumber *)reactTag params - : (NSString *)polylineId) { +RCT_EXPORT_METHOD(removePolyline : (nonnull NSNumber *)reactTag params : (NSString *)polylineId) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController removePolyline:polylineId]; }); } -RCT_EXPORT_METHOD(removePolygon - : (nonnull NSNumber *)reactTag params - : (NSString *)polygonId) { +RCT_EXPORT_METHOD(removePolygon : (nonnull NSNumber *)reactTag params : (NSString *)polygonId) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController removePolygon:polygonId]; }); } -RCT_EXPORT_METHOD(removeCircle - : (nonnull NSNumber *)reactTag params - : (NSString *)circleId) { +RCT_EXPORT_METHOD(removeCircle : (nonnull NSNumber *)reactTag params : (NSString *)circleId) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController removeCircle:circleId]; @@ -243,27 +227,21 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { } // MAPS SDK -RCT_EXPORT_METHOD(setIndoorEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setIndoorEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setIndoorEnabled:isEnabled]; }); } -RCT_EXPORT_METHOD(setTrafficEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setTrafficEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setTrafficEnabled:isEnabled]; }); } -RCT_EXPORT_METHOD(setCompassEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setCompassEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setCompassEnabled:isEnabled]; @@ -279,9 +257,7 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setMyLocationEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setMyLocationEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setMyLocationEnabled:isEnabled]; @@ -333,9 +309,7 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setBuildingsEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setBuildingsEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setBuildingsEnabled:isEnabled]; @@ -351,18 +325,14 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setHeaderEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setHeaderEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setHeaderEnabled:isEnabled]; }); } -RCT_EXPORT_METHOD(setFooterEnabled - : (nonnull NSNumber *)reactTag isEnabled - : (BOOL)isEnabled) { +RCT_EXPORT_METHOD(setFooterEnabled : (nonnull NSNumber *)reactTag isEnabled : (BOOL)isEnabled) { dispatch_async(dispatch_get_main_queue(), ^{ NavViewController *viewController = [self getViewControllerForTag:reactTag]; [viewController setFooterEnabled:isEnabled]; @@ -397,15 +367,12 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { : (RCTResponseSenderBlock)debugCallback) { dispatch_async(dispatch_get_main_queue(), ^{ NSError *error; - GMSMapStyle *mapStyle = [GMSMapStyle styleWithJSONString:jsonStyleString - error:&error]; + GMSMapStyle *mapStyle = [GMSMapStyle styleWithJSONString:jsonStyleString error:&error]; if (!mapStyle) { // Send error message through debugCallback instead of logging it debugCallback(@[ [NSString - stringWithFormat: - @"One or more of the map styles failed to load. Error: %@", - error] ]); + stringWithFormat:@"One or more of the map styles failed to load. Error: %@", error] ]); return; } @@ -421,27 +388,25 @@ - (void)unregisterViewControllerForTag:(NSNumber *)reactTag { }); } -RCT_EXPORT_METHOD(setMapType - : (nonnull NSNumber *)reactTag mapType - : (NSInteger)mapType) { +RCT_EXPORT_METHOD(setMapType : (nonnull NSNumber *)reactTag mapType : (NSInteger)mapType) { dispatch_async(dispatch_get_main_queue(), ^{ GMSMapViewType mapViewType; switch (mapType) { - case 1: - mapViewType = kGMSTypeNormal; - break; - case 2: - mapViewType = kGMSTypeSatellite; - break; - case 3: - mapViewType = kGMSTypeTerrain; - break; - case 4: - mapViewType = kGMSTypeHybrid; - break; - default: - mapViewType = kGMSTypeNone; - break; + case 1: + mapViewType = kGMSTypeNormal; + break; + case 2: + mapViewType = kGMSTypeSatellite; + break; + case 3: + mapViewType = kGMSTypeTerrain; + break; + case 4: + mapViewType = kGMSTypeHybrid; + break; + default: + mapViewType = kGMSTypeNone; + break; } NavViewController *viewController = [self getViewControllerForTag:reactTag]; diff --git a/ios/react-native-navigation-sdk/UIColor+Util.m b/ios/react-native-navigation-sdk/UIColor+Util.m index 0229025..2b65e18 100644 --- a/ios/react-native-navigation-sdk/UIColor+Util.m +++ b/ios/react-native-navigation-sdk/UIColor+Util.m @@ -19,53 +19,53 @@ @implementation UIColor (HexString) + (UIColor *)colorWithHexString:(NSString *)hexString { - NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" - withString:@""] uppercaseString]; - CGFloat alpha, red, blue, green; - - switch ([colorString length]) { - case 3: // #RGB - alpha = 1.0f; - red = [self colorComponentFrom:colorString start:0 length:1]; - green = [self colorComponentFrom:colorString start:1 length:1]; - blue = [self colorComponentFrom:colorString start:2 length:1]; - break; - case 4: // #ARGB - alpha = [self colorComponentFrom:colorString start:0 length:1]; - red = [self colorComponentFrom:colorString start:1 length:1]; - green = [self colorComponentFrom:colorString start:2 length:1]; - blue = [self colorComponentFrom:colorString start:3 length:1]; - break; - case 6: // #RRGGBB - alpha = 1.0f; - red = [self colorComponentFrom:colorString start:0 length:2]; - green = [self colorComponentFrom:colorString start:2 length:2]; - blue = [self colorComponentFrom:colorString start:4 length:2]; - break; - case 8: // #AARRGGBB - alpha = [self colorComponentFrom:colorString start:0 length:2]; - red = [self colorComponentFrom:colorString start:2 length:2]; - green = [self colorComponentFrom:colorString start:4 length:2]; - blue = [self colorComponentFrom:colorString start:6 length:2]; - break; - default: - [NSException raise:@"Invalid color value" - format:@"Color value %@ is invalid. It should be a hex value of the form #RBG, " - @"#ARGB, #RRGGBB, or #AARRGGBB", - hexString]; - break; - } - return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; + NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" + withString:@""] uppercaseString]; + CGFloat alpha, red, blue, green; + + switch ([colorString length]) { + case 3: // #RGB + alpha = 1.0f; + red = [self colorComponentFrom:colorString start:0 length:1]; + green = [self colorComponentFrom:colorString start:1 length:1]; + blue = [self colorComponentFrom:colorString start:2 length:1]; + break; + case 4: // #ARGB + alpha = [self colorComponentFrom:colorString start:0 length:1]; + red = [self colorComponentFrom:colorString start:1 length:1]; + green = [self colorComponentFrom:colorString start:2 length:1]; + blue = [self colorComponentFrom:colorString start:3 length:1]; + break; + case 6: // #RRGGBB + alpha = 1.0f; + red = [self colorComponentFrom:colorString start:0 length:2]; + green = [self colorComponentFrom:colorString start:2 length:2]; + blue = [self colorComponentFrom:colorString start:4 length:2]; + break; + case 8: // #AARRGGBB + alpha = [self colorComponentFrom:colorString start:0 length:2]; + red = [self colorComponentFrom:colorString start:2 length:2]; + green = [self colorComponentFrom:colorString start:4 length:2]; + blue = [self colorComponentFrom:colorString start:6 length:2]; + break; + default: + [NSException raise:@"Invalid color value" + format:@"Color value %@ is invalid. It should be a hex value of the form #RBG, " + @"#ARGB, #RRGGBB, or #AARRGGBB", + hexString]; + break; + } + return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } #pragma mark - Helper Methods + (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length { - NSString *substring = [string substringWithRange:NSMakeRange(start, length)]; - NSString *fullHex = - length == 2 ? substring : [NSString stringWithFormat:@"%@%@", substring, substring]; - unsigned hexComponent; - [[NSScanner scannerWithString:fullHex] scanHexInt:&hexComponent]; - return hexComponent / 255.0; + NSString *substring = [string substringWithRange:NSMakeRange(start, length)]; + NSString *fullHex = + length == 2 ? substring : [NSString stringWithFormat:@"%@%@", substring, substring]; + unsigned hexComponent; + [[NSScanner scannerWithString:fullHex] scanHexInt:&hexComponent]; + return hexComponent / 255.0; } @end diff --git a/lefthook.yml b/lefthook.yml index 936ecff..6a073a7 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -15,7 +15,14 @@ pre-commit: parallel: true commands: + format-objc: + runner: sh + run: ./scripts/format-objc.sh --check + format-java: + runner: sh + run: ./scripts/format-java.sh --check license-check: + runner: sh run: ./scripts/addlicense.sh --check lint: glob: '*.{js,ts,jsx,tsx}' diff --git a/scripts/addlicense.sh b/scripts/addlicense.sh index c309a94..7751d21 100755 --- a/scripts/addlicense.sh +++ b/scripts/addlicense.sh @@ -1,3 +1,4 @@ +#!/bin/sh # Copyright 2024 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - addlicense -f header_template.txt $@ \ --ignore "**/Pods/**" \ --ignore "**/node_modules/**" \ @@ -24,4 +24,4 @@ addlicense -f header_template.txt $@ \ --ignore "lib/**" \ --ignore "coverage/**" \ --ignore ".yarn/**" \ - . \ No newline at end of file + . diff --git a/scripts/format-java.sh b/scripts/format-java.sh new file mode 100755 index 0000000..ab8df7d --- /dev/null +++ b/scripts/format-java.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Script to format or check formatting for Java files in /android and /example/android + +if [ "$1" = "--check" ]; then + find android/src example/android/app/src -name "*.java" | xargs google-java-format --dry-run --set-exit-if-changed +else + find android/src example/android/app/src -name "*.java" | xargs google-java-format -i +fi diff --git a/scripts/format-objc.sh b/scripts/format-objc.sh new file mode 100755 index 0000000..e7f6d12 --- /dev/null +++ b/scripts/format-objc.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Script to format or check formatting for Objective-C files in /ios and /example/ios + +if [ "$1" = "--check" ]; then + find ios example/ios/SampleApp -name "*.m" -o -name "*.h" | xargs clang-format -style=Google --dry-run -Werror +else + find ios example/ios/SampleApp -name "*.m" -o -name "*.h" | xargs clang-format -style=Google -i +fi