React Native Geolocation Works in Emulator but Fails on Real Device in React Native App

Title: React Native Geolocation not working on Android device, but works on emulator

I’m having trouble getting geolocation to work in my React Native app on Android. The problem occurs when I build the APK and install it on a real device. It’s not fetching the location latitude and longitude(Given the app permission of location). However, if I install the APK on any emulator, it works fine. Can anyone suggest what might be causing this issue?

Here’s the relevant code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import Geolocation from '@react-native-community/geolocation';
const [location, setLocation] = useState(null);
const [isLoadingLocation, setIsLoadingLocation] = useState(false);
const requestLocationPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'This app needs access to your location for attendance tracking.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn('Permission request error:', err);
return false;
}
}
return true;
};
const checkLocationPermission = async () => {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
return granted;
}
return true; // For iOS, permissions are handled differently
};
const getLocation = useCallback(async () => {
setErrorMsg(null);
const hasPermission = await checkLocationPermission();
if (!hasPermission) {
const retry = await requestLocationPermission(); // Prompt for permission
if (!retry) {
Alert.alert(
'Error',
'Location permission denied. Please enable it in settings.',
[{ text: 'OK' }]
);
return; // Exit if permission is denied
}
}
Geolocation.getCurrentPosition(
position => {
const loc = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
};
console.log('Location obtained:', loc);
setLocation(loc);
},
error => {
console.log('GeolocationError:', error);
setErrorMsg('Error getting location');
Alert.alert('Error', `Error getting location: ${error.message}`);
},
{
enableHighAccuracy: false,
timeout: 20000,
maximumAge: 1000,
},
);
}, []);
useEffect(() => {
const fetchLocation = async () => {
try {
await getLocation();
} catch (error) {
console.error('Error fetching location on mount:', error);
}
};
fetchLocation();
}, [getLocation]);
</code>
<code>import Geolocation from '@react-native-community/geolocation'; const [location, setLocation] = useState(null); const [isLoadingLocation, setIsLoadingLocation] = useState(false); const requestLocationPermission = async () => { if (Platform.OS === 'android') { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Location Permission', message: 'This app needs access to your location for attendance tracking.', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } catch (err) { console.warn('Permission request error:', err); return false; } } return true; }; const checkLocationPermission = async () => { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION); return granted; } return true; // For iOS, permissions are handled differently }; const getLocation = useCallback(async () => { setErrorMsg(null); const hasPermission = await checkLocationPermission(); if (!hasPermission) { const retry = await requestLocationPermission(); // Prompt for permission if (!retry) { Alert.alert( 'Error', 'Location permission denied. Please enable it in settings.', [{ text: 'OK' }] ); return; // Exit if permission is denied } } Geolocation.getCurrentPosition( position => { const loc = { latitude: position.coords.latitude, longitude: position.coords.longitude, }; console.log('Location obtained:', loc); setLocation(loc); }, error => { console.log('GeolocationError:', error); setErrorMsg('Error getting location'); Alert.alert('Error', `Error getting location: ${error.message}`); }, { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, }, ); }, []); useEffect(() => { const fetchLocation = async () => { try { await getLocation(); } catch (error) { console.error('Error fetching location on mount:', error); } }; fetchLocation(); }, [getLocation]); </code>
import Geolocation from '@react-native-community/geolocation';

const [location, setLocation] = useState(null);
const [isLoadingLocation, setIsLoadingLocation] = useState(false);

const requestLocationPermission = async () => {
  if (Platform.OS === 'android') {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          title: 'Location Permission',
          message: 'This app needs access to your location for attendance tracking.',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        }
      );
      return granted === PermissionsAndroid.RESULTS.GRANTED;
    } catch (err) {
      console.warn('Permission request error:', err);
      return false;
    }
  }
  return true;
};

const checkLocationPermission = async () => {
  if (Platform.OS === 'android') {
    const granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
    return granted;
  }
  return true; // For iOS, permissions are handled differently
};

const getLocation = useCallback(async () => {
  setErrorMsg(null);
  const hasPermission = await checkLocationPermission();
  if (!hasPermission) {
    const retry = await requestLocationPermission(); // Prompt for permission
    if (!retry) {
      Alert.alert(
        'Error',
        'Location permission denied. Please enable it in settings.',
        [{ text: 'OK' }]
      );
      return; // Exit if permission is denied
    }
  }
  Geolocation.getCurrentPosition(
    position => {
      const loc = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      };
      console.log('Location obtained:', loc);
      setLocation(loc);
    },
    error => {
      console.log('GeolocationError:', error);
      setErrorMsg('Error getting location');
      Alert.alert('Error', `Error getting location: ${error.message}`);
    },
    {
      enableHighAccuracy: false,
      timeout: 20000,
      maximumAge: 1000,
    },
  );
}, []);

useEffect(() => {
  const fetchLocation = async () => {
    try {
      await getLocation();
    } catch (error) {
      console.error('Error fetching location on mount:', error);
    }
  };
  fetchLocation();
}, [getLocation]);

What I tried:

Set up geolocation using @react-native-community/geolocation in my React Native app.
Implemented Android permission handling (both checking and requesting).
Wrote a getLocation function to fetch the current position.
Used useEffect to call this function when the component mounts.
Built the APK and tested on both an Android emulator and my actual Android phone.

What I expected:

The app to work just as well on my real Android device as it did on the emulator.
To see those latitude and longitude numbers pop up on my phone screen.

What actually happened:

On the Android emulator: It’s all good! Location fetched and displayed perfectly.
On my real Android device: Total letdown. No location data at all.
Instead, I’m getting this frustrating “Error getting location” message.(But at emulator its showing no problem)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật