How to Zoom in/Out in React Native with a onPress button?

Viewed 165

Hi everybody newbie here,

First of all thank you in advance if you are reading this! Im using React Native with Google maps API and Expo. My problem is the following:

Whenever I click on "StartRoute:, the page refreshes and it shows me the route. All fine. But the map is still zoomed out. I want the map to zoom in automatically whenever I click on this button.

import {Platform, Text, View, StyleSheet, Dimensions, Image, Button, Pressable, SafeAreaView} from 'react-native';
import * as Location from 'expo-location';
import MapView, {Callout, Circle, Marker,AnimatedRegion} from "react-native-maps";
import {locations} from "./POIdata";
import POIRoute from "./POIRoute";
import {createStackNavigator} from '@react-navigation/stack';
import WiggleBox from "react-native-wiggle-box";
import Tabs from "./tabs";
import * as TaskManager from "expo-task-manager";
import {LocationGeofencingEventType, LocationGeofencingRegionState} from "expo-location";
import Geofencing from "./Geofencing";
import { regions } from './Regions';

export default function Map({navigation: {navigate}}) {

    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [marginBottom, setMarginBottom] = useState(1)
    const [paddingTop, setPaddingTop] = useState(1)
    const [routeShow, setRouteShow] = useState(false);
    const [buttonSelectRoute, setButtonSelectRoute] = useState(true);
    const [buttonStartRoute, setButtonStartRoute] = useState(false);
    


    const _onMapReady = function () {
        setMarginBottom(0)
        setPaddingTop(0)
    }


    const onSelectRoute = function () {
        setRouteShow(true)
        setButtonStartRoute(true)
        setButtonSelectRoute(false)

    }

    const onStartRoute = function () {
        setButtonStartRoute(false) 
        console.log("inzoom op locatie nog maken (Twan)")
    }

    useEffect(() => {
        (async () => {
            let {status} = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                setErrorMsg('Permission to access location was denied');
                return;
            }

            let location = await Location.getCurrentPositionAsync({});
            setLocation(location);
        })();

    }, []);

    let mapRegion = {
        latitude: 52.2210452,
        longitude: 5.1597742,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
    }


    let text = 'Waiting..';
    if (errorMsg) {
        console.log("location not found...");
    } else if (location) {
        text = JSON.stringify(location);
        mapRegion = {
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
        };
    }



return (

    <SafeAreaView style={styles.container}>
        {buttonSelectRoute ? (
            <Pressable style={styles.SelectRoutebutton} onPress={() => onSelectRoute()}>
                {/*<WiggleBox*/}
                {/*    active={true}*/}
                {/*    duration={800}*/}
                {/*    type={'wiggle'}*/}
                {/*>*/}
                    <Text style={styles.text} onPress={() => onSelectRoute()}> Selecteer een route </Text> 
                {/*</WiggleBox>*/}
            </Pressable>
        ) : null}
        {buttonStartRoute ? (
            <Pressable style={styles.StartRoutebutton} onPress={() => onStartRoute()}> +
                {/*<WiggleBox*/}
                {/*    active={true}*/}
                {/*    duration={800}*/}
                {/*    type={'wiggle'}*/}
                {/*>*/}
                    <Text onPress={() => onStartRoute()} style={styles.text}> Start de route! </Text>
                {/*</WiggleBox>*/}
            </Pressable>
        ) : null}
1 Answers

latitudeDelta and longitudeDelta control how zoomed-in your map is. The lower the number, the more zoomed in. So you would want to make your mapRegion object dynamic.

I would make mapRegion a useState hook:

const [mapRegion, setMapRegion] = useState({
        latitude: 52.2210452,
        longitude: 5.1597742,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
})

Then, whenever you need to adjust it, just call setMapRegion, perhaps in your location if/else:

setMapRegion({
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
})

...Except use lower latitudeDelta and longitudeDelta numbers. You would probably want to experiment with different numbers and see what suit your needs.

EDIT:

Sorry, forgot to mention that you need to put setMapRegion({}) into your onStartRoute function.

Try something like this:

setMapRegion({
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
            latitudeDelta: 0.025,
            longitudeDelta: 0.025,
})

I'm new at this as well. Hope my response helps.

Related