Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,8 +311,10 @@ axis shows more than the region asks for.

Durations are in milliseconds, for `animateCamera` and `animateToRegion`
alike, as in react-native-maps. Both default to `250`, and `0` moves the camera
without animating. Up to 1.2.1 `animateCamera` took seconds, so multiply a
duration passed to it by 1000 when upgrading.
without animating, as does a negative duration or one that is not a finite
number. Releases up to and including 1.2.1 take `animateCamera` durations in
seconds; 2.0.0 is the first release that takes milliseconds, so multiply a
duration passed to it by 1000 when upgrading from 1.2.1 or earlier.

#### When the ref is usable

Expand Down Expand Up @@ -367,8 +369,10 @@ read `getVisibleRegion()` or `getCamera()` after the `await` when that matters.
(On Apple Maps a gesture cannot cut `animateCamera` or `animateToRegion` short:
the map ignores touches until the animation ends.)

Pass `fitToCoordinates`' `animated` argument explicitly: left out, iOS animates
the fit and Android jumps to it.
`fitToCoordinates` animates unless `animated` is `false`, on every provider.

> **Behavior change in 2.0.0:** on Android, `fitToCoordinates` without
> `animated` used to jump to the fit. It now animates, as on iOS.

> **Behavior change after 1.2.1:** these promises used to resolve as soon as the
> animation started, so `await` returned with the camera still at its old position.
Expand Down
118 changes: 113 additions & 5 deletions example/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
import {
APPLE_POI_DETAILS_DEFAULT_PRESENTATION,
APPLE_POI_DETAILS_SCENARIO_ID,
CAMERA_TIMING_SCENARIO_ID,
MAP_SCENARIOS,
type MapScenario,
createApplePoiDetailsScenario,
Expand All @@ -63,6 +64,7 @@ import {
} from './examples';

const MAP_TYPES: MapType[] = ['standard', 'satellite', 'hybrid'];
const CAMERA_TIMING_DURATIONS = [250, 2000];
type SupportedExampleProvider = Extract<MapProvider, 'apple' | 'google'>;
type AnimationOptionId = 'system' | 'fade' | 'fade-scale' | 'none';

Expand Down Expand Up @@ -318,6 +320,8 @@ type ScenarioDockProps = {
onCycleCustomMarkerRotation: () => void;
onToggleCustomMarkerFlat: () => void;
onCycleApplePoiDetailMode: () => void;
onTimeAnimateCamera: (duration: number) => void;
onTimeDefaultFit: () => void;
};

const ScenarioDock = memo(function ScenarioDock({
Expand All @@ -341,6 +345,8 @@ const ScenarioDock = memo(function ScenarioDock({
onCycleCustomMarkerRotation,
onToggleCustomMarkerFlat,
onCycleApplePoiDetailMode,
onTimeAnimateCamera,
onTimeDefaultFit,
}: ScenarioDockProps) {
const applePoiDetailPresentation =
scenario.advanced?.applePoiDetailPresentation;
Expand Down Expand Up @@ -483,6 +489,28 @@ const ScenarioDock = memo(function ScenarioDock({
</View>
) : null}

{scenario.id === CAMERA_TIMING_SCENARIO_ID ? (
<View style={styles.actionRow}>
{CAMERA_TIMING_DURATIONS.map((duration) => (
<ScalePressable
key={duration}
onPress={() => onTimeAnimateCamera(duration)}
style={styles.actionButton}
>
<Text style={styles.actionButtonIcon}>↻</Text>
<Text style={styles.actionButtonText}>{duration} ms</Text>
</ScalePressable>
))}
<ScalePressable
onPress={onTimeDefaultFit}
style={[styles.actionButton, styles.actionButtonAccent]}
>
<Text style={styles.actionButtonIcon}>⤢</Text>
<Text style={styles.actionButtonText}>Fit</Text>
</ScalePressable>
</View>
) : null}

{applePoiDetailPresentation != null ? (
<View style={styles.actionRow}>
<ScalePressable
Expand Down Expand Up @@ -811,6 +839,77 @@ export default function App() {
?.catch(() => {});
}, [scenario]);

// A timing promise settles after the scene changed when the old map is
// released; its result belongs to that scene, not the one on screen.
const sceneKey = mapSceneKey(scenario, animationOption, provider);
const sceneKeyRef = useRef(sceneKey);
useEffect(() => {
sceneKeyRef.current = sceneKey;
}, [sceneKey]);
const timeCameraPromise = useCallback(
(label: string, move: () => Promise<void> | undefined) => {
const startedIn = sceneKeyRef.current;
const startedAt = Date.now();
const report = (result: string) => {
if (sceneKeyRef.current === startedIn) {
setStatus(`${label} · ${result}`);
}
};
move()
?.then(() => report(`${Date.now() - startedAt} ms`))
.catch((error: unknown) => report(String(error)));
},
[],
);

const handleTimeAnimateCamera = useCallback(
async (duration: number) => {
// Zoom away from wherever the camera is, so every press moves the map
// and no other button can turn it into a no-op.
const map = mapRef.current;
const startedIn = sceneKeyRef.current;
if (map == null) {
return;
}
let camera;
try {
camera = await map.getCamera();
} catch {
return;
}
// The scene may have changed while the camera was read; the replacement
// map must not be moved to the old scenario.
if (mapRef.current !== map || sceneKeyRef.current !== startedIn) {
return;
}
timeCameraPromise(`animateCamera ${duration} ms`, () =>
map.animateCamera(
{
center: {
latitude: scenario.region.latitude,
longitude: scenario.region.longitude,
},
zoom: (camera.zoom ?? 0) >= 11 ? 9 : 13,
heading: 0,
pitch: 0,
},
duration,
),
);
},
[scenario, timeCameraPromise],
);

const handleTimeDefaultFit = useCallback(() => {
// No `animated` argument: the call under test is the default.
timeCameraPromise('fitToCoordinates', () =>
mapRef.current?.fitToCoordinates(
(scenario.markers ?? []).map((marker) => marker.coordinate),
mapPadding,
),
);
}, [scenario, mapPadding, timeCameraPromise]);

const handleGetCamera = useCallback(async () => {
try {
const camera = await mapRef.current?.getCamera();
Expand Down Expand Up @@ -968,25 +1067,32 @@ export default function App() {
);
}, []);

// The camera timing results are the point of that scenario; do not bury them.
const reportsRegionChanges = scenario.id !== CAMERA_TIMING_SCENARIO_ID;

const handleRegionChange = useCallback(
(region: Region, details: RegionChangeDetails) => {
setStatus(`Region start · ${regionLabel(region, details)}`);
if (reportsRegionChanges) {
setStatus(`Region start · ${regionLabel(region, details)}`);
}
},
[],
[reportsRegionChanges],
);

const handleRegionChangeComplete = useCallback(
(region: Region, details: RegionChangeDetails) => {
setStatus(`Region complete · ${regionLabel(region, details)}`);
if (reportsRegionChanges) {
setStatus(`Region complete · ${regionLabel(region, details)}`);
}
},
[],
[reportsRegionChanges],
);

return (
<View style={styles.container}>
<MapScene
ref={mapRef}
key={mapSceneKey(scenario, animationOption, provider)}
key={sceneKey}
scenario={scenario}
provider={provider}
mapType={MAP_TYPES[mapTypeIndex]}
Expand Down Expand Up @@ -1033,6 +1139,8 @@ export default function App() {
onCycleCustomMarkerRotation={cycleCustomMarkerRotation}
onToggleCustomMarkerFlat={toggleCustomMarkerFlat}
onCycleApplePoiDetailMode={cycleApplePoiDetailMode}
onTimeAnimateCamera={handleTimeAnimateCamera}
onTimeDefaultFit={handleTimeDefaultFit}
/>
<StatusBar style="light" />
</View>
Expand Down
38 changes: 38 additions & 0 deletions example/examples/cameraTiming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { MapScenario } from './types';

export const CAMERA_TIMING_SCENARIO_ID = 'camera-timing';

/**
* Buttons for `animateCamera` at 250 ms and 2000 ms and for `fitToCoordinates`
* without `animated`, so iOS and Android can be compared side by side. The
* status header reports how long each promise took to settle.
*/
export const cameraTimingScenario: MapScenario = {
id: CAMERA_TIMING_SCENARIO_ID,
name: 'Camera timing',
description:
'animateCamera at 250 ms and 2000 ms, and fitToCoordinates without animated',
region: {
latitude: 52.2297,
longitude: 21.0122,
latitudeDelta: 0.06,
longitudeDelta: 0.06,
},
markers: [
{
id: 'gdansk',
coordinate: { latitude: 54.352, longitude: 18.6466 },
title: 'Gdańsk',
},
{
id: 'szczecin',
coordinate: { latitude: 53.4285, longitude: 14.5528 },
title: 'Szczecin',
},
{
id: 'rzeszow',
coordinate: { latitude: 50.0413, longitude: 21.999 },
title: 'Rzeszów',
},
],
};
6 changes: 6 additions & 0 deletions example/examples/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { advancedFeaturesScenario } from './advancedFeatures';
import { allOverlaysScenario } from './allOverlays';
import {
CAMERA_TIMING_SCENARIO_ID,
cameraTimingScenario,
} from './cameraTiming';
import {
APPLE_POI_DETAILS_DEFAULT_PRESENTATION,
APPLE_POI_DETAILS_SCENARIO_ID,
Expand All @@ -24,6 +28,7 @@ export type { MapScenario } from './types';
export {
APPLE_POI_DETAILS_DEFAULT_PRESENTATION,
APPLE_POI_DETAILS_SCENARIO_ID,
CAMERA_TIMING_SCENARIO_ID,
createApplePoiDetailsScenario,
createCustomMarkerImagesScenario,
createScenarioOverlayProps,
Expand All @@ -41,4 +46,5 @@ export const MAP_SCENARIOS: MapScenario[] = [
advancedFeaturesScenario,
applePoiDetailsScenario,
mountEffectCameraScenario,
cameraTimingScenario,
];
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ internal const val DEFAULT_CAMERA_ANIMATION_DURATION_MS = 250.0

/**
* The duration `MapViewRef` passes, in milliseconds, as the whole number the SDK takes. Anything
* under one millisecond - 0, a negative value or `NaN` - comes back as 0 or less, which callers
* treat as a jump: `GoogleMap.animateCamera` throws for a duration that is not positive.
* under one millisecond - 0, a negative value or `NaN` - and infinity come back as 0 or less,
* which callers treat as a jump: `GoogleMap.animateCamera` throws for a duration that is not
* positive. The Swift `cameraAnimationSeconds(fromMilliseconds:)` does the same for iOS.
*/
internal fun cameraAnimationDurationMs(duration: Double?): Int = (duration ?: DEFAULT_CAMERA_ANIMATION_DURATION_MS).toInt()
internal fun cameraAnimationDurationMs(duration: Double?): Int {
val durationMs = duration ?: DEFAULT_CAMERA_ANIMATION_DURATION_MS
return if (durationMs.isFinite()) durationMs.toInt() else 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ class GoogleMapProviderAdapter(
view.height,
) ?: bounds
val update = CameraUpdateFactory.newLatLngBounds(target, 0)
if (animated == true) {
if (animated ?: true) {
map.animateCamera(update, cameraAnimations.callback(onEnd))
} else {
map.moveCamera(update)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,10 @@ class CameraAnimationDurationTest {
assertEquals(0, cameraAnimationDurationMs(Double.NaN))
assertTrue(cameraAnimationDurationMs(-100.0) <= 0)
}

@Test
fun jumpsForAnInfiniteDuration() {
assertEquals(0, cameraAnimationDurationMs(Double.POSITIVE_INFINITY))
assertEquals(0, cameraAnimationDurationMs(Double.NEGATIVE_INFINITY))
}
}
15 changes: 6 additions & 9 deletions package/ios/AppleMapProviderAdapter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ final class AppleMapProviderAdapter: MapProviderAdapter {
/// MapKit animates `setVisibleMapRect` over a duration it does not publish. This is
/// only the watchdog's guess at it, not a duration handed to MapKit.
private static let fitAnimationDuration: TimeInterval = 0.3
private static let defaultAnimationDuration: TimeInterval = 0.25

private let mapViewDelegate = HybridMapViewDelegate()
private let cameraMoves = CameraMoveTracker()
Expand Down Expand Up @@ -246,16 +245,15 @@ final class AppleMapProviderAdapter: MapProviderAdapter {
return Promise.resolved()
}

func animateCamera(camera: Camera, duration: TimeInterval?) throws -> Promise<Void> {
let animationDuration = duration ?? Self.defaultAnimationDuration
func animateCamera(camera: Camera, duration: TimeInterval) throws -> Promise<Void> {
let promise = Promise<Void>()
trackAnimation(settling: promise, duration: animationDuration) { completion in
updateMapCamera(camera, animated: true, duration: animationDuration, completion: completion)
trackAnimation(settling: promise, duration: duration) { completion in
updateMapCamera(camera, animated: true, duration: duration, completion: completion)
}
return promise
}

func animateToRegion(region: Region, duration: TimeInterval?) throws -> Promise<Void> {
func animateToRegion(region: Region, duration: TimeInterval) throws -> Promise<Void> {
// `setRegion` raises an NSException Swift cannot catch - see `applyRegion`.
guard region.isValid else {
return Promise.resolved()
Expand All @@ -267,17 +265,16 @@ final class AppleMapProviderAdapter: MapProviderAdapter {
// honours the animation's duration at any distance, so the region goes in
// as the camera `setRegion` would pick for it - which takes a map with a
// size.
let animationDuration = duration ?? Self.defaultAnimationDuration
let promise = Promise<Void>()
whenLaidOut(rejecting: promise) { [weak self] in
guard let self else {
return
}
self.trackAnimation(settling: promise, duration: animationDuration) { completion in
self.trackAnimation(settling: promise, duration: duration) { completion in
self.moveMapCamera(
to: self.view.camera(framing: region.toMKCoordinateRegion()),
animated: true,
duration: animationDuration,
duration: duration,
completion: completion
)
}
Expand Down
16 changes: 16 additions & 0 deletions package/ios/Camera/CameraAnimationDuration.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Foundation

/// The duration a camera animation takes when the caller passes none, in milliseconds.
let defaultCameraAnimationDurationMilliseconds: Double = 250

/// The duration `MapViewRef` passes, in milliseconds, as the seconds UIKit and Core
/// Animation take. Anything that is not a finite number greater than 0 - a negative
/// value, `NaN` or infinity - comes back as 0, which the adapters treat as a jump. The
/// Kotlin `cameraAnimationDurationMs` gives Android the same default.
func cameraAnimationSeconds(fromMilliseconds milliseconds: Double?) -> TimeInterval {
let milliseconds = milliseconds ?? defaultCameraAnimationDurationMilliseconds
guard milliseconds.isFinite, milliseconds > 0 else {
return 0
}
return milliseconds / 1000
}
Loading
Loading