'Why the onPress button doesn't send me to my current location?

What I'm trying to do is when the user clicks the position button in the map, to go to the user current location. For the location I'm using import * as Location from 'expo-location';

import React, { useState, useEffect } from 'react';
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
import { StyleSheet, Image, Text, View } from 'react-native';
import * as Location from 'expo-location';
import { MaterialIcons } from '@expo/vector-icons';
import { LocationView, LocationBtn } from '../components/styles';

function Map(props) {
  const [mapRegion, setMapRegion] = useState(null);
  useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }

      const location = await Location.getCurrentPositionAsync({});
      setMapRegion({
        longitude: location.coords.longitude,
        latitude: location.coords.latitude,
        longitudeDelta: 0.0922,
        latitudeDelta: 0.0421,
      });
      console.log('location', location);
    })();
  }, []);

  return (
    <View style={{ flex: 1 }}>
      <MapView
        provider={PROVIDER_GOOGLE}
        style={styles.map}
        mapType={props.mapType}
        // showsUserLocation={true}
        loadingEnabled
        initialRegion={mapRegion}
        userInterfaceStyle="light"
        showsTraffic
      >
        <Marker coordinate={mapRegion}>
          <Image source={require('../assets/marker.png')} style={{ height: 90, width: 90 }} />
        </Marker>
      </MapView>
      <LocationView>
        <LocationBtn onPress={() => mapRegion}>
          <MaterialIcons name="my-location" size={30} color="black" style={{ alignSelf: 'center', marginTop: 13 }} />
        </LocationBtn>
      </LocationView>
    </View>
  );
}

const styles = StyleSheet.create({
  map: {
    height: '100%',
  },
});

export default Map;

By far I have put mapRegion state which it have the current location. When I press the button, it doesn't work.



Solution 1:[1]

What do you mean by going to the user location? Looking at your code, you're saving your coordinates to the mapRegion state.

The onPress prop of LocationBtn has () => mapRegion which does nothing. It's just a function that has mapRegion return value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1