You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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!


1. Fixing the "Location Request timed out" Error on Screen Reload

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. Use PermissionsAndroid to 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 useEffect that 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 the timeout value (to 20 seconds in the example above) to give the system more time to fetch coordinates. Setting maximumAge: 1000 allows using cached location data, which speeds up requests on reload. You can also set enableHighAccuracy: false if you don't need pinpoint accuracy—this reduces load time.

  • Verify AndroidManifest.xml permissions
    Double-check that these permissions are added to your android/app/src/main/AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    

2. Fixing GeoLib Path Errors When Calculating Distance

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 --save
    

    Then 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's getDistance expects objects with latitude and longitude keys. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:14