React Native中计算当前位置与目的地距离的问题
Hey there! Let's work through your two key problems step by step: fixing the geolocation timeout in the Android emulator, and calculating the mile distance between your current location and your destination.
The timeout issue you're seeing is super common with Android emulators—they don't have real GPS hardware, so we need to set up simulated location data and tweak a few settings:
Add required permissions first
Open your project'sandroid/app/src/main/AndroidManifest.xmland add these permissions above the<application>tag:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />Without these, your app can't request location data at all.
Simulate a location in the emulator
- Launch your Android emulator, then click the "Location" icon in the right-side toolbar (if you don't see it, go to
More > Location). - Enter a test latitude and longitude (e.g.,
37.7749, -122.4194for San Francisco) and click "Send". This feeds fake GPS data to your app.
- Launch your Android emulator, then click the "Location" icon in the right-side toolbar (if you don't see it, go to
Tweak your geolocation code
getCurrentPositioncan be flaky in emulators. Try usingwatchPositioninstead—it listens for location updates and stops once it gets a valid reading:componentDidMount() { const watchId = navigator.geolocation.watchPosition( (position) => { this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude, error: null, }); // Stop listening once we have the location navigator.geolocation.clearWatch(watchId); }, (error) => this.setState({ error: error.message }), { enableHighAccuracy: false, timeout: 15000, maximumAge: 30000 }, ); }Lowering the timeout slightly and increasing maximumAge can also help with emulator latency.
Check Google Play Services
Make sure your emulator has updated Google Play Services—outdated versions often cause location bugs. You can update it via the emulator's Play Store app.
Once you have both your current coordinates and the destination coordinates, use the Haversine formula to calculate the spherical distance between them, then convert kilometers to miles.
Add these helper methods to your component:
// Convert degrees to radians (required for the formula) deg2rad(deg) { return deg * (Math.PI / 180); } // Calculate distance in miles between two coordinate pairs calculateMileDistance(lat1, lon1, lat2, lon2) { const earthRadiusKm = 6371; // Earth's radius in kilometers const dLat = this.deg2rad(lat2 - lat1); const dLon = this.deg2rad(lon2 - lon1); const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); const kmDistance = earthRadiusKm * c; // Convert km to miles (1 km = 0.621371 miles) return kmDistance * 0.621371; }
Then, use this method once you have all coordinates. For example, update your state to include destination coordinates, then calculate the distance in componentDidUpdate or when you fetch the JSON data:
// Example: Assume you have destination coords stored in state componentDidUpdate(prevProps, prevState) { // Only calculate if coordinates have changed if ( this.state.latitude !== prevState.latitude && this.state.longitude !== prevState.longitude && this.state.destLatitude && this.state.destLongitude ) { const distance = this.calculateMileDistance( this.state.latitude, this.state.longitude, this.state.destLatitude, this.state.destLongitude ); this.setState({ distance: distance.toFixed(2) }); // Round to 2 decimal places } }
Finally, add a text element in your render method to display the distance:
{this.state.distance && ( <Text>Distance to destination: {this.state.distance} miles</Text> )}
内容的提问来源于stack exchange,提问作者user54967

