3

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.stack.imgur.com/8VadZ.png
Anjali
  • 2,540
  • 7
  • 37
  • 77

2 Answers2

3

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>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • I am getting the above error: TypeError: null is not an object. I pasted the phone picture above. Is it possible that Longitude and latitude are becoming null. – Anjali May 01 '19 at 18:07
  • @Anjali notice the destructuring I'm doing with `this.state`. – Emile Bergeron May 01 '19 at 18:46
  • Hi Emile, Not sure what am I doing wrong, but I am still getting the above error TypeError: null is not an object. I pasted my code above at the end of my post. Your help will be greatly appreciated. – Anjali May 01 '19 at 20:35
  • @Anjali maybe you're passing null somewhere as a long or lat, I don't know, I'm not using either geolib nor your code. It's now your job to debug and see what's going on. You're already on the right track since now the error comes from Geolib. – Emile Bergeron May 01 '19 at 20:52
  • I put the code of my entire page. Still getting the error. Can you please look at the code. As soon as I remove the line const dist = geolib.getDistance( { latitude, longitude }, { latitude: 33.935558, longitude: -117.284912 } ); error stops coming. – Anjali May 01 '19 at 22:08
  • Finally, figured out what I was doing wrong. Thank you for all your help. – Anjali May 26 '19 at 09:05
2

Try:

import { getDistance } from "geolib"

and then using:

const dist = getDistance(...)

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

dan674
  • 1,848
  • 2
  • 15
  • 21