user54967
user54967

Reputation: 25

calculating distance in React Native

I want to get the distance from my current location to destination. I do have the Longitude and latitude of the destination in my JSON file. How can I get the longitude and latitude of my current location so that I can calculate the distance between two points? I tried the code below in my android emulator, but I keep getting the time out issues.

    import React, { Component } from 'react';
import { View, Text } from 'react-native';

class GeolocationExample extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
    );
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

export default GeolocationExample;

I just want to get the distance from the current location to destination in miles. How can I achieve that? Below is the screen along with the error enter image description herethat I am getting :

Upvotes: 2

Views: 3877

Answers (2)

Shivam
Shivam

Reputation: 3131

Adding another answer as its the best solution to the problem. As a solution to the location timeout issue i am using react-native-geolocation-service and it works like a charm.

This library has been created to fix the location timeout issue on android with the react-native's current implementation of Geolocation API. This library tries to solve the issue by using Google Play Service's new FusedLocationProviderClient API, which Google strongly recommends over android's default framework location API.

Upvotes: 2

Shivam
Shivam

Reputation: 3131

Today I faced the same issue, What I found is, If you execute tests "inside your office" using physical device, the GPS locator can be disturbed by external things like walls, or by the simple reason that you are trying to do this operation "indoor" and, generally, this should be executed outdoor.

My suggestion is: try geolocation using enableHighAccuracy set to true, if this fail with location request timed out error (in the office this can fail), retry with false, this should work, in my case it did.

Hope this will help you.

Upvotes: 2

Related Questions