How to zoom in/out in react-native-map?
This is what I did and it worked out for me very well:
function getRegion(origin, destination, zoom) {
const oLat = Math.abs(origin.latitude);
const oLng = Math.abs(origin.longitude);
const dLat = Math.abs(destination.latitude);
const dLng = Math.abs(destination.longitude);
return {
latitude: (origin.latitude + destination.latitude) / 2,
longitude: (origin.longitude + destination.longitude) / 2,
latitudeDelta: Math.abs(oLat - dLat) + zoom,
longitudeDelta: Math.abs(oLng - dLng) + zoom,
};
}
New React Native Maps API gives you option to call animateCamera
method with zoom
parameter.
const MapComponent= (props: any) => {
const map: LegacyRef<MapView> = useRef(null);
const onZoomInPress = () => {
map?.current?.getCamera().then((cam: Camera) => {
cam.zoom += 1;
map?.current?.animateCamera(cam);
});
};
return (
<View>
<MapView
ref={map}
provider={PROVIDER_GOOGLE}
region={region}>
</MapView>
<ButtonComponent
style={{position: 'absolute', bottom: 400, left: 0}}
onPress={onZoomInPress}>
Zoom In
</MainButtonBlue>
</View>
);
}
I was able to make this work using Dimensions.get('window');
const window = Dimensions.get('window');
const { width, height } = window
LONGITUDE_DELTA = LATITUD_DELTA + (width / height)
and by default set LATITUD_DELTA = 0.0922
.
Then just update this values with the prop onRegionChangeComplete
in the <MapView>
You should use the animateToRegion
method (see here)
It takes a region object which has latitudeDelta
and longitudeDelta
. Use these to set the zoom level.
Updated:
in a Region
object the latitude
and longitude
specify the center location and latitudeDelta
and longitudeDelta
specify the span of the viewable map area.
This image from this blog post illustrates it well (LatΔ and LngΔ).