Anjali
Anjali

Reputation: 2698

How to import geolib in React Native to calculate the distance between two points?

I need to calculate the distance between Longitude and Latitude in react native. I have the Longitude and Latitude of my current location and I have the Longitude and Latitude of my destination. Is their any easy way to calculate the distance?

I tried using geolib, but keep getting an error. Below is what I did:

npm i geolib

I put the geolib in my import statement too.

  import {
    AppRegistry,
    StyleSheet,
    FlatList,
    Text,
    View,
    Alert,
    TouchableOpacity,
    Linking,
    Image,
    ScrollView,
    RefreshControl,
    Location,
    geolib
  } from 'react-native';

 _renderItem = ({item, index}) => {

    var dist  = geolib.getDistance(
      this.state.latitude,
      this.state.longitude,
      item.LatL,
      item.Long2
    );

    return (
      <View>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>Latitude from file:{item.LatL}</Text>
        <Text>Longitude from file :{item.Long2} </Text>
        <Text style={styles.AddressSpace} >Miles:{dist }</Text>
      </View>
    );

Below is the error that I am getting:

TypeError: undefined is not an object
(evaluating '_reactNative.geolib.getDistance')

[![enter image description here][1]][1]

I am getting this error as soon as I put this code:

   const dist = geolib.getDistance(
      { latitude, longitude },{ latitude: item.LatL, longitude: item.Long2 }
    );

enter image description here

Not sure, but I am still getting the above error: Below is my entire code:

 import React, { Component } from 'react';
import { View, Text, item } from 'react-native';
import geolib from 'geolib';
class ServiceListDetails 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: true, timeout: 20000, maximumAge: 1000 },
    );
  }

  render() {
    const { latitude, longitude } = this.state;

    const dist = geolib.getDistance(
  { latitude, longitude },
  { latitude: 33.935558, longitude: -117.284912 }
);
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        <Text>Miles:{dist} </Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

export default ServiceListDetails;

_  [1]: https://i.sstatic.net/8VadZ.png

Upvotes: 3

Views: 9667

Answers (2)

dan674
dan674

Reputation: 2127

Try:

import { getDistance } from "geolib"

and then using:

const dist = getDistance(...)

I had a similar issue with computeDestinationPoint(...)

Upvotes: 2

Emile Bergeron
Emile Bergeron

Reputation: 17430

geolib doesn't exist as a named export in react-native.

import {
  AppRegistry,
  StyleSheet,
  FlatList,
  Text,
  View,
  Alert,
  TouchableOpacity,
  Linking,
  Image,
  ScrollView,
  RefreshControl,
  Location
  // Remove `geolib` from here.
} from 'react-native';

// Import the lib from the one you've just installed.
import geolib from 'geolib';

It helps to know how the import and export works in ES6 to be able to use all the libs you want and structure your own code in independent module files.

Then, to get the distance between two points with Geolib, you need to use the getDistance function, which takes 2 objects as parameters.

// Function signature from the documentation:
geolib.getDistance(object start, object end[, int accuracy, int precision])

In your case:

// Using destructuring here just to avoid repetition.
const { latitude, longitude } = this.state;

const dist = geolib.getDistance(
  { latitude, longitude },
  { latitude: item.LatL, longitude: item.Long2 }
);

Also note that:

Return value is always float and represents the distance in meters.

To convert it to miles, you could multiply the result by 0.000621.

<Text style={styles.AddressSpace}>Miles: {dist * 0.000621}</Text>

Ideally, I would put the 0.000621 magic number inside a clearly defined constant somewhere.

Or just use the geolib.convertUnit function.

<Text style={styles.AddressSpace}>Miles: {geolib.convertUnit('mi', dist)}</Text>

Upvotes: 3

Related Questions