React Native使用GeoLib计算坐标距离遇两类问题求助
Hey Anjali, let's tackle these two issues one by one—they're both pretty common with React Native location handling, so I've got some solid fixes for you!
This issue usually happens because the location request isn't properly reinitialized or permission checks are skipped when the screen reloads. Here's how to fix it:
Recheck permissions on component mount
Screen reloads trigger a re-mount, so you need to re-verify location permissions every time the component loads, not just on first app launch. UsePermissionsAndroidto handle this:import { PermissionsAndroid } from 'react-native'; const requestLocationAccess = async () => { try { const permissionGranted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: "Location Access Needed", message: "This app requires your location to display your current position.", buttonPositive: "Allow", buttonNegative: "Cancel" } ); return permissionGranted === PermissionsAndroid.RESULTS.GRANTED; } catch (err) { console.warn("Permission request failed:", err); return false; } };Then tie this to a
useEffectthat runs on mount (and reload):useEffect(() => { const fetchCurrentLocation = async () => { const hasPermission = await requestLocationAccess(); if (!hasPermission) return; navigator.geolocation.getCurrentPosition( (pos) => { console.log("Latitude:", pos.coords.latitude, "Longitude:", pos.coords.longitude); // Update your state with the coordinates here }, (error) => console.error("Location error:", error.message), { timeout: 20000, maximumAge: 1000, enableHighAccuracy: false } ); }; fetchCurrentLocation(); // Cleanup: Remove location watcher to prevent memory leaks return () => navigator.geolocation.clearWatch(watchId); }, []);Tweak location request parameters
Increase thetimeoutvalue (to 20 seconds in the example above) to give the system more time to fetch coordinates. SettingmaximumAge: 1000allows using cached location data, which speeds up requests on reload. You can also setenableHighAccuracy: falseif you don't need pinpoint accuracy—this reduces load time.Verify AndroidManifest.xml permissions
Double-check that these permissions are added to yourandroid/app/src/main/AndroidManifest.xml:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Path errors here almost always stem from incorrect imports, misformatted coordinates, or cached module issues. Let's break down the fixes:
Confirm correct installation and import
First, make sure you've installed the right package and imported it properly:# Install the official geolib package npm install geolib --saveThen import the method correctly (avoid relative paths or typos):
import { getDistance } from 'geolib';If you're using
react-native-geolib, adjust the import to:import Geolib from 'react-native-geolib';Ensure coordinates are in the right format
GeoLib'sgetDistanceexpects objects withlatitudeandlongitudekeys. If your coordinates are stored as arrays or other formats, convert them first:// Correct format const locationA = { latitude: 51.5074, longitude: -0.1278 }; const locationB = { latitude: 40.7128, longitude: -74.0060 }; // Calculate distance (returns value in meters) const distance = getDistance(locationA, locationB); console.log("Distance:", distance);Clear React Native cache
Cached modules can cause path mismatches. Reset the cache and rebuild your app:npx react-native start --reset-cache npx react-native run-android
内容的提问来源于stack exchange,提问作者Anjali

