Repository navigation
fix(ios): send the current camera when onCameraChanged is registered - #4430
Open
aderiushev wants to merge 1 commit into
Open
aderiushev wants to merge 1 commit into
aderiushev wants to merge 1 commit into
Conversation
mfazekas
requested changes
Nov 2, 2026
mfazekas
left a comment
Contributor
There was a problem hiding this comment.
Thanks, this reproduces cleanly. On main (iOS sim, RN 0.84.1, new arch), attaching onCameraChanged after the map settled gave no event until the camera moved, and with 3 s of JS busy work during mount 10 of 10 runs got no camera at all. With this PR the late attach gets exactly one event with the current camera (zoom 12.00, isGestureActive: false, same payload keys as a normal event). The busy mount gets exactly one event in 10 of 10 runs. Five re-renders with an inline callback send nothing extra, normal camera changes are unaffected, and with onRegionIsChanging registered no one-shot is sent.
A few requests before merging:
- Please move the event construction into a small helper (e.g.
sendCameraChanged()) and use it from bothapplyOnMapChangeand here, so the one-shot can't drift from the regularcameraChangedpayload. withMapViewdoesn't wait here:RNMBXMapViewModule.setHandledMapChangedEventsalready rejects when the view has no map, and it runs on the main thread with_mapViewset, so the callback always runs synchronously. Either call it directly or keepwithMapViewas a guard, but the "waits for the map view" part of the description isn't accurate.- The comment can be one sentence, e.g.
// Camera changes before JS registers for them are never sent, so send the current camera when it first does.The "as applyOnMapChange would" part goes away with the helper. - Android parity: the late-attach case has the same gap there (
setHandledMapChangedEventsonly stores the set). I'd prefer both platforms in this PR, since the change is small. Treat the initialnullset as already containingCAMERA_CHANGED, so the first registration doesn't resend the startup camera, which Android already delivers. Then emithandleMapChangedEvent(CAMERA_CHANGED)when it is newly added andREGION_IS_CHANGINGisn't registered.
Reproducer used (Late / Busy / Late+Region, Attach, Detach, Re-render x5, setCamera)
import React, { useLayoutEffect, useRef, useState } from 'react';
import { Button, Text, View } from 'react-native';
import { Camera, MapView } from '@rnmapbox/maps';
// Repro for rnmapbox/maps#4430: onCameraChanged gets no camera when it is registered after the
// start camera. The map is never touched unless "setCamera" is pressed.
const START = { centerCoordinate: [-74.00597, 40.71427], zoomLevel: 12 };
const BusyOnMount = () => {
// Delays MapView.componentDidMount (which registers the handled events) by 3 s of JS busy work.
useLayoutEffect(() => {
const end = Date.now() + 3000;
while (Date.now() < end) {}
}, []);
return null;
};
const fmt = (s) =>
s
? `z ${s.properties.zoom.toFixed(2)} c ${s.properties.center
.map((v) => v.toFixed(3))
.join(',')} gest ${s.gestures?.isGestureActive}`
: '-';
const Repro = ({ mode, onRegion }) => {
const t0 = useRef(Date.now());
const camera = useRef(null);
const [listening, setListening] = useState(mode === 'busy');
const [, setTick] = useState(0);
const [cam, setCam] = useState({ calls: 0, first: null, last: null, firstAt: 0 });
const [region, setRegion] = useState(0);
const [idle, setIdle] = useState(null);
const log = (kind, payload) =>
console.log(`[R4430] ${mode} +${Date.now() - t0.current}ms ${kind} ${JSON.stringify(payload)}`);
return (
<View style={{ flex: 1 }}>
<MapView
style={{ flex: 1 }}
// inline on purpose: a new function every render, so MapView re-registers events each render
onCameraChanged={
listening
? (s) => {
log('onCameraChanged', s);
setCam((c) => ({
calls: c.calls + 1,
first: c.first ?? s,
firstAt: c.first ? c.firstAt : Date.now() - t0.current,
last: s,
}));
}
: undefined
}
onRegionIsChanging={
onRegion
? (f) => {
log('onRegionIsChanging', f.properties);
setRegion((n) => n + 1);
}
: undefined
}
onMapIdle={(s) => {
log('onMapIdle', s);
setIdle(s);
}}
>
<Camera ref={camera} defaultSettings={START} />
{mode === 'busy' && <BusyOnMount />}
</MapView>
{/* fixed height: a map resize would itself be a camera change */}
<View style={{ height: 170 }}>
<Text testID="r-cam">{`${mode} listening=${listening} calls=${cam.calls} first@+${cam.firstAt}ms`}</Text>
<Text testID="r-first">{`first: ${fmt(cam.first)}`}</Text>
<Text testID="r-last">{`last: ${fmt(cam.last)}`}</Text>
<Text testID="r-idle">{`idle: ${fmt(idle)} region=${region}`}</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
<Button testID="r-attach" title="Attach" onPress={() => setListening(true)} />
<Button testID="r-detach" title="Detach" onPress={() => setListening(false)} />
<Button testID="r-rerender" title="Re-render x5" onPress={() => [1, 2, 3, 4, 5].forEach((i) => setTimeout(() => setTick((n) => n + 1), i * 100))} />
<Button testID="r-move" title="setCamera z14" onPress={() => camera.current?.setCamera({ zoomLevel: 14, animationDuration: 0 })} />
</View>
</View>
</View>
);
};
const CameraOnRegisterRepro = () => {
const [run, setRun] = useState({ key: 0, mode: 'late', onRegion: false });
const start = (mode, onRegion = false) => setRun((r) => ({ key: r.key + 1, mode, onRegion }));
return (
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', paddingTop: 4 }}>
<Button testID="r-late" title="Late" onPress={() => start('late')} />
<Button testID="r-busy" title="Busy" onPress={() => start('busy')} />
<Button testID="r-late-region" title="Late+Region" onPress={() => start('late', true)} />
</View>
<Repro key={run.key} mode={run.mode} onRegion={run.onRegion} />
</View>
);
};
export default CameraOnRegisterRepro;This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
On iOS,
MapViewsends camera changes to JS only after JS has asked for them (setHandledMapChangedEventsWithEvents, whichMapViewcalls fromcomponentDidMountand again when a callback prop changes). A camera change before that is never sent, and nothing sends the camera afterwards. So when JS asks late,onCameraChangedgets no camera until the map moves:componentDidMount(timing-dependent; we hit it every time in our app's map screen, which mounts many layers);onCameraChangedis set after the map has settled (always).onMapIdlestill reports the right camera, so an app that keeps the camera fromonCameraChangeddisagrees with the map until the user touches it.This PR: when
.cameraChangedis newly in the handled set, send the current camera once, asapplyOnMapChangewould (not when.regionIsChangingis registered, which takes precedence there). It goes throughwithMapView, so it waits for the map view. Registering the same set again (MapViewdoes that on every render with an inline callback) sends nothing.Android is not changed. There the handled set starts as
null, so camera changes before the first registration are sent; a listener added later gets no camera until the map moves there too (from readingRNMBXMapView.kt, not run). I can add the same one-shot on Android if you want both to behave the same. #4426 fixes the Android start-camera loss from the 10 ms drop.Checklist
CONTRIBUTING.mdyarn generatein the root folder (no changes)/exampleapp./example)Screenshot OR Video
The reproducer below in the example app (
mainat 47a736a, React Native 0.84.1, New Architecture, Mapbox 11.33.0), iOS 26.5 simulator (iPhone 16). The map opens at zoom 12 and is never touched; each run is a fresh app launch.main'busy'(JS busy 3 s while the map mounts), 10 runs: noonCameraChangedat all'late'(onCameraChangedset at the first idle), 3 runs:onCameraChangedcallsIn every run
onMapIdlereported zoom 12.00. Without the busy child the start camera usually comes aftercomponentDidMount, which is why the'busy'case is timing-dependent; in one run with this PR the one-shot carried the map's first camera (zoom 0.47) and the start camera followed as a normal change. The text area has a fixed height: text that grows would resize the map, and a resize is a camera change of its own.Component to reproduce the issue you're fixing
BugReportExample.js — 'busy' and 'late' modes, counts onCameraChanged for a map that is never moved
🤖 Generated with Claude Code